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
madpilot78/ntopng
scripts/lua/please_wait.lua
1
3241
-- -- (C) 2013-21 - ntop.org -- dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path -- io.write ("Session:".._SESSION["session"].."\n") require "lua_utils" local page_utils = require("page_utils") sendHTTPContentTypeHeader('text/html') page_utils.print_header_minimal() local prefs = ntop.getPrefs() local dbname = (prefs.mysql_dbname or '') -- read the db activities to notify the user about what is going on in the database local res = ntop.execSingleSQLQuery("show full processlist") print [[ <div class="container-narrow"> <style type="text/css"> body { padding-top: 40px; padding-bottom: 40px; background-color: #f5f5f5; } .please-wait { max-width: 600px; padding: 9px 29px 29px; margin: 0 auto 20px; background-color: #fff; border: 1px solid #e5e5e5; -webkit-border-radius: 5px; -moz-border-radius: 5px; border-radius: 5px; -webkit-box-shadow: 0 1px 2px rgba(0,0,0,.05); -moz-box-shadow: 0 1px 2px rgba(0,0,0,.05); box-shadow: 0 1px 2px rgba(0,0,0,.05); } .please-wait .please-wait-heading, </style> <div class="container please-wait"> <div style="text-align: center; vertical-align: middle"> ]] addLogoSvg() print[[ </div> <div> <br> ]] print(" "..i18n("please_wait_page.waiting_for_db_msg", {dbname=dbname})) print[[ </div> <br> <div>]] if res == nil then res = {} end if #res >= 1 then print[[ <br> ]] print(i18n("please_wait_page.operations_on_database_msg")) print [[ <small> <br><br> <table class="table table-bordered table-striped" width=100%> <thead> <tr> <th>]] print(i18n("please_wait_page.database")) print[[</th><th>]] print(i18n("please_wait_page.state")) print[[</th><th>]] print(i18n("please_wait_page.command")) print[[</th><th>]] print(i18n("please_wait_page.id")) print[[</th><th>]] print(i18n("please_wait_page.user")) print[[</th><th>]] print(i18n("please_wait_page.time")) print[[</th><th>]] print(i18n("please_wait_page.info")) print[[</th><th>]] print(i18n("please_wait_page.host")) print[[</th> </tr> </thead> <tbody> ]] for i,p in ipairs(res) do if p["Command"] ~= "Sleep" then print('<tr>') print('<td>'..(p["db"] or '')..'</td><td>'..(p["State"] or '')..'</td><td>'..(p["Command"] or '')..'</td><td>'..(p["Id"] or '')..'</td>') print('<td>'..(p["User"] or '')..'</td><td>'..secondsToTime(tonumber((p["Time"] or '')))..'</td>') print('<td title="'..(p["Info"] or '')..'">'..shortenString((p["Info"] or ''))..'</td><td>'..(p["Host"] or '')..'</td>') print('</tr>') local msg = "" for k, v in pairs(p) do msg = msg..k..": "..v.." " end end end print[[ </tbody> </table> </small> ]] end local host if not isEmptyString(_GET["referer"]) then host = getHttpUrlPrefix().._GET["referer"] else host = _SERVER["HTTP_HOST"] .. ntop.getHttpPrefix() .. "/lua/index.lua" end print[[</div> </div> <!-- /container --> <script type="text/javascript"> var intervalID = setInterval( function() { window.location.replace("]] print(host) print[["); }, 5000); </script> </body> </html> ]]
gpl-3.0
madpilot78/ntopng
scripts/lua/rest/v1/get/host/alert/ts.lua
2
1241
-- -- (C) 2013-21 - ntop.org -- local dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path package.path = dirs.installdir .. "/scripts/lua/modules/alert_store/?.lua;" .. package.path local auth = require "auth" local alert_utils = require "alert_utils" local alert_consts = require "alert_consts" local alert_entities = require "alert_entities" local rest_utils = require("rest_utils") local host_alert_store = require "host_alert_store".new() local alert_severities = require "alert_severities" -- -- Read alerts count by time -- Example: curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "1"}' http://localhost:3000/lua/rest/v1/get/host/alert/ts.lua -- -- NOTE: in case of invalid login, no error is returned but redirected to login -- local rc = rest_utils.consts.success.ok if not auth.has_capability(auth.capabilities.alerts) then rest_utils.answer(rest_utils.consts.err.not_granted) return end local ifid = _GET["ifid"] if isEmptyString(ifid) then rc = rest_utils.consts.err.invalid_interface rest_utils.answer(rc) return end interface.select(ifid) local res = host_alert_store:count_by_severity_and_time_request() rest_utils.answer(rc, res)
gpl-3.0
salehvw0011/stfbot
plugins/FileManager.lua
7
1132
local function savefile(extra, success, result) local msg = extra.msg local name = extra.name local adress = extra.adress local receiver = get_receiver(msg) if success then local file = './'..adress..'/'..name..'' print('File saving to:', result) os.rename(result, file) print('File moved to:', file) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function run(msg,matches) local receiver = get_receiver(msg) local group = msg.to.id if msg.reply_id then local adress = matches[2] local name = matches[3] if matches[1]:lower() == "file" and matches[2] and matches[3] and is_sudo(msg) then load_document(msg.reply_id, savefile, {msg=msg,name=name,adress=adress}) return 'File '..name..' has been saved in: \n./'..adress end if not is_sudo(msg) then return "just sudo!" end end end return { usage = { sudo = { "/file [folder] [file.format]: upload file to serve" }, }, patterns = { "^[!/#]([Ff]ile) (.*) (.*)$", }, run = run, }
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/RuLude_Gardens/npcs/Neraf-Najiruf.lua
1
2017
----------------------------------- -- Area: Ru'Lud Gardens -- NPC: Neraf-Najiruf -- Involved in Quests: Save my Sister -- @zone 243 -- @pos -36 2 60 ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/globals/quests"] = nil; require("scripts/globals/quests"); package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) saveMySister = player:getQuestStatus(JEUNO,SAVE_MY_SISTER); if(saveMySister == QUEST_AVAILABLE and player:getVar("saveMySisterVar") == 3) then player:startEvent(0x0062); -- Real start of this quest (with addquest) elseif(saveMySister == QUEST_ACCEPTED) then player:startEvent(0x0063); -- During quest elseif(saveMySister == QUEST_COMPLETED and player:hasKeyItem(DUCAL_GUARDS_LANTERN) == true) then player:startEvent(0x0061); -- last CS (after talk with baudin) else player:startEvent(0x009C); -- 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 == 0x0062) then player:addQuest(JEUNO,SAVE_MY_SISTER); player:setVar("saveMySisterVar", 0); player:addKeyItem(DUCAL_GUARDS_LANTERN); player:messageSpecial(KEYITEM_OBTAINED,DUCAL_GUARDS_LANTERN); elseif(csid == 0x0061) then player:delKeyItem(DUCAL_GUARDS_LANTERN); player:setVar("saveMySisterFireLantern", 0); end end;
gpl-3.0
vince06fr/prosody-modules
mod_data_access/mod_data_access.lua
32
4906
-- HTTP Access to datamanager -- By Kim Alvefur <zash@zash.se> local t_concat = table.concat; local t_insert = table.insert; local jid_prep = require "util.jid".prep; local jid_split = require "util.jid".split; local test_password = require "core.usermanager".test_password; local is_admin = require "core.usermanager".is_admin local dm_load = require "util.datamanager".load; local dm_store = require "util.datamanager".store; local dm_list_load = require "util.datamanager".list_load; local dm_list_store = require "util.datamanager".list_store; local dm_list_append = require "util.datamanager".list_append; local b64_decode = require "util.encodings".base64.decode; local saslprep = require "util.encodings".stringprep.saslprep; local realm = module:get_host() .. "/" .. module:get_name(); module:depends"http"; local encoders = { lua = require "util.serialization".serialize, json = require "util.json".encode }; local decoders = { lua = require "util.serialization".deserialize, json = require "util.json".decode, }; local content_type_map = { ["text/x-lua"] = "lua"; lua = "text/x-lua"; ["application/json"] = "json"; json = "application/json"; } local function require_valid_user(f) return function(event, path) local request = event.request; local response = event.response; local headers = request.headers; if not headers.authorization then response.headers.www_authenticate = ("Basic realm=%q"):format(realm); return 401 end local from_jid, password = b64_decode(headers.authorization:match"[^ ]*$"):match"([^:]*):(.*)"; from_jid = jid_prep(from_jid); password = saslprep(password); if from_jid and password then local user, host = jid_split(from_jid); local ok, err = test_password(user, host, password); if ok and user and host then return f(event, path, from_jid); elseif err then module:log("debug", "User failed authentication: %s", err); end end return 401 end end local function handle_request(event, path, authed_user) local request, response = event.request, event.response; --module:log("debug", "spliting path"); local path_items = {}; for i in string.gmatch(path, "[^/]+") do t_insert(path_items, i); end --module:log("debug", "split path, got %d parts: %s", #path_items, table.concat(path_items, ", ")); local user_node, user_host = jid_split(authed_user); if #path_items < 3 then --module:log("debug", "since we need at least 3 parts, adding %s/%s", user_host, user_node); t_insert(path_items, 1, user_node); t_insert(path_items, 1, user_host); --return http_response(400, "Bad Request"); end if #path_items < 3 then return 404; end local p_host, p_user, p_store, p_type = unpack(path_items); if not p_store or not p_store:match("^[%a_]+$") then return 404; end if user_host ~= path_items[1] or user_node ~= path_items[2] then -- To only give admins acces to anything, move the inside of this block after authz --module:log("debug", "%s wants access to %s@%s[%s], is admin?", authed_user, p_user, p_host, p_store) if not is_admin(authed_user, p_host) then return 403; end end local method = request.method; if method == "GET" then local data = dm_load(p_user, p_host, p_store); data = data or dm_list_load(p_user, p_host, p_store); --TODO Use the Accept header local content_type = p_type or "json"; if data and encoders[content_type] then response.headers.content_type = content_type_map[content_type].."; charset=utf-8"; return encoders[content_type](data); else return 404; end elseif method == "POST" or method == "PUT" then local body = request.body; if not body then return 400; end local content_type, content = request.headers.content_type, body; content_type = content_type and content_type_map[content_type] --module:log("debug", "%s: %s", content_type, tostring(content)); content = content_type and decoders[content_type] and decoders[content_type](content); --module:log("debug", "%s: %s", type(content), tostring(content)); if not content then return 400; end local ok, err if method == "PUT" then ok, err = dm_store(p_user, p_host, p_store, content); elseif method == "POST" then ok, err = dm_list_append(p_user, p_host, p_store, content); end if ok then response.headers.location = t_concat({module:http_url(nil,"/data"),p_host,p_user,p_store}, "/"); return 201; else response.headers.debug = err; return 500; end elseif method == "DELETE" then dm_store(p_user, p_host, p_store, nil); dm_list_store(p_user, p_host, p_store, nil); return 204; end end local handle_request_with_auth = require_valid_user(handle_request); module:provides("http", { default_path = "/data"; route = { ["GET /*"] = handle_request_with_auth, ["PUT /*"] = handle_request_with_auth, ["POST /*"] = handle_request_with_auth, ["DELETE /*"] = handle_request_with_auth, }; });
mit
Max-pbot/Maxbot3
plugins/banhammer.lua
1
12244
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['..user_id..'] USere morede nazare shoma ban ast!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] User["..user_id.."]kick va ban shod! ")-- 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['..user_id..'] USere morede nazare shoma ban ast!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] User["..user_id.."]Bot add shod! > @".. 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('Usere darhale sohbat kardan kick shod!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] User["..user_id.."]dar hale sohbat kardan kick shod!")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "User["..user_id.."]shoma nemitavanid khodeton ro kick konid!") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "User["..user_id.."]Shoma nemitavanid modha/Modir/adminha ra kick konid") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "User["..user_id.."]Shoma nemitavanid modha/Modir/adminha ra Ban konid") end send_large_msg(receiver, 'User @'..member..' ['..member_id..']User['..user_id..'] Ban shod!') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] User['..user_id..']Unban shod!') local hash = 'Ban shod!:'..chat_id redis:srem(hash, member_id) return 'User ['..user_id..'] Unban shod!' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] User['..user_id..']az global ban shod!') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] User['..user_id..']az global unban shod!') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Id bot: "..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.."] User["..user_id.."]az /id estefade konid! ") 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.."] User["..user_id.."]az /id estefade konid! ") return "Group ID Baraye " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] User["..user_id.."]Baraye left az /kickme estefade konid! ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "User["..user_id.."]Shoma nemitavanid mod/Modir/admin ra ban konid!" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "User["..user_id.."]Shoma nemitavanid khodetono ban konid!" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] User["..user_id.."]User ban shod! ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'Ban shod!:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] User["..user_id.."]User unban shod! ".. matches[2]) return 'User '..user_id..' Unban shod!' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "User["..user_id.."]Shoma nemitavanid mod/Modir/admin ra kick konid!" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "User["..user_id.."]SHoma nemitavanid khodetono kick konid!" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."]User["..user_id.."] kick shod!".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] Az global ban shod!' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] Az liste global ban hazf shod!' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
RyMarq/Zero-K
units/turretemp.lua
1
3744
return { turretemp = { unitname = [[turretemp]], name = [[Faraday]], description = [[EMP Turret]], buildCostMetal = 250, builder = false, buildingGroundDecalDecaySpeed = 30, buildingGroundDecalSizeX = 4, buildingGroundDecalSizeY = 4, buildingGroundDecalType = [[turretemp_aoplane.dds]], buildPic = [[turretemp.png]], category = [[SINK TURRET]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[32 75 32]], collisionVolumeType = [[CylY]], corpse = [[DEAD]], customParams = { aimposoffset = [[0 10 0]], modelradius = [[16]], }, damageModifier = 0.25, explodeAs = [[MEDIUM_BUILDINGEX]], footprintX = 2, footprintZ = 2, iconType = [[defensespecial]], levelGround = false, maxDamage = 1600, maxSlope = 36, maxWaterDepth = 0, minCloakDistance = 150, noChaseCategory = [[FIXEDWING LAND SHIP SWIM GUNSHIP SUB HOVER]], objectName = [[armartic]], script = [[turretemp.lua]], selfDestructAs = [[MEDIUM_BUILDINGEX]], sfxtypes = { explosiongenerators = { [[custom:YELLOW_LIGHTNING_MUZZLE]], [[custom:YELLOW_LIGHTNING_GROUNDFLASH]], }, }, sightDistance = 554, -- Range*1.1 + 48 for radar overshoot useBuildingGroundDecal = true, yardMap = [[oo oo]], weapons = { { def = [[arm_det_weapon]], onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER FIXEDWING GUNSHIP]], }, }, weaponDefs = { arm_det_weapon = { name = [[Electro-Stunner]], areaOfEffect = 160, collideFriendly = false, craterBoost = 0, craterMult = 0, cylinderTargeting = 0, customParams = { light_color = [[0.75 0.75 0.56]], light_radius = 220, }, damage = { default = 1200, }, duration = 8, edgeEffectiveness = 0.8, explosionGenerator = [[custom:YELLOW_LIGHTNINGPLOSION]], fireStarter = 0, impulseBoost = 0, impulseFactor = 0, intensity = 12, interceptedByShieldType = 1, noSelfDamage = true, paralyzer = true, paralyzeTime = 2, range = 460, reloadtime = 2.7, rgbColor = [[1 1 0.25]], soundStart = [[weapon/lightning_fire]], soundTrigger = true, texture1 = [[lightning]], thickness = 10, turret = true, weaponType = [[LightningCannon]], weaponVelocity = 450, }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[armartic_dead.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris3x3b.s3o]], }, }, } }
gpl-2.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/NplBrowser/NplBrowserManager.lua
1
2686
--[[ Title: NplBrowserManager Author(s): leio Date: 2020/6/24 Desc: use the lib: ------------------------------------------------------------ local NplBrowserManager = NPL.load("(gl)script/apps/Aries/Creator/Game/NplBrowser/NplBrowserManager.lua"); NplBrowserManager:PreShowWnd(wndName, url) NplBrowserManager:CreateOrGet("DailyCheckBrowser"):Show("https://keepwork.com", "title", false, true); NplBrowserManager:CreateOrGet("DailyCheckBrowser"):Show("https://keepwork.com", "title", true, true, { left = 100, top = 50, right = 100, bottom = 50}); NplBrowserManager:CreateOrGet("DailyCheckBrowser"):Show("https://keepwork.com", "title", false, false, { left = 100, top = 50, right = 100, bottom = 50, fixed = true, }); NplBrowserManager:CreateOrGet("DailyCheckBrowser"):Show("https://keepwork.com", "title", true, true, { left = 100, top = 50, right = 100, bottom = 50, fixed = true, candrag = true, }); NplBrowserManager:CreateOrGet("DailyCheckBrowser"):Show("https://keepwork.com", "title", true, true, { scale_screen = "4:3:v", }); NplBrowserManager:CreateOrGet("DailyCheckBrowser"):GotoEmpty() ------------------------------------------------------- ]] local NplBrowserFrame = NPL.load("(gl)script/apps/Aries/Creator/Game/NplBrowser/NplBrowserFrame.lua"); local NplBrowserManager = NPL.export(); NplBrowserManager.browser_pages = {}; function NplBrowserManager:CreateOrGet(name) if(not name)then return end local browser_page = self.browser_pages[name]; if(not browser_page)then browser_page = NplBrowserFrame:new():OnInit(name); self.browser_pages[name] = browser_page; end return browser_page; end function NplBrowserManager:CloseAll() for k,v in pairs(self.browser_pages) do v:Close(); end end -- pre loading cef3 window -- @param {table} list: window list -- @param {string} list.name -- @param {string} list.url -- @param {bool} list.is_show_control function NplBrowserManager:PreLoadWindows(list) NPL.load("(gl)script/apps/Aries/Creator/Game/NplBrowser/NplBrowserLoaderPage.lua"); local NplBrowserLoaderPage = commonlib.gettable("NplBrowser.NplBrowserLoaderPage"); NPL.load("(gl)script/ide/timer.lua"); list = list or {}; local function loadingAll(list) for k, v in ipairs(list) do local name = v.name; local url = v.url or ""; local is_show_control = v.is_show_control; NplBrowserManager:CreateOrGet(name):PreShow(url, is_show_control); end end if(NplBrowserLoaderPage.IsLoaded()) then loadingAll(list); else NplBrowserLoaderPage.CheckOnce(); local mytimer = commonlib.Timer:new({callbackFunc = function(timer) loadingAll(list); end}) mytimer:Change(5000, nil) end end
gpl-2.0
dwindow/dwindow
oem-3dvstar/dwindow/dwindow_UI/3dvplayer/render.lua
1
11816
local lua_file = core.loading_file local lua_path = GetPath(lua_file) volume_bar = BaseFrame:Create() core.execute_luafile(lua_path .. "menu.lua") setting.MAX_WIDTH = 746 setting.MAX_HEIGHT = 461 core.ApplySetting("MAX_WIDTH") core.ApplySetting("MAX_HEIGHT") local UI_fading_time = 300 local UI_show_time = 2000 local alpha = 1 local last_mousemove = 0 local mousex = -999 local mousey = -999 player.set_window_text("3DVPlayer", "3DVPlayer") -- 3dvplayer UI renderer local button_size = 40; local margin_button_right = 32; local margin_button_bottom = 8; local space_of_each_button = 62; local toolbar_height = 65; local width_progress_left = 5; local width_progress_right = 6; local margin_progress_right = 522; local margin_progress_left = 37; local progress_height = 21; local progress_margin_bottom = 27; local volume_base_width = 84; local volume_base_height = 317; local volume_margin_right = (156 - 84); local volume_margin_bottom = (376 - 317); local volume_button_zero_point = 26; local volume_bar_height = 265; local numbers_left_margin = 21; local numbers_right_margin = 455+62; local numbers_width = 12; local numbers_height = 20; local numbers_bottom_margin = 26; local hidden_progress_width = 72; logo = BaseFrame:Create() logo.name = "LOGO" root:AddChild(logo) logo:SetPoint(CENTER, nil, nil, 0, -20) logo:SetSize(1920,1080) function logo:RenderThis() if not player.movie_loaded then local res = get_bitmap(lua_path .. "logo_bg.png") paint(0,0,1920,1080, res) end end function logo:OnClick(x, y, key) if key == VK_RBUTTON then popup3dvstar() end return false end function logo:OnMouseDown(x, y, button) if button ~= VK_RBUTTON and not player.is_fullscreen() then ui.StartDragging() end return true end function logo:OnUpdate(t, dt) local px, py = ui.get_mouse_pos() if (mousex-px)*(mousex-px)+(mousey-py)*(mousey-py) > 100 or ((mousex-px)*(mousex-px)+(mousey-py)*(mousey-py) > 0 and alpha > 0.5) then last_mousemove = core.GetTickCount() mousex, mousey = ui.get_mouse_pos() end local da = dt/UI_fading_time local old_alpha = alpha local mouse_in_pannel = px>=0 and px<ui.width and py>=ui.height-toolbar_height and py<ui.height local hide_mouse = not mouse_in_pannel and (t > last_mousemove + UI_show_time) player.show_mouse(not hide_mouse) if hide_mouse then alpha = alpha - da else alpha = alpha + da end alpha = math.min(1, math.max(alpha, 0)) end local open = BaseFrame:Create() root:AddChild(open) open:SetPoint(CENTER, nil, nil, 0, 60) open:SetSize(230,70) function open:RenderThis() if not player.movie_loaded then paint(0,0,230,70, get_bitmap(lua_path .. (setting.LCID == "简体中文" and "open.png" or "open_en.png"))) end end function open:HitTest() return not player.movie_loaded end function open:OnClick() local file = ui.OpenFile() if file then playlist:play(file) end return true end logo_hot = BaseFrame:Create() logo_hot.name = "LOGO HOT AREA" logo:AddChild(logo_hot) logo_hot:SetPoint(CENTER, nil, nil, 0, -50) logo_hot:SetSize(400,171) function logo_hot:RenderThis() if not player.movie_loaded then local res = get_bitmap(lua_path .. "logo_hot.png") paint(0,0,400,171, res) end end toolbar_bg = BaseFrame:Create() toolbar_bg.name = "toolbar_bg" root:AddChild(toolbar_bg) toolbar_bg:SetPoint(BOTTOMLEFT) toolbar_bg:SetPoint(BOTTOMRIGHT) toolbar_bg:SetSize(nil, toolbar_height) print("toolbar_height=", toolbar_height) function toolbar_bg:RenderThis() local l,t,r,b = self:GetRect() local res = get_bitmap(lua_path .. "toolbar_background.png"); paint(0,0,r-l,b-t, res, alpha) end -- buttons local button_pictures = { "fullscreen.png", "", "volume.png", "", "next.png", "", "play.png", "pause.png", "previous.png", "", "stop.png", "", "3d.png", "2d.png", "setting.png", "", } function show_volume_bar() volume_bar:show() end function start_play_or_pause() if not player.movie_loaded then if playlist:count() > 0 then playlist:play_item(playlist:current_pos()) else local file = ui.OpenFile() if file then playlist:play(file) end end else player.pause() end end local button_functions = { player.toggle_fullscreen, show_volume_bar, playlist.next, start_play_or_pause, playlist.previous, player.reset, player.toggle_3d, player.show_setting, } local function button_GetRect(self) return 0, 0, space_of_each_button, button_size, self.dx, self.dy end local function button_RenderThis(self) paint(11,0,button_size+11,button_size, get_bitmap(lua_path .. self.pic[1]), alpha) end local function button_OnClick(self) return button_functions[self.id]() end local x = - margin_button_right local y = - margin_button_bottom local buttons = {} for i=1,#button_pictures/2 do local button = buttons[i] or BaseFrame:Create() buttons[i] = button toolbar_bg:AddChild(button) button.pic = {button_pictures[i*2-1], button_pictures[i*2]} button.RenderThis = button_RenderThis button.OnClick = button_OnClick button.name = button.pic[1] button:SetPoint(BOTTOMRIGHT, nil, nil, x, y) button:SetSize(space_of_each_button, button_size) button.id = i x = x - space_of_each_button end buttons[4].RenderThis = function(self) paint(11,0,button_size+11,button_size, get_bitmap(lua_path .. self.pic[player.is_playing() and 2 or 1]), alpha) end buttons[7].RenderThis = function(self) paint(11,0,button_size+11,button_size, get_bitmap(lua_path .. self.pic[dx9.is2DRendering() and 2 or 1]), alpha) end progressbar = BaseFrame:Create() progressbar.name = "progressbar" toolbar_bg:AddChild(progressbar) progressbar:SetPoint(BOTTOMLEFT, nil, nil, margin_progress_left, -progress_margin_bottom+progress_height) progressbar:SetPoint(BOTTOMRIGHT, nil, nil, -margin_progress_right, -progress_margin_bottom+progress_height) progressbar:SetSize(nil, progress_height) local progress_pic = { "progress_left_base.png", "progress_center_base.png", "progress_right_base.png", "progress_left_top.png", "progress_center_top.png", "progress_right_top.png", } function file(n) return progress_pic[n] end function progressbar:OnClick(x) local l,_,r = self:GetRect() local fv = x/(r-l) player.seek(player.total()*fv) end function progressbar:RenderThis() local l,t,r,b = self:GetRect() l,r,t,b = 0,r-l,0,b-t local fv = player.tell() / player.total() if fv > 1 then fv = 1 end if fv < 0 then fv = 0 end local v = fv * r -- draw bottom paint(0,0, width_progress_left, b, get_bitmap(lua_path .. file(1)), alpha) paint(width_progress_left,0, r-width_progress_right, b, get_bitmap(lua_path .. file(2)), alpha) paint(r-width_progress_right,0, r, b, get_bitmap(lua_path .. file(3)), alpha) -- draw top if (v > 1.5) then local bmp = get_bitmap(lua_path .. file(4)) paint(0,0,math.min(width_progress_left, v),b, bmp, alpha) end if (v > width_progress_left) then local r = math.min(r-width_progress_right, v) local bmp = get_bitmap(lua_path .. file(5)) paint(width_progress_left, 0, r, b, bmp, alpha) end if (v > r - width_progress_right) then local bmp = get_bitmap(lua_path .. file(6)) paint(r-width_progress_right, 0, v, b, bmp, alpha) end end number_current = BaseFrame:Create() number_current.name = "number_current" toolbar_bg:AddChild(number_current) number_current:SetPoint(BOTTOMLEFT, nil, nil, numbers_left_margin, - numbers_bottom_margin) number_current:SetSize(numbers_width * 8, numbers_height) function number_current:RenderThis() if not player.movie_loaded then return end local t = player.total() if self.name == "number_current" then t= player.tell() end local ms = t % 1000 local s = t / 1000 local h = (s / 3600) % 100 local h1 = h/10 local h2 = h%10 local m1 = (s/60 /10) % 6 local m2 = (s/60) % 10 local s1 = (s/10) % 6 local s2 = s%10 local numbers = { h1, h2, 10, m1, m2, 10, s1, s2, -- 10 = : symbol in time } local x = 0 for i=1,#numbers do paint(x, 0, x+numbers_width, numbers_height, get_bitmap(lua_path .. math.floor(numbers[i]) .. ".png"), alpha) x = x + numbers_width end end number_total = BaseFrame:Create() number_total.name = "number_total" toolbar_bg:AddChild(number_total) number_total:SetPoint(BOTTOMRIGHT, nil, nil, -numbers_right_margin, - numbers_bottom_margin) number_total.t = 23456000 number_total:SetSize(numbers_width * 8, numbers_height) number_total.RenderThis = number_current.RenderThis root:AddChild(volume_bar) volume_bar:SetPoint(BOTTOMRIGHT, nil, nil, 84-156, 317-376) volume_bar:SetSize(84, 317) volume_bar.alpha = 0 volume_bar.volume = player.get_volume() function volume_bar:RenderThis() if self.alpha < 0.05 then return end paint(0,0,84,317, get_bitmap(lua_path .. "volume_base.png"), self.alpha) -- the button local ypos = volume_button_zero_point + (317-volume_button_zero_point*2) * (1-player.get_volume()); paint (22, ypos-20, 62, ypos + 20, get_bitmap(lua_path .. "volume_button.png"), self.alpha) end function volume_bar:hide() self.showing = false end function volume_bar:show() self.last_show = core.GetTickCount() self.showing = true end function volume_bar:OnUpdate(t, dt) local da = dt/UI_fading_time if self.showing or self.dragging then self.alpha = self.alpha + da else self.alpha = self.alpha - da end self.alpha = math.max(0, self.alpha) self.alpha = math.min(1, self.alpha) if self.volume ~= player.get_volume() then self:show() self.volume = player.get_volume() elseif core.GetTickCount() > (self.last_show or 0)+UI_show_time then self:hide() end end function volume_bar:HitTest() return self.alpha > 0 end function volume_bar:OnMouseMove(x,y,button) if not self.dragging then return end local _,t,_,b=self:GetRect() local h = b-t-volume_button_zero_point*2 local v = 1-(y-volume_button_zero_point)/h v = math.max(0,math.min(v,1)) player.set_volume(v) end function volume_bar:OnMouseUp(x, y, button) self.dragging = false; end function volume_bar:OnMouseDown(...) self.dragging = true self:OnMouseMove(...) return true end grow = BaseFrame:Create() grow.x = 0 grow.y = 0 local last_in_time = 0 local last_out_time = 0 local last_in = false local alpha_tick = 0 toolbar_bg:AddChild(grow) grow.name = "GROW" grow:SetSize(250, 250) grow:SetPoint(BOTTOMLEFT, nil, nil, -125, 125) function grow:Stick(dt) local frame = root:GetFrameByPoint(self.px or 0, self.py or 0) local isbutton = false for _,v in ipairs(buttons) do if v == frame then isbutton = true end end if not isbutton then return end local l,t,r,b = frame:GetRect() local dx = (l+r)/2 - self.x self.x = self.x + 0.65 * dx self:SetPoint(BOTTOMLEFT, nil, nil, self.x-125, 125) end function grow:PreRender() self.px, self.py = ui.get_mouse_pos() local px,py = self.px,self.py local r,b = toolbar_bg:GetPoint(BOTTOMRIGHT) r,b = r - margin_button_right, b - margin_button_bottom local l,t = toolbar_bg:GetPoint(BOTTOMRIGHT) l,t = l - margin_progress_right, t - margin_button_bottom - button_size local dt = 0; if l<=px and px<r and t<=py and py<b then if not last_in then self:OnEnter() else alpha_tick = alpha_tick + (core.GetTickCount() - last_in_time)+2 dt = core.GetTickCount() - last_in_time end last_in = true last_in_time = core.GetTickCount() else if last_in then self:OnLeave() else alpha_tick = alpha_tick - (core.GetTickCount() - last_out_time)*0.8 dt = core.GetTickCount() - last_out_time end last_in = false last_out_time = core.GetTickCount() end alpha_tick = math.max(alpha_tick, 0) alpha_tick = math.min(alpha_tick, 300) if dt > 0 then self:Stick(dt) end end function grow:OnEnter() end function grow:OnLeave() end function grow:RenderThis() local res = get_bitmap(lua_path .. "grow.png") local alpha = alpha_tick / 200 paint(0, 0, 250, 250, res, alpha) end function grow:HitTest() return false end
gpl-3.0
vince06fr/prosody-modules
mod_auto_accept_subscriptions/mod_auto_accept_subscriptions.lua
20
2165
local rostermanager = require "core.rostermanager"; local jid = require "util.jid"; local st = require "util.stanza"; local core_post_stanza = prosody.core_post_stanza; local function handle_inbound_subscription_request(origin, stanza) local to_bare, from_bare = jid.bare(stanza.attr.to), jid.bare(stanza.attr.from); local node, host = jid.split(to_bare); stanza.attr.from, stanza.attr.to = from_bare, to_bare; module:log("info", "Auto-accepting inbound subscription request from %s to %s", tostring(from_bare), tostring(to_bare)); if not rostermanager.is_contact_subscribed(node, host, from_bare) then core_post_stanza(hosts[host], st.presence({from=to_bare, to=from_bare, type="unavailable"}), true); -- acknowledging receipt module:log("debug", "receipt acknowledged"); if rostermanager.set_contact_pending_in(node, host, from_bare) then module:log("debug", "set pending in"); if rostermanager.subscribed(node, host, from_bare) then module:log("debug", "set subscribed"); rostermanager.roster_push(node, host, to_bare); module:log("debug", "pushed roster item"); local subscribed_stanza = st.reply(stanza); subscribed_stanza.attr.type = "subscribed"; core_post_stanza(hosts[host], subscribed_stanza); module:log("debug", "sent subscribed"); hosts[host].modules.presence.send_presence_of_available_resources(node, host, to_bare, origin); module:log("debug", "sent available presence of all resources"); -- Add return subscription from user to contact local subscribe_stanza = st.reply(stanza); subscribed_stanza.attr.type = "subscribe"; if rostermanager.set_contact_pending_out(node, host, from_bare) then rostermanager.roster_push(node, host, from_bare); end core_post_stanza(hosts[host], subscribe_stanza); return true; end end end module:log("warn", "Failed to auto-accept subscription request from %s to %s", tostring(from_bare), tostring(to_bare)); end module:hook("presence/bare", function (event) local stanza = event.stanza; if stanza.attr.type == "subscribe" then handle_inbound_subscription_request(event.origin, stanza); return true; end end, 0.1);
mit
SlNPacifist/ProDBG
bin/macosx/tundra/scripts/tundra/tools/dotnet.lua
28
1125
module(..., package.seeall) local frameworkDir = "c:\\Windows\\Microsoft.NET\\Framework" local defaultFrameworkVersion = "v3.5" function apply(env, options) tundra.unitgen.load_toolset("generic-dotnet", env) local version = options and assert(options.Version) or defaultFrameworkVersion env:set_external_env_var('FrameworkDir', frameworkDir) env:set_external_env_var('FrameworkVersion', version) local binPath = frameworkDir .. "\\" .. version env:set_external_env_var('PATH', binPath .. ";" .. env:get_external_env_var('PATH')) -- C# support env:set_many { ["DOTNET_SUFFIXES"] = { ".cs" }, ["DOTNET_SUFFIXES_RESOURCE"] = { ".resource" }, ["CSC"] = "csc.exe", ["CSPROGSUFFIX"] = ".exe", ["CSLIBSUFFIX"] = ".dll", ["CSRESGEN"] = "resgen $(<) $(@)", ["_CSC_COMMON"] = "-warn:$(CSC_WARNING_LEVEL) /nologo $(CSLIBPATH:b:p/lib\\:) $(CSRESOURCES:b:p/resource\\:) $(CSLIBS:p/reference\\::A.dll)", ["CSCLIBCOM"] = "$(CSC) $(_CSC_COMMON) $(CSCOPTS) -target:library -out:$(@:b) $(<:b)", ["CSCEXECOM"] = "$(CSC) $(_CSC_COMMON) $(CSCOPTS) -target:exe -out:$(@:b) $(<:b)", } end
mit
madpilot78/ntopng
scripts/lua/modules/pools/mac_pools.lua
1
1456
-- -- (C) 2017-21 - ntop.org -- local dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/pools/?.lua;" .. package.path if ntop.isPro() then package.path = dirs.installdir .. "/pro/scripts/lua/modules/?.lua;" .. package.path end local pools = require "pools" local mac_pools = {} -- ############################################## function mac_pools:create() -- Instance of the base class local _mac_pools = pools:create() -- Subclass using the base class instance self.key = "mac" -- self is passed as argument so it will be set as base class metatable -- and this will actually make it possible to override functions local _mac_pools_instance = _mac_pools:create(self) -- Return the instance return _mac_pools_instance end -- ############################################## -- @brief Given a member key, returns a table of member details such as member name. -- POOL WITH NO MEMBERS function mac_pools:get_member_details(member) return {} end -- ############################################## -- @brief Returns a table of all possible ids, both assigned and unassigned to pool members -- POOL WITH NO MEMBERS function mac_pools:get_all_members() return {} end -- ############################################## function mac_pools:default_only() -- This is a dummy, default-only pool return true end -- ############################################## return mac_pools
gpl-3.0
akiss77/skia
tools/lua/bbh_filter.lua
207
4407
-- bbh_filter.lua -- -- This script outputs info about 'interesting' skp files, -- where the definition of 'interesting' changes but is roughly: -- "Interesting for bounding box hierarchy benchmarks." -- -- Currently, the approach is to output, in equal ammounts, the names of the files that -- have most commands, and the names of the files that use the least popular commands. function count_entries(table) local count = 0 for _,_ in pairs(table) do count = count + 1 end return count end verbCounts = {} function reset_current() -- Data about the skp in transit currentInfo = { fileName = '', verbs = {}, numOps = 0 } end reset_current() numOutputFiles = 10 -- This is per measure. globalInfo = {} -- Saves currentInfo for each file to be used at the end. output = {} -- Stores {fileName, {verb, count}} tables. function tostr(t) local str = "" for k, v in next, t do if #str > 0 then str = str .. ", " end if type(k) == "number" then str = str .. "[" .. k .. "] = " else str = str .. tostring(k) .. " = " end if type(v) == "table" then str = str .. "{ " .. tostr(v) .. " }" else str = str .. tostring(v) end end return str end function sk_scrape_startcanvas(c, fileName) end function sk_scrape_endcanvas(c, fileName) globalInfo[fileName] = currentInfo globalInfo[fileName].fileName = fileName reset_current() end function sk_scrape_accumulate(t) -- dump the params in t, specifically showing the verb first, which we -- then nil out so it doesn't appear in tostr() -- verbCounts[t.verb] = (verbCounts[t.verb] or 0) + 1 currentInfo.verbs[t.verb] = (currentInfo.verbs[t.verb] or 0) + 1 currentInfo.numOps = currentInfo.numOps + 1 t.verb = nil end function sk_scrape_summarize() verbWeights = {} -- {verb, weight}, where 0 < weight <= 1 meta = {} for k,v in pairs(verbCounts) do table.insert(meta, {key=k, value=v}) end table.sort(meta, function (a,b) return a.value > b.value; end) maxValue = meta[1].value io.write("-- ==================\n") io.write("------------------------------------------------------------------ \n") io.write("-- Command\t\t\tNumber of calls\t\tPopularity\n") io.write("------------------------------------------------------------------ \n") for k, v in pairs(meta) do verbWeights[v.key] = v.value / maxValue -- Poor man's formatting: local padding = "\t\t\t" if (#v.key + 3) < 8 then padding = "\t\t\t\t" end if (#v.key + 3) >= 16 then padding = "\t\t" end io.write ("-- ",v.key, padding, v.value, '\t\t\t', verbWeights[v.key], "\n") end meta = {} function calculate_weight(verbs) local weight = 0 for name, count in pairs(verbs) do weight = weight + (1 / verbWeights[name]) * count end return weight end for n, info in pairs(globalInfo) do table.insert(meta, info) end local visitedFiles = {} -- Prints out information in lua readable format function output_with_metric(metric_func, description, numOutputFiles) table.sort(meta, metric_func) print(description) local iter = 0 for i, t in pairs(meta) do if not visitedFiles[t.fileName] then visitedFiles[t.fileName] = true io.write ("{\nname = \"", t.fileName, "\", \nverbs = {\n") for verb,count in pairs(globalInfo[t.fileName].verbs) do io.write(' ', verb, " = ", count, ",\n") end io.write("}\n},\n") iter = iter + 1 if iter >= numOutputFiles then break end end end end output_with_metric( function(a, b) return calculate_weight(a.verbs) > calculate_weight(b.verbs); end, "\n-- ================== skps with calling unpopular commands.", 10) output_with_metric( function(a, b) return a.numOps > b.numOps; end, "\n-- ================== skps with the most calls.", 50) local count = count_entries(visitedFiles) print ("-- Spat", count, "files") end
bsd-3-clause
pakoito/ToME---t-engine4
game/modules/tome/data/general/events/snowstorm.lua
3
2172
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org -- Darken game.level.map:setShown(0.6, 0.6, 0.6, 1) game.level.map:setObscure(0.6*0.6, 0.6*0.6, 0.6*0.6, 0.6) game.level.map:liteAll(0, 0, game.level.map.w, game.level.map.h, false) -- Add snowing local Map = require "engine.Map" level.foreground_particle = require("engine.Particles").new("snowing", 1, {factor=10, width=Map.viewport.width, height=Map.viewport.height}) game.level.data.snowstorm_event_foreground = game.level.data.foreground game.level.data.foreground = function(level, x, y, nb_keyframes) if level.data.snowstorm_event_foreground then level.data.snowstorm_event_foreground(level, x, y, nb_keyframes) end if not config.settings.tome.weather_effects or not level.foreground_particle then return end level.foreground_particle.ps:toScreen(x, y, true, 1) end game.zone.snowstorm_event_levels = game.zone.snowstorm_event_levels or {} game.zone.snowstorm_event_levels[level.level] = true if not game.zone.snowstorm_event_on_turn then game.zone.snowstorm_event_on_turn = game.zone.on_turn or function() end end game.zone.on_turn = function() if game.zone.snowstorm_event_on_turn then game.zone.snowstorm_event_on_turn() end if game.turn % 10 ~= 0 or not game.zone.snowstorm_event_levels[game.level.level] then return end end require("engine.ui.Dialog"):simplePopup("Snowstorm", "As you walk into the area you notice a huge snowstorm over your head. Beware!") return true
gpl-3.0
BinChengfei/openwrt-3.10.14
package/ramips/ui/luci-mtk/src/modules/admin-full/luasrc/model/cbi/admin_network/dhcp.lua
37
8552
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local sys = require "luci.sys" m = Map("dhcp", translate("DHCP and DNS"), translate("Dnsmasq is a combined <abbr title=\"Dynamic Host Configuration Protocol" .. "\">DHCP</abbr>-Server and <abbr title=\"Domain Name System\">DNS</abbr>-" .. "Forwarder for <abbr title=\"Network Address Translation\">NAT</abbr> " .. "firewalls")) s = m:section(TypedSection, "dnsmasq", translate("Server Settings")) s.anonymous = true s.addremove = false s:tab("general", translate("General Settings")) s:tab("files", translate("Resolv and Hosts Files")) s:tab("tftp", translate("TFTP Settings")) s:tab("advanced", translate("Advanced Settings")) s:taboption("general", Flag, "domainneeded", translate("Domain required"), translate("Don't forward <abbr title=\"Domain Name System\">DNS</abbr>-Requests without " .. "<abbr title=\"Domain Name System\">DNS</abbr>-Name")) s:taboption("general", Flag, "authoritative", translate("Authoritative"), translate("This is the only <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" .. "abbr> in the local network")) s:taboption("files", Flag, "readethers", translate("Use <code>/etc/ethers</code>"), translate("Read <code>/etc/ethers</code> to configure the <abbr title=\"Dynamic Host " .. "Configuration Protocol\">DHCP</abbr>-Server")) s:taboption("files", Value, "leasefile", translate("Leasefile"), translate("file where given <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</" .. "abbr>-leases will be stored")) s:taboption("files", Flag, "noresolv", translate("Ignore resolve file")).optional = true rf = s:taboption("files", Value, "resolvfile", translate("Resolve file"), translate("local <abbr title=\"Domain Name System\">DNS</abbr> file")) rf:depends("noresolv", "") rf.optional = true s:taboption("files", Flag, "nohosts", translate("Ignore Hosts files")).optional = true hf = s:taboption("files", DynamicList, "addnhosts", translate("Additional Hosts files")) hf:depends("nohosts", "") hf.optional = true s:taboption("advanced", Flag, "boguspriv", translate("Filter private"), translate("Do not forward reverse lookups for local networks")) s:taboption("advanced", Flag, "filterwin2k", translate("Filter useless"), translate("Do not forward requests that cannot be answered by public name servers")) s:taboption("advanced", Flag, "localise_queries", translate("Localise queries"), translate("Localise hostname depending on the requesting subnet if multiple IPs are available")) s:taboption("general", Value, "local", translate("Local server"), translate("Local domain specification. Names matching this domain are never forwarded and are resolved from DHCP or hosts files only")) s:taboption("general", Value, "domain", translate("Local domain"), translate("Local domain suffix appended to DHCP names and hosts file entries")) s:taboption("advanced", Flag, "expandhosts", translate("Expand hosts"), translate("Add local domain suffix to names served from hosts files")) s:taboption("advanced", Flag, "nonegcache", translate("No negative cache"), translate("Do not cache negative replies, e.g. for not existing domains")) s:taboption("advanced", Flag, "strictorder", translate("Strict order"), translate("<abbr title=\"Domain Name System\">DNS</abbr> servers will be queried in the " .. "order of the resolvfile")).optional = true bn = s:taboption("advanced", DynamicList, "bogusnxdomain", translate("Bogus NX Domain Override"), translate("List of hosts that supply bogus NX domain results")) bn.optional = true bn.placeholder = "67.215.65.132" s:taboption("general", Flag, "logqueries", translate("Log queries"), translate("Write received DNS requests to syslog")).optional = true df = s:taboption("general", DynamicList, "server", translate("DNS forwardings"), translate("List of <abbr title=\"Domain Name System\">DNS</abbr> " .. "servers to forward requests to")) df.optional = true df.placeholder = "/example.org/10.1.2.3" rp = s:taboption("general", Flag, "rebind_protection", translate("Rebind protection"), translate("Discard upstream RFC1918 responses")) rp.rmempty = false rl = s:taboption("general", Flag, "rebind_localhost", translate("Allow localhost"), translate("Allow upstream responses in the 127.0.0.0/8 range, e.g. for RBL services")) rl:depends("rebind_protection", "1") rd = s:taboption("general", DynamicList, "rebind_domain", translate("Domain whitelist"), translate("List of domains to allow RFC1918 responses for")) rd:depends("rebind_protection", "1") rd.datatype = "host" rd.placeholder = "ihost.netflix.com" pt = s:taboption("advanced", Value, "port", translate("<abbr title=\"Domain Name System\">DNS</abbr> server port"), translate("Listening port for inbound DNS queries")) pt.optional = true pt.datatype = "port" pt.placeholder = 53 qp = s:taboption("advanced", Value, "queryport", translate("<abbr title=\"Domain Name System\">DNS</abbr> query port"), translate("Fixed source port for outbound DNS queries")) qp.optional = true qp.datatype = "port" qp.placeholder = translate("any") lm = s:taboption("advanced", Value, "dhcpleasemax", translate("<abbr title=\"maximal\">Max.</abbr> <abbr title=\"Dynamic Host Configuration " .. "Protocol\">DHCP</abbr> leases"), translate("Maximum allowed number of active DHCP leases")) lm.optional = true lm.datatype = "uinteger" lm.placeholder = translate("unlimited") em = s:taboption("advanced", Value, "ednspacket_max", translate("<abbr title=\"maximal\">Max.</abbr> <abbr title=\"Extension Mechanisms for " .. "Domain Name System\">EDNS0</abbr> packet size"), translate("Maximum allowed size of EDNS.0 UDP packets")) em.optional = true em.datatype = "uinteger" em.placeholder = 1280 cq = s:taboption("advanced", Value, "dnsforwardmax", translate("<abbr title=\"maximal\">Max.</abbr> concurrent queries"), translate("Maximum allowed number of concurrent DNS queries")) cq.optional = true cq.datatype = "uinteger" cq.placeholder = 150 s:taboption("tftp", Flag, "enable_tftp", translate("Enable TFTP server")).optional = true tr = s:taboption("tftp", Value, "tftp_root", translate("TFTP server root"), translate("Root directory for files served via TFTP")) tr.optional = true tr:depends("enable_tftp", "1") tr.placeholder = "/" db = s:taboption("tftp", Value, "dhcp_boot", translate("Network boot image"), translate("Filename of the boot image advertised to clients")) db.optional = true db:depends("enable_tftp", "1") db.placeholder = "pxelinux.0" m:section(SimpleSection).template = "admin_network/lease_status" s = m:section(TypedSection, "host", translate("Static Leases"), translate("Static leases are used to assign fixed IP addresses and symbolic hostnames to " .. "DHCP clients. They are also required for non-dynamic interface configurations where " .. "only hosts with a corresponding lease are served.") .. "<br />" .. translate("Use the <em>Add</em> Button to add a new lease entry. The <em>MAC-Address</em> " .. "indentifies the host, the <em>IPv4-Address</em> specifies to the fixed address to " .. "use and the <em>Hostname</em> is assigned as symbolic name to the requesting host.")) s.addremove = true s.anonymous = true s.template = "cbi/tblsection" name = s:option(Value, "name", translate("Hostname")) name.datatype = "hostname" name.rmempty = true mac = s:option(Value, "mac", translate("<abbr title=\"Media Access Control\">MAC</abbr>-Address")) mac.datatype = "list(macaddr)" mac.rmempty = true ip = s:option(Value, "ip", translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Address")) ip.datatype = "or(ip4addr,'ignore')" hostid = s:option(Value, "hostid", translate("<abbr title=\"Internet Protocol Version 6\">IPv6</abbr>-Suffix (hex)")) sys.net.arptable(function(entry) ip:value(entry["IP address"]) mac:value( entry["HW address"], entry["HW address"] .. " (" .. entry["IP address"] .. ")" ) end) function ip.validate(self, value, section) local m = mac:formvalue(section) or "" local n = name:formvalue(section) or "" if value and #n == 0 and #m == 0 then return nil, translate("One of hostname or mac address must be specified!") end return Value.validate(self, value, section) end return m
gpl-2.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/mcml/keepwork/lessons_ppt/notes.lua
1
1740
--[[ Title: Author(s): yangguiyi Date: 2021/9/15 Desc: use the lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/keepwork/lessons_ppt/notes.lua"); local notes = commonlib.gettable("MyCompany.Aries.Game.mcml.lessons_ppt.notes"); ------------------------------------------------------- ]] local notes = commonlib.gettable("MyCompany.Aries.Game.mcml.lessons_ppt.notes"); local KeepWorkItemManager = NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/KeepWorkItemManager.lua"); local RedSummerCampPPtPage = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampPPtPage.lua"); function notes.render_callback(mcmlNode, rootName, bindingContext, _parent, left, top, right, bottom, myLayout, css) notes.create_default(rootName, mcmlNode, bindingContext, _parent, left, top, right, bottom, myLayout, css); return true, true, true; -- ignore_onclick, ignore_background, ignore_tooltip; end function notes.create(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, style, parentLayout, css) return mcmlNode:DrawDisplayBlock(rootName, bindingContext, _parent, left, top, width, height, parentLayout, style, notes.render_callback); end function notes.create_default(rootName, mcmlNode, bindingContext, _parent, left, top, width, height, parentLayout, css) local display = mcmlNode:GetString("display") if display == "teacher" then if RedSummerCampPPtPage.GetTeachingPlanPower() then mcmlNode:DrawChildBlocks_Callback(rootName, bindingContext, _parent, left, top, width, height, parentLayout, css); end else mcmlNode:DrawChildBlocks_Callback(rootName, bindingContext, _parent, left, top, width, height, parentLayout, css); end end
gpl-2.0
jsj2008/ValyriaTear
dat/maps/layna_village/layna_village_south_entrance_right_house_map.lua
4
26503
map_data = {} -- The number of rows, and columns that compose the map map_data.num_tile_cols = 32 map_data.num_tile_rows = 24 -- The tilesets definition files used. map_data.tileset_filenames = {} map_data.tileset_filenames[1] = "dat/tilesets/building_interior_objects_01.lua" map_data.tileset_filenames[2] = "dat/tilesets/mountain_house_interior.lua" -- The map grid to indicate walkability. 0 is walkable, 1 is not. map_data.map_grid = {} map_data.map_grid[0] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[1] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[2] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[3] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[4] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[5] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[6] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[7] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[8] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[9] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[10] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[11] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[12] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[13] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[14] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[15] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[16] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[17] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[18] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[19] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[20] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[21] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[22] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[23] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[24] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[25] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[26] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[27] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[28] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[29] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[30] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[31] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[32] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[33] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[34] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[35] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[36] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[37] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[38] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[39] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[40] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[41] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[42] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[43] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[44] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[45] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[46] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } map_data.map_grid[47] = { 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 } -- The tile layers. The numbers are indeces to the tile_mappings table. map_data.layers = {} map_data.layers[0] = {} map_data.layers[0].type = "ground" map_data.layers[0].name = "Background" map_data.layers[0][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 368, 369, 370, 370, 371, 370, 371, 371, 372, 373, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 384, 385, 386, 386, 387, 386, 387, 387, 388, 389, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 400, 401, 402, 402, 403, 402, 403, 403, 404, 405, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, 435, 419, 419, 419, 419, 419, 419, 435, 421, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][9] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, 435, 419, 419, 419, 419, 419, 419, 435, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, 435, 419, 419, 419, 419, 419, 419, 435, 421, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, 435, 435, 419, 435, 419, 419, 419, 435, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 448, 435, 419, 419, 419, 419, 419, 419, 435, 453, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 464, 435, 435, 435, 435, 435, 435, 435, 435, 469, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 418, 418, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][18] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[0][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1] = {} map_data.layers[1].type = "ground" map_data.layers[1].name = "Background 2" map_data.layers[1][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 197, 198, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 208, 224, 224, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 224, 224, 224, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 224, 224, 224, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 417, -1, -1, -1, -1, 224, 224, 224, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][9] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][18] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[1][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2] = {} map_data.layers[2].type = "ground" map_data.layers[2].name = "Background 3" map_data.layers[2][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 176, 177, 178, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 192, 193, 194, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][9] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][18] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[2][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3] = {} map_data.layers[3].type = "sky" map_data.layers[3].name = "Sky" map_data.layers[3][0] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][1] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][2] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][3] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][4] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][5] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][6] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][7] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][8] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, -1, -1, -1, -1, -1, -1, -1, -1, 421, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][9] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, -1, -1, -1, -1, -1, -1, -1, -1, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][10] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, -1, -1, -1, -1, -1, -1, -1, -1, 421, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][11] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, 432, -1, -1, -1, -1, -1, -1, -1, -1, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][12] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 449, -1, 376, 377, 374, 375, -1, 452, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][13] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 465, 466, 392, 393, 390, 391, 467, 468, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][14] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, 416, -1, -1, 437, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][15] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][16] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][17] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][18] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][19] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][20] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][21] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][22] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 } map_data.layers[3][23] = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1 }
gpl-2.0
madpilot78/ntopng
scripts/lua/get_dhcp_config.lua
1
2731
-- -- (C) 2017-21 - ntop.org -- local dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path local json = require("dkjson") local dhcp_utils = require("dhcp_utils") require "lua_utils" local ifid = _GET["ifid"] -- Table parameters local currentPage = _GET["currentPage"] local perPage = _GET["perPage"] local sortColumn = _GET["sortColumn"] local sortOrder = _GET["sortOrder"] local sortPrefs = "dhcp_ranges" sendHTTPContentTypeHeader('application/json') if((ifid == nil) or (not isAdministrator())) then return end interface.select(getInterfaceName(ifid)) -- ################################################ if isEmptyString(sortColumn) or sortColumn == "column_" then sortColumn = getDefaultTableSort(sortPrefs) else if((sortColumn ~= "column_") and (sortColumn ~= "")) then tablePreferences("sort_"..sortPrefs, sortColumn) end end if isEmptyString(_GET["sortColumn"]) then sortOrder = getDefaultTableSortOrder(sortPrefs, true) end if((_GET["sortColumn"] ~= "column_") and (_GET["sortColumn"] ~= "")) then tablePreferences("sort_order_"..sortPrefs, sortOrder, true) end if(currentPage == nil) then currentPage = 1 else currentPage = tonumber(currentPage) end if(perPage == nil) then perPage = getDefaultTableSize() else perPage = tonumber(perPage) tablePreferences("rows_number", perPage) end local sOrder local to_skip = (currentPage-1) * perPage if((sortColumn == "column_first_ip") or (sortColumn == "column_last_ip")) then sOrder = ternary(sortOrder == "desc", ip_address_rev, ip_address_asc) else sOrder = ternary(sortOrder == "desc", rev_insensitive, asc_insensitive) end -- ################################################ local ranges = dhcp_utils.listRanges(ifid) local totalRows = 0 local sort_to_key = {} for key, range in pairs(ranges) do totalRows = totalRows + 1 if sortColumn == "column_first_ip" then sort_to_key[key] = range[1] elseif sortColumn == "column_last_ip" then sort_to_key[key] = range[2] else -- default sort_to_key[key] = key end end -- ################################################ local res = {} local i = 0 for key in pairsByValues(sort_to_key, sOrder) do if i >= to_skip + perPage then break end if (i >= to_skip) then local range = ranges[key] res[#res + 1] = { column_first_ip = range[1], column_last_ip = range[2], } end i = i + 1 end -- ################################################ local result = {} result["perPage"] = perPage result["currentPage"] = currentPage result["totalRows"] = totalRows result["data"] = res result["sort"] = {{sortColumn, sortOrder}} print(json.encode(result))
gpl-3.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Tavnazian_Safehold/Zone.lua
1
1131
----------------------------------- -- -- Zone: Tavnazian_Safehold -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
madpilot78/ntopng
scripts/lua/modules/notifications/endpoints.lua
1
19675
-- -- (C) 2019-21 - ntop.org -- local dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path package.path = dirs.installdir .. "/scripts/lua/modules/recipients/?.lua;" .. package.path package.path = dirs.installdir .. "/scripts/lua/modules/toasts/?.lua;" .. package.path local plugins_utils = require("plugins_utils") local json = require "dkjson" -- ################################################################# -- A key to access a hash table containing mappings between endpoint_conf_name and endpoint_key -- endpoint_key s are defined inside ./endpoint lua files, such as email.lua -- -- Example: -- ntop_mail -> mail -- customer_1_mail -> mail -- crew_es -> elasticsearch -- local ENDPOINT_CONFIG_TO_ENDPOINT_KEY = "ntopng.prefs.notification_endpoint.endpoint_conf_name_endpoint_key" -- A key to access a hash table containing mappings, for each endpoint_key, between every endpoint_conf_name and endpoint_params -- -- Example: -- notification endpoint mail has two configurations, `ntop_mail` and `customer_1_mail`, so the resulting entry -- ntopng.prefs.notification_endpoint.endpoint_key_mail.configs is as follows: -- ntop_mail -> {smtmp_server_name: "...", etc} -- customer_1_mail -> {smtp_server_name: "...", etc} -- local ENDPOINT_CONFIGS_KEY = "ntopng.prefs.notification_endpoint.endpoint_key_%s.configs" -- A key to atomically generate integer endpoint ids local ENDPOINT_NEXT_ID_KEY = "ntopng.prefs.notification_endpoint.next_endpoint_id" -- ################################################################# local endpoints = {} -- ################################################################# -- Key where it's saved a boolean indicating if the first endpoint has been created endpoints.FIRST_ENDPOINT_CREATED_CACHE_KEY = "ntopng.prefs.endpoint_hints.endpoint_created" -- ################################################################# function endpoints.get_types(exclude_builtin) local endpoint_types = {} -- Currently, we load all the available alert endpoints local available_endpoints = plugins_utils.getLoadedAlertEndpoints() -- Then, we actually consider vaid types for the notification configs -- only those modules that have their `endpoint_params` and `recipient_params`. -- Eventually, when the migration between alert endpoints and generic notification endpoints -- will be completed, all the available endpoints will have `endpoint_params` and `recipient_params`. for _, endpoint in ipairs(available_endpoints) do if endpoint.endpoint_params and endpoint.recipient_params and endpoint.endpoint_template and endpoint.recipient_template then for _, k in pairs({"plugin_key", "template_name"}) do if not endpoint.endpoint_template[k] or not endpoint.recipient_template[k] then goto continue end end -- See if only non-builtin endpoints have been requested (e.g., to populate UI fields) if not exclude_builtin or not endpoint.builtin then endpoint_types[endpoint.key] = endpoint end end ::continue:: end return endpoint_types end -- ################################################################# -- @brief Check if an endpoint configuration identified with `endpoint_id` exists -- @param endpoint_conf_name A string with the configuration name -- @return true if the configuration exists, false otherwise local function is_endpoint_config_existing(endpoint_conf_name) local configs = endpoints.get_configs() for _, conf in pairs(configs) do if conf.endpoint_conf_name == endpoint_conf_name then -- Another endpoint with the same name already existing return true, conf end end -- No other endpoint exists with the same name return false end -- ################################################################# -- @brief Set a configuration along with its params. Configuration name and params must be already sanitized -- @param endpoint_key A string with the notification endpoint key -- @param endpoint_id An integer identifier of the endpoint -- @param endpoint_conf_name A string with the configuration name -- @param safe_params A table with endpoint configuration params already sanitized -- @return nil local function set_endpoint_config_params(endpoint_key, endpoint_id, endpoint_conf_name, safe_params) if tonumber(endpoint_id) then -- Format the integer identifier as a string representation of the same integer -- This is necessary as subsequent Redis cache sets work with strings and not integers endpoint_id = string.format("%d", endpoint_id) else -- backward compatibility: we can ignore the cast to id because the it's a string (old endpoint type id) end -- Write the endpoint conf_name and its key in a hash ntop.setHashCache(ENDPOINT_CONFIG_TO_ENDPOINT_KEY, endpoint_id, endpoint_key) -- Before storing the configuration as safe_params, we need to extend safe_params -- to also include the endpoint configuration name. -- This is necessary as endpoints are identified with integers in newer implementations -- so the name must be stored in the configuration safe_params["endpoint_conf_name"] = endpoint_conf_name -- Endpoint config is the merge of safe_params plus the endpoint_conf_name -- Write the endpoint config in another hash local k = string.format(ENDPOINT_CONFIGS_KEY, endpoint_key) ntop.setHashCache(k, endpoint_id, json.encode(safe_params)) end -- ################################################################# -- @brief Read the configuration parameters of an existing configuration -- @param endpoint_id An integer identifier of the endpoint -- @return A table with two keys: endpoint_key and endpoint_params or nil if the configuration isn't found local function read_endpoint_config_raw(endpoint_id) if tonumber(endpoint_id) then -- Subsequent Redis keys access work with strings so, the integer must be converted to its string representation endpoint_id = string.format("%d", endpoint_id) else -- Old endpoint configs were strings, so there's nothing to do here end local endpoint_key = ntop.getHashCache(ENDPOINT_CONFIG_TO_ENDPOINT_KEY, endpoint_id) local k = string.format(ENDPOINT_CONFIGS_KEY, endpoint_key) -- Endpoint params are saved as JSON local endpoint_params_json = ntop.getHashCache(k, endpoint_id) -- Decode params as a table local endpoint_params = json.decode(endpoint_params_json) if endpoint_params and endpoint_params ~= '' then return { endpoint_key = endpoint_key, endpoint_id = endpoint_id, -- For backward compatibility, endpoint_id is returned as the endpoint_conf_name when not name is found inside endpoint_conf endpoint_conf_name = endpoint_params.endpoint_conf_name or endpoint_id, endpoint_params = endpoint_params } end end -- ################################################################# -- @brief Sanity checks for the endpoint key -- @param endpoint_key A string with the notification endpoint key -- @return true if the sanity checks are ok, false otherwise local function check_endpoint_key(endpoint_key) if not endpoints.get_types()[endpoint_key] then return false, {status = "failed", error = {type = "endpoint_not_existing"}} end return true end -- ################################################################# -- @brief Sanity checks for the endpoint configuration name -- @param endpoint_conf_name A string with the configuration name -- @return true if the sanity checks are ok, false otherwise local function check_endpoint_conf_name(endpoint_conf_name) if not endpoint_conf_name or endpoint_conf_name == "" then return false, {status = "failed", error = {type = "invalid_endpoint_conf_name"}} end return true end -- ################################################################# -- @brief Sanity checks for the endpoint configuration parameters -- @param endpoint_key A string with the notification endpoint key -- @param endpoint_params A table with endpoint configuration params that will be possibly sanitized -- @return false with a description of the error, or true, with a table containing sanitized configuration params. local function check_endpoint_config_params(endpoint_key, endpoint_params) if not endpoint_params or not type(endpoint_params) == "table" then return false, {status = "failed", error = {type = "invalid_endpoint_params"}} end -- Create a safe_params table with only expected params local endpoint = endpoints.get_types()[endpoint_key] local safe_params = {} -- So iterate across all expected params of the current endpoint for _, param in ipairs(endpoint.endpoint_params) do -- param is a lua table so we access its elements local param_name = param["param_name"] local optional = param["optional"] if endpoint_params and endpoint_params[param_name] and not safe_params[param_name] then safe_params[param_name] = endpoint_params[param_name] elseif not optional then return false, {status = "failed", error = {type = "missing_mandatory_param", missing_param = param_name}} end end return true, {status = "OK", safe_params = safe_params, builtin = endpoint.builtin or false} end -- ################################################################# -- @brief Add a new configuration endpoint -- @param endpoint_key A string with the notification endpoint key -- @param endpoint_conf_name A string with the configuration name -- @param endpoint_params A table with endpoint configuration params that will be possibly sanitized -- @return A table with a key status which is either "OK" or "failed". When "failed", the table contains another key "error" with an indication of the issue function endpoints.add_config(endpoint_key, endpoint_conf_name, endpoint_params) local ok, status = check_endpoint_key(endpoint_key) if not ok then return status end ok, status = check_endpoint_conf_name(endpoint_conf_name) if not ok then return status end -- Is the config already existing? local is_existing, existing_conf = is_endpoint_config_existing(endpoint_conf_name) if is_existing then return {status = "failed", endpoint_id = existing_conf.endpoint_id, endpoint_conf_name = existing_conf.endpoint_conf_name, error = { type = "endpoint_config_already_existing", endpoint_conf_name = existing_conf.endpoint_conf_name, } } end -- Are the submitted params those expected by the endpoint? ok, status = check_endpoint_config_params(endpoint_key, endpoint_params) if not ok then return status end local safe_params = status["safe_params"] if status.builtin then -- If the endpoint is a builtin endpoint, a special boolean safe param builtin is added to the configuration safe_params["builtin"] = true else if isEmptyString(ntop.getPref(endpoints.FIRST_ENDPOINT_CREATED_CACHE_KEY)) then -- set a flag to indicate that an endpoint has been created ntop.setPref(endpoints.FIRST_ENDPOINT_CREATED_CACHE_KEY, "1") end end -- Set the config -- Atomically generate and endpoint identificator local endpoint_id = ntop.incrCache(ENDPOINT_NEXT_ID_KEY) -- Save endpoint params, along with the newly generated identificator set_endpoint_config_params(endpoint_key, endpoint_id, endpoint_conf_name, safe_params) return { status = "OK", endpoint_id = endpoint_id -- This is the newly assigned enpoint it } end -- ################################################################# -- @brief Edit the configuration parameters of an existing endpoint -- @param endpoint_id An integer identifier of the endpoint -- @param endpoint_conf_name A string with the configuration name -- @param endpoint_params A table with endpoint configuration params that will be possibly sanitized -- @return A table with a key status which is either "OK" or "failed". When "failed", the table contains another key "error" with an indication of the issue function endpoints.edit_config(endpoint_id, endpoint_conf_name, endpoint_params) local ok, status = check_endpoint_conf_name(endpoint_conf_name) if not ok then return status end -- TODO: remove when migration of edit_endpoint.lua is complete and passes the id if tonumber(endpoint_id) then endpoint_id = string.format("%d", endpoint_id) else -- backward compatibility: we can ignore the cast to id because the it's a string (old endpoint type id) end -- Is the config already existing? local ec = read_endpoint_config_raw(endpoint_id) if not ec then return {status = "failed", error = {type = "endpoint_config_not_existing", endpoint_conf_name = endpoint_conf_name}} end -- Are the submitted params those expected by the endpoint? ok, status = check_endpoint_config_params(ec["endpoint_key"], endpoint_params) if not ok then return status end local safe_params = status["safe_params"] -- Overwrite the config set_endpoint_config_params(ec["endpoint_key"], ec["endpoint_id"], endpoint_conf_name, safe_params) return {status = "OK"} end -- ################################################################# -- @brief Delete the configuration parameters of an existing endpoint configuration -- @param endpoint_id An integer identifier of the endpoint -- @return A table with a key status which is either "OK" or "failed". When "failed", the table contains another key "error" with an indication of the issue function endpoints.delete_config(endpoint_id) -- TODO: remove when migration of edit_endpoint.lua is complete and passes the id if tonumber(endpoint_id) then endpoint_id = string.format("%d", endpoint_id) end -- Is the config already existing? local ec = read_endpoint_config_raw(endpoint_id) if not ec then return {status = "failed", error = {type = "endpoint_config_not_existing", endpoint_conf_name = endpoint_id}} end -- Delete the all the recipients associated to this config recipients local recipients = require "recipients" recipients.delete_recipients_by_conf(endpoint_id) -- Now delete the actual config local k = string.format(ENDPOINT_CONFIGS_KEY, ec["endpoint_key"]) ntop.delHashCache(k, endpoint_id) ntop.delHashCache(ENDPOINT_CONFIG_TO_ENDPOINT_KEY, endpoint_id) return {status = "OK"} end -- ################################################################# -- @brief Retrieve the configuration parameters of an existing endpoint configuration -- @param endpoint_id An integer identifier of the endpoint -- @return A table with a key status which is either "OK" or "failed". -- When "failed", the table contains another key "error" with an indication of the issue. -- When "OK", the table contains "endpoint_conf_name", "endpoint_key", and "endpoint_conf" with the results function endpoints.get_endpoint_config(endpoint_id) -- Is the config already existing? local ec = read_endpoint_config_raw(endpoint_id) if not ec then return {status = "failed", error = {type = "endpoint_config_not_existing", endpoint_conf_name = endpoint_id}} end -- Decode endpoint configuration params -- NOTE: in newer implementations, configuration params also contain the endpoint name -- in older implementations, the endpoint name was used also as endpoint id local endpoint_conf = ec["endpoint_params"] return { status = "OK", endpoint_id = endpoint_id, -- For backward compatibility, endpoint_id is returned as the endpoint_conf_name when not name is found inside endpoint_conf endpoint_conf_name = endpoint_conf["endpoint_conf_name"] or endpoint_id, endpoint_key = ec["endpoint_key"], endpoint_conf = endpoint_conf } end -- ################################################################# -- @brief Retrieve all the available configurations and configuration params -- @param exclude_builtin Whether to exclude builtin configs. Default is false. -- @return A lua array with a as many elements as the number of existing configurations. -- Each element is the result of `endpoints.get_endpoint_config` function endpoints.get_configs(exclude_builtin) local res = {} for endpoint_key, endpoint in pairs(endpoints.get_types()) do local k = string.format(ENDPOINT_CONFIGS_KEY, endpoint_key) local all_configs = ntop.getHashAllCache(k) or {} for endpoint_id, endpoint_params in pairs(all_configs) do local ec = endpoints.get_endpoint_config(endpoint_id) if not exclude_builtin or not ec.endpoint_conf.builtin then res[#res + 1] = ec end end end return res end -- ################################################################# -- @brief Retrieve all the available configurations, configuration params, and associated recipients -- @return A lua array with as many elements as the number of existing configurations. -- Each element is the result of `endpoints.get_endpoint_config` -- with an extra key `recipients`. function endpoints.get_configs_with_recipients(include_stats) local recipients = require "recipients" local configs = endpoints.get_configs() for _, conf in pairs(configs) do conf["recipients"] = recipients.get_recipients_by_conf(conf.endpoint_id, include_stats) end return configs end -- ################################################################# -- @brief Clear all the existing endpoint configurations -- @return Always return a table {status = "OK"} function endpoints.reset_configs() local all_configs = endpoints.get_configs() for _, endpoint_params in pairs(all_configs) do endpoints.delete_config(endpoint_params.endpoint_id) end return {status = "OK"} end -- ################################################################# -- @brief Restore a full set of configurations, exported with get_configs_with_recipients -- including configuration params and associated recipients function endpoints.add_configs_with_recipients(configs) local recipients = require "recipients" local rc = true -- Restore Endpoints for _, conf in ipairs(configs) do local endpoint_key = conf.endpoint_key local endpoint_conf_name = conf.endpoint_conf_name local endpoint_params = conf.endpoint_conf if endpoint_key and endpoint_conf_name and endpoint_params and conf.recipients and not endpoint_params.builtin then local ret = endpoints.add_config(endpoint_key, endpoint_conf_name, endpoint_params) if not ret or not ret.endpoint_id then rc = false else -- Restore Recipients for _, recipient_conf in ipairs(conf.recipients) do local endpoint_recipient_name = recipient_conf.recipient_name local check_categories = recipient_conf.check_categories local minimum_severity = recipient_conf.minimum_severity local recipient_params = recipient_conf.recipient_params ret = recipients.add_recipient(ret.endpoint_id, endpoint_recipient_name, check_categories, minimum_severity, false, -- Not necessary to bind to every pool: the restore takes care of tis automatically recipient_params) if not ret or not ret.status or ret.status ~= "OK" then rc = false end end end end end return rc end -- ################################################################# return endpoints
gpl-3.0
purebn/ShadowBot
plugins/anti_bot.lua
1
3079
local function isBotAllowed (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId local banned = redis:get(hash) return banned end local function allowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:set(hash, true) end local function disallowBot (userId, chatId) local hash = 'anti-bot:allowed:'..chatId..':'..userId redis:del(hash) end -- Is anti-bot enabled on chat local function isAntiBotEnabled (chatId) local hash = 'anti-bot:enabled:'..chatId local enabled = redis:get(hash) return enabled end local function enableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:set(hash, true) end local function disableAntiBot (chatId) local hash = 'anti-bot:enabled:'..chatId redis:del(hash) end local function isABot (user) -- Flag its a bot 0001000000000000 local binFlagIsBot = 4096 local result = bit32.band(user.flags, binFlagIsBot) return result == binFlagIsBot end local function kickUser(userId, chatId) local chat = 'chat#id'..chatId local user = 'user#id'..userId chat_del_user(chat, user, function (data, success, result) if success ~= 1 then print('I can\'t kick '..data.user..' but should be kicked') end end, {chat=chat, user=user}) end local function run (msg, matches) -- We wont return text if is a service msg if matches[1] ~= 'chat_add_user' and matches[1] ~= 'chat_add_user_link' then if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' end end local chatId = msg.to.id if matches[1] == 'enable' then enableAntiBot(chatId) return 'ورود ربات ها ممنوع شد' end if matches[1] == 'disable' then disableAntiBot(chatId) return 'ورود ربات ها ازاد شد' end if matches[1] == 'allow' then local userId = matches[2] allowBot(userId, chatId) return 'Bot '..userId..' allowed' end if matches[1] == 'disallow' then local userId = matches[2] disallowBot(userId, chatId) return 'Bot '..userId..' disallowed' end if matches[1] == 'chat_add_user' or matches[1] == 'chat_add_user_link' then local user = msg.action.user or msg.from if isABot(user) then print('It\'s a bot!') if isAntiBotEnabled(chatId) then print('Anti bot is enabled') local userId = user.id if not isBotAllowed(userId, chatId) then kickUser(userId, chatId) else print('This bot is allowed') end end end end end return { description = 'When bot enters group kick it.', usage = { '!antibot enable: Enable Anti-bot on current chat', '!antibot disable: Disable Anti-bot on current chat', '!antibot allow <botId>: Allow <botId> on this chat', '!antibot disallow <botId>: Disallow <botId> on this chat' }, patterns = { '^!antibot (allow) (%d+)$', '^!antibot (disallow) (%d+)$', '^!antibot (enable)$', '^!antibot (disable)$', '^!!tgservice (chat_add_user)$', '^!!tgservice (chat_add_user_link)$' }, run = run }
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Nashmau/npcs/Wata_Khamazom.lua
1
1401
----------------------------------- -- Area: Nashmau -- NPC: Wata Khamazom -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; require("scripts/zones/Nashmau/TextIDs"); ----------------------------------- -- 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 0x4341,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
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Code/McmlBlocklyDef/McmlBlocklyDef_Attrs.lua
1
3511
--[[ Title: language configuration plugin Author(s): LiXizhi Date: 2019/10/28 Desc: use the lib: ------------------------------------------------------- ------------------------------------------------------- ]] NPL.export({ ----------------------- { type = "mcml_attrs_style_key_value", message0 = "%1 = \"%2\"%3%4", arg0 = { { name = "key", type = "field_dropdown", options = { { "style", "style"}, }, }, { name = "start_dummy", type = "input_dummy", }, { name = "end_dummy", type = "input_dummy", }, { name = "btn", type = "field_button", content = { src = "png/plus-2x.png" }, width = 16, height = 16, callback = "FIELD_BUTTON_CALLBACK_append_mcml_attr" }, }, output = {type = "null",}, category = "McmlAttrs", helpUrl = "", canRun = false, func_description_lua_provider = [[ var key_value = block.getFieldValue("key"); var attrs_value = Blockly.Extensions.readTextFromMcmlAttrs(block,"Lua"); var s = key_value + "='" + attrs_value + "'" return [s]; ]], ToNPL = function(self) return string.format('%s="%s"',self:getFieldValue('key'),self:getFieldValue('value')); end, examples = {{desc = "", canRun = false, code = [[ ]]}}, }, { type = "mcml_attrs_key_value_onclick", message0 = "%1 = \"%2\"", arg0 = { { name = "key", type = "field_dropdown", options = { { "onclick", "onclick"}, }, }, { name = "value", type = "input_value", shadow = { type = "text"}, }, }, output = {type = "null",}, category = "McmlAttrs", helpUrl = "", canRun = false, func_description = '%s=%s', ToNPL = function(self) return string.format('%s=%s',self:getFieldValue('key'),self:getFieldValue('value')); end, examples = {{desc = "", canRun = false, code = [[ ]]}}, }, { type = "mcml_attrs_key_value", message0 = "%1 = \"%2\"", arg0 = { { name = "key", type = "field_dropdown", options = { { "value", "value"}, { "name", "name"}, { "class", "class"}, { "align", "align"}, { "checked", "checked"}, { "Minimum", "Minimum"}, { "Maximum", "Maximum"}, { "min", "min"}, { "max", "max"}, { "setter", "setter"}, { "getter", "getter"}, { "tooltip", "tooltip"}, }, }, { name = "value", type = "input_value", shadow = { type = "text"}, }, }, output = {type = "null",}, category = "McmlAttrs", helpUrl = "", canRun = false, func_description = '%s=%s', ToNPL = function(self) return string.format('%s=%s',self:getFieldValue('key'),self:getFieldValue('value')); end, examples = {{desc = "", canRun = false, code = [[ ]]}}, }, { type = "mcml_attrs_align_key_value", message0 = "%1 = \"%2\"", arg0 = { { name = "key", type = "field_dropdown", options = { { "align", "align"}, }, }, { name = "value", type = "field_dropdown", options = { { "left", "left"}, { "center", "center"}, { "right", "right"}, }, }, }, output = {type = "null",}, category = "McmlAttrs", helpUrl = "", canRun = false, func_description = '%s="%s"', ToNPL = function(self) return string.format('%s="%s"',self:getFieldValue('key'),self:getFieldValue('value')); end, examples = {{desc = "", canRun = false, code = [[ ]]}}, }, --------------------- })
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Windurst_Woods/npcs/Anillah.lua
5
1035
----------------------------------- -- Area: Windurst Woods -- NPC: Anillah -- Type: Craftsman -- @zone: 241 -- @pos: -34.800 -2.25 -119.950 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x271f); 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
LuaDist2/zee
build-aux/mkdotzee.lua
1
1426
-- Produce dotzee.sample -- -- Copyright (c) 2012-2014 Free Software Foundation, Inc. -- -- This file is part of Zee. -- -- This program is free software; you can redistribute it and/or modify it -- under the terms of the GNU General Public License as published by -- the Free Software Foundation; either version 3, or (at your option) -- any later version. -- -- This program is distributed in the hope that it will be useful, but -- WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU -- General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- This script should be run as zee -e "loadfile ('script.lua') ()" -- Don't note where the contents of this file comes from or that it's -- auto-generated, because it's ugly in a user configuration file. io.write ( [[ -- ]] .. os.getenv ("PACKAGE_NAME") .. [[ configuration -- Rebind keys with: -- bind_key("key", "func") ]]) for name, var in pairs (env) do if not command_exists (name) then io.writelines ("-- " .. var.doc:gsub ("\n", "\n; "), "-- Default value is " .. var.val .. ".", "call_command (\"preferences-set-variable\", \"" .. name .. "\", \"" .. var.val .. "\")", "") end end os.exit ()
gpl-3.0
flyzjhz/witi-openwrt
package/ramips/ui/luci-mtk/src/protocols/ppp/luasrc/model/cbi/admin_network/proto_ppp.lua
59
3761
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- local map, section, net = ... local device, username, password local ipv6, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand, mtu device = section:taboption("general", Value, "device", translate("Modem device")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/tty*S*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", Flag, "ipv6", translate("Enable IPv6 negotiation on the PPP link")) ipv6.default = ipv6.disabled end defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end function keepalive_failure.write() end function keepalive_failure.remove() end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger" mtu = section:taboption("advanced", Value, "mtu", translate("Override MTU")) mtu.placeholder = "1500" mtu.datatype = "max(9200)"
gpl-2.0
pakoito/ToME---t-engine4
game/engines/default/modules/boot/data/general/grids/basic.lua
3
5498
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org ----------------------------------------- -- Basic floors ----------------------------------------- newEntity{ define_as = "FLOOR", type = "floor", subtype = "floor", name = "floor", image = "terrain/marble_floor.png", display = '.', color_r=255, color_g=255, color_b=255, back_color=colors.DARK_GREY, grow = "WALL", } ----------------------------------------- -- Walls ----------------------------------------- newEntity{ define_as = "WALL", type = "wall", subtype = "floor", name = "wall", image = "terrain/granite_wall1.png", display = '#', color_r=255, color_g=255, color_b=255, back_color=colors.GREY, z = 3, nice_tiler = { method="wall3d", inner={"WALL", 100, 1, 5}, north={"WALL_NORTH", 100, 1, 5}, south={"WALL_SOUTH", 10, 1, 17}, north_south="WALL_NORTH_SOUTH", small_pillar="WALL_SMALL_PILLAR", pillar_2="WALL_PILLAR_2", pillar_8={"WALL_PILLAR_8", 100, 1, 5}, pillar_4="WALL_PILLAR_4", pillar_6="WALL_PILLAR_6" }, always_remember = true, does_block_move = true, can_pass = {pass_wall=1}, block_sight = true, air_level = -20, dig = "FLOOR", } for i = 1, 5 do newEntity{ base = "WALL", define_as = "WALL"..i, image = "terrain/granite_wall1_"..i..".png", z = 3} newEntity{ base = "WALL", define_as = "WALL_NORTH"..i, image = "terrain/granite_wall1_"..i..".png", z = 3, add_displays = {class.new{image="terrain/granite_wall3.png", z=18, display_y=-1}}} newEntity{ base = "WALL", define_as = "WALL_PILLAR_8"..i, image = "terrain/granite_wall1_"..i..".png", z = 3, add_displays = {class.new{image="terrain/granite_wall_pillar_8.png", z=18, display_y=-1}}} end newEntity{ base = "WALL", define_as = "WALL_NORTH_SOUTH", image = "terrain/granite_wall2.png", z = 3, add_displays = {class.new{image="terrain/granite_wall3.png", z=18, display_y=-1}}} newEntity{ base = "WALL", define_as = "WALL_SOUTH", image = "terrain/granite_wall2.png", z = 3} for i = 1, 17 do newEntity{ base = "WALL", define_as = "WALL_SOUTH"..i, image = "terrain/granite_wall2_"..i..".png", z = 3} end newEntity{ base = "WALL", define_as = "WALL_SMALL_PILLAR", image = "terrain/marble_floor.png", z=1, add_displays = {class.new{image="terrain/granite_wall_pillar_small.png",z=3}, class.new{image="terrain/granite_wall_pillar_small_top.png", z=18, display_y=-1}}} newEntity{ base = "WALL", define_as = "WALL_PILLAR_6", image = "terrain/marble_floor.png", z=1, add_displays = {class.new{image="terrain/granite_wall_pillar_3.png",z=3}, class.new{image="terrain/granite_wall_pillar_9.png", z=18, display_y=-1}}} newEntity{ base = "WALL", define_as = "WALL_PILLAR_4", image = "terrain/marble_floor.png", z=1, add_displays = {class.new{image="terrain/granite_wall_pillar_1.png",z=3}, class.new{image="terrain/granite_wall_pillar_7.png", z=18, display_y=-1}}} newEntity{ base = "WALL", define_as = "WALL_PILLAR_2", image = "terrain/marble_floor.png", z=1, add_displays = {class.new{image="terrain/granite_wall_pillar_2.png",z=3}}} ----------------------------------------- -- Doors ----------------------------------------- newEntity{ define_as = "DOOR", type = "wall", subtype = "floor", name = "door", image = "terrain/granite_door1.png", display = '+', color_r=238, color_g=154, color_b=77, back_color=colors.DARK_UMBER, nice_tiler = { method="door3d", north_south="DOOR_VERT", west_east="DOOR_HORIZ" }, notice = true, always_remember = true, block_sight = true, door_opened = "DOOR_OPEN", dig = "FLOOR", } newEntity{ define_as = "DOOR_OPEN", type = "wall", subtype = "floor", name = "open door", image="terrain/granite_door1_open.png", display = "'", color_r=238, color_g=154, color_b=77, back_color=colors.DARK_GREY, always_remember = true, door_closed = "DOOR", } newEntity{ base = "DOOR", define_as = "DOOR_HORIZ", image = "terrain/granite_door1.png", add_displays = {class.new{image="terrain/granite_wall3.png", z=18, display_y=-1}}, door_opened = "DOOR_HORIZ_OPEN"} newEntity{ base = "DOOR_OPEN", define_as = "DOOR_HORIZ_OPEN", image = "terrain/marble_floor.png", add_displays = {class.new{image="terrain/granite_door1_open.png", z=17}, class.new{image="terrain/granite_wall3.png", z=18, display_y=-1}}, door_closed = "DOOR_HORIZ"} newEntity{ base = "DOOR", define_as = "DOOR_VERT", image = "terrain/marble_floor.png", add_displays = {class.new{image="terrain/granite_door1_vert.png", z=17}, class.new{image="terrain/granite_door1_vert_north.png", z=18, display_y=-1}}, door_opened = "DOOR_OPEN_VERT", dig = "DOOR_OPEN_VERT"} newEntity{ base = "DOOR_OPEN", define_as = "DOOR_OPEN_VERT", image = "terrain/marble_floor.png", add_displays = {class.new{image="terrain/granite_door1_open_vert.png", z=17}, class.new{image="terrain/granite_door1_open_vert_north.png", z=18, display_y=-1}}, door_closed = "DOOR_VERT"}
gpl-3.0
coronalabs/plugins-source-bit
Corona/main.lua
1
2567
-------------------------------------------------------------------------------- -- Sample code is MIT licensed, see http://www.coronalabs.com/links/code/license -- Copyright (C) 2012 Corona Labs Inc. All Rights Reserved. -------------------------------------------------------------------------------- print( "Bit sample start." ) local bit = require( "plugin.bit" ) local vb = { 0, 1, -1, 2, -2, 0x12345678, 0x87654321, 0x33333333, 0x77777777, 0x55aa55aa, 0xaa55aa55, 0x7fffffff, 0x80000000, 0xffffffff } local function cksum(name, s, r) local z = 0 for i=1,#s do z = (z + string.byte(s, i)*i) % 2147483629 end if z ~= r then error("bit."..name.." test failed (got "..z..", expected "..r..")", 0) end end local function check_unop(name, r) local f = bit[name] local s = "" if pcall(f) or pcall(f, "z") or pcall(f, true) then error("bit."..name.." fails to detect argument errors", 0) end for _,x in ipairs(vb) do s = s..","..tostring(f(x)) end cksum(name, s, r) end local function check_binop(name, r) local f = bit[name] local s = "" if pcall(f) or pcall(f, "z") or pcall(f, true) then error("bit."..name.." fails to detect argument errors", 0) end for _,x in ipairs(vb) do for _,y in ipairs(vb) do s = s..","..tostring(f(x, y)) end end cksum(name, s, r) end local function check_binop_range(name, r, yb, ye) local f = bit[name] local s = "" if pcall(f) or pcall(f, "z") or pcall(f, true) or pcall(f, 1, true) then error("bit."..name.." fails to detect argument errors", 0) end for _,x in ipairs(vb) do for y=yb,ye do s = s..","..tostring(f(x, y)) end end cksum(name, s, r) end local function check_shift(name, r) check_binop_range(name, r, 0, 31) end -- Minimal sanity checks. assert(0x7fffffff == 2147483647, "broken hex literals") assert(0xffffffff == -1 or 0xffffffff == 2^32-1, "broken hex literals") assert(tostring(-1) == "-1", "broken tostring()") assert(tostring(0xffffffff) == "-1" or tostring(0xffffffff) == "4294967295", "broken tostring()") assert( bit.bor( 1, 2, 4, 8 ) == 15 ) assert( bit.band( 0x12345678, 0xff ) == 0x00000078 ) assert( bit.bxor( 0xa5a5f0f0, 0xaa55ff00 ) == 0x0ff00ff0 ) assert( bit.lshift( 1, 8 ) == 256 ) assert( bit.lshift( 0x87654321, 12 ) == 0x54321000 ) assert( bit.rshift( 0x87654321, 12 ) == 0x00087654 ) assert( bit.rol( 0x12345678, 12 ) == 0x45678123 ) assert( bit.ror( 0x12345678, 12 ) == 0x67812345 ) assert( bit.bswap( 0x12345678 ) == 0x78563412 ) assert( bit.bswap( 0x78563412 ) == 0x12345678 ) print( "Bit sample done." )
mit
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Tasks/FillLineTask.lua
1
4214
--[[ Title: Create Line Author(s): LiXizhi Date: 2013/1/19 Desc: Replace blocks in the direction specifed until it is blocked by another block or max_radius is reached. Support undo/redo use the lib: ------------------------------------------------------------ NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/FillLineTask.lua"); local task = MyCompany.Aries.Game.Tasks.FillLine:new({blockX = result.blockX,blockY = result.blockY, blockZ = result.blockZ, side = result.side, fill_id=nil, max_radius = 20}) task:Run(); ------------------------------------------------------- ]] NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/UndoManager.lua"); local UndoManager = commonlib.gettable("MyCompany.Aries.Game.UndoManager"); local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic") local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine") local TaskManager = commonlib.gettable("MyCompany.Aries.Game.TaskManager") local Direction = commonlib.gettable("MyCompany.Aries.Game.Common.Direction"); local FillLine = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Task"), commonlib.gettable("MyCompany.Aries.Game.Tasks.FillLine")); FillLine.max_radius = 20; FillLine.min_radius = 4; FillLine.radius = FillLine.min_radius; function FillLine:ctor() self.step = 1; self.history = {}; end function FillLine:Run() if(self.blockX and self.side) then if(not self.fill_id) then self.fill_id, self.fill_data, self.fill_sdata = BlockEngine:GetBlockFull(self.blockX, self.blockY, self.blockZ); if(self.fill_id == 0) then return; end if(self.fill_data == 0) then self.fill_data = nil; end end local block_template = BlockEngine:GetBlock(self.blockX, self.blockY, self.blockZ); local side = self.side; self.dx, self.dy, self.dz = Direction.GetOffsetBySide(self.side); if(block_template and not block_template:canPlaceBlockOnSide(self.blockX+self.dx, self.blockY+self.dy, self.blockZ+self.dz, self.side)) then return; end self.radius = self.min_radius; local n; for n=1, self.max_radius do local block = BlockEngine:GetBlock(self.blockX+self.dx*n,self.blockY+self.dy*n,self.blockZ+self.dz*n) if(block and (not block.liquid or block.obstruction)) then self.max_radius = n; if(block.id == self.fill_id) then self.radius = n; end break; end end local tx, ty, tz = BlockEngine:real(self.blockX,self.blockY,self.blockZ); GameLogic.PlayAnimation({animationName = "Create",facingTarget = {x=tx, y=ty, z=tz},}); TaskManager.AddTask(self); end end function FillLine:FillLine(x, y, z) if(ParaTerrain.GetBlockTemplateByIdx(x,y,z) == self.from_id) then BlockEngine:SetBlock(x,y,z, self.to_id, nil, 3); self.new_blocks[#(self.new_blocks)+1] = {x,y,z}; end end local blocks = {} function FillLine:FrameMove() self.step = self.step + 1; self.blockX = self.blockX + (self.dx or 0); self.blockY = self.blockY + (self.dy or 0); self.blockZ = self.blockZ + (self.dz or 0); local block = BlockEngine:GetBlock(self.blockX,self.blockY,self.blockZ) if((not block or (block.liquid and not block.obstruction)) and self.step <= self.radius) then BlockEngine:SetBlock(self.blockX,self.blockY,self.blockZ, self.fill_id, self.fill_data, 3, self.fill_sdata); blocks[#blocks + 1] = {self.blockX,self.blockY,self.blockZ, self.fill_id, self.fill_data} if(GameLogic.GameMode:CanAddToHistory()) then self.history[#(self.history)+1] = {self.blockX,self.blockY,self.blockZ, block and block.id or 0}; end else self.finished = true; if(GameLogic.GameMode:CanAddToHistory()) then if(#(self.history) > 0) then UndoManager.PushCommand(self); end end GameLogic.GetFilters():apply_filters("lessonbox_change_region_blocks",blocks) blocks = {} end end function FillLine:Redo() if(self.blockX and self.fill_id and (#self.history)>0) then for _, b in ipairs(self.history) do BlockEngine:SetBlock(b[1],b[2],b[3], self.fill_id, self.fill_data, 3, self.fill_sdata); end end end function FillLine:Undo() if(self.blockX and self.fill_id and (#self.history)>0) then local _, b; for _, b in ipairs(self.history) do BlockEngine:SetBlock(b[1],b[2],b[3], b[4] or 0); end end end
gpl-2.0
pakoito/ToME---t-engine4
game/modules/tome/data/quests/paradoxology.lua
2
5055
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org name = "The Way We Weren't" desc = function(self, who) local desc = {} desc[#desc+1] = "You have met what seems to be a future version of yourself.\n" if self:isCompleted("combat") then desc[#desc+1] = "You tried to kill yourself to prevent you from doing something, or going somewhere... you were not very clear.\n" end if self:isCompleted("now-died") then desc[#desc+1] = "You were killed by your future self, and thus this event never occured.\n" end if self:isCompleted("future-died") then desc[#desc+1] = "You killed your future self. In the future, you might wish to avoid time-traveling back to this moment...\n" end return table.concat(desc, "\n") end on_status_change = function(self, who, status, sub) if sub then if self:isCompleted("future-died") or self:isCompleted("now-died") then who:setQuestStatus(self.id, engine.Quest.DONE) end end end generate = function(self, player, x, y) local a = mod.class.NPC.new{} a:replaceWith(player:resolveSource():cloneFull()) mod.class.NPC.castAs(a) engine.interface.ActorAI.init(a, a) a.no_drops = true a.energy.value = 0 a.player = nil a.rank = 4 a.name = a.name.." the Paradox Mage" a.color_r = 250 a.color_g = 50 a.color_b = 250 a:removeAllMOs() a.ai = "tactical" a.ai_state = {talent_in=1} a.faction = "enemies" a.max_life = a.max_life * 2 a.puuid = nil a.life = a.max_life -- Remove all talents local tids = {} for tid, _ in pairs(a.talents) do local t = a:getTalentFromId(tid) tids[#tids+1] = t end for i, t in ipairs(tids) do if t.mode == "sustained" and a:isTalentActive(t.id) then a:forceUseTalent(t.id, {ignore_energy=true}) end a.talents[t.id] = nil end -- Add talents a:learnTalent(a.T_TURN_BACK_THE_CLOCK, true, 3) a:learnTalent(a.T_BODY_REVERSION, true, 3) a:learnTalent(a.T_TEMPORAL_FUGUE, true, 4) a:learnTalent(a.T_DISENTANGLE, true, 4) a:learnTalent(a.T_RETHREAD, true, 3) a:learnTalent(a.T_GATHER_THE_THREADS, true, 3) a:learnTalent(a.T_FADE_FROM_TIME, true, 3) a:learnTalent(a.T_ASHES_TO_ASHES, true, 4) a:learnTalent(a.T_QUANTUM_SPIKE, true, 3) a:learnTalent(a.T_SEVER_LIFELINE, true, 5) a.talent_cd_reduction = a.talent_cd_reduction or {} a.talent_cd_reduction[a.T_DISENTANGLE] = 15 a.talents_cd[a.T_SEVER_LIFELINE] = 20 a:forceLevelup(a.level + 7) a:incIncStat("wil", 200) a.self_resurrect = nil -- In case this is a skeleton player a.on_die = function(self) local o = game.zone:makeEntityByName(game.level, "object", "RUNE_RIFT") o:identify(true) game.zone:addEntity(game.level, o, "object", self.x, self.y) game.player:setQuestStatus("paradoxology", engine.Quest.COMPLETED, "future-died") world:gainAchievement("PARADOX_FUTURE", p) game.logSeen(self, "#LIGHT_BLUE#Killing your own future self does feel weird, but you know that you can avoid this future. Just do not time travel.") end a.on_takehit = function(self, val) if not self.half_life_check and (self.life - val < self.max_life / 2) then self:doEmote("Meet the guardian!") game:onTickEnd(function() game:changeLevel(1, "paradox-plane") end) self.half_life_check = true self:heal(self.max_life) return 0 end return val end a.on_kill = function(self, who) local p = game.party:findMember{main=true} if who == p then p:setQuestStatus("paradoxology", engine.Quest.COMPLETED, "now-died") game.logSeen(self, "#LIGHT_BLUE#Your future self kills you! The timestreams are broken by the paradox!") game.logSeen(self, "#LIGHT_BLUE#All those events never happened. Except they did, somewhen.") game:setAllowedBuild("chronomancer_paradox_mage", true) world:gainAchievement("PARADOX_NOW", p) local rift = game.zone:makeEntityByName(game.level, "terrain", "RIFT") rift.change_level_check = function() game.log("This rift in time has been created by the paradox. You dare not enter it; it could make things worse. Another Warden will have to fix your mess.") return true end game.zone:addEntity(game.level, rift, "terrain", self.x, self.y) self.on_die = nil self:die() who.changed = true who.life = math.max(who.life, who.max_life * 0.3) return true end end game.zone:addEntity(game.level, a, "actor", x, y) local chat = require("engine.Chat").new("paradoxology", a, player) chat:invoke() end
gpl-3.0
Laterus/Darkstar-Linux-Fork
scripts/zones/The_Eldieme_Necropolis/npcs/Brazier.lua
1
3351
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Brazier -- Involved in Quests: Save my Sister -- @zone 195 -- @pos 101 -33 -59 (F-9) -- @pos 259 -33 99 (H-7) -- @pos 99 -33 98 (F-7) -- @pos 259 -33 -58 (H-9) ----------------------------------- 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) if(player:getQuestStatus(JEUNO,SAVE_MY_SISTER) == QUEST_ACCEPTED and player:getVar("saveMySisterFireLantern") < 4) then player:startEvent(0x002c); else player:messageSpecial(NOTHING_OUT_OF_ORDINARY); 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 == 0x002c and option == 0) then LanternOrder = player:getVar("saveMySisterFireLantern"); X = player:getXPos(); Z = player:getZPos(); if(LanternOrder == 0) then if(X >= 94 and X <= 105 and Z >= -68 and Z <= -51) then --(F-9) -- "The Ducal Guard's lantern lights dimly." player:messageSpecial(THE_LIGHT_DIMLY); player:setVar("saveMySisterFireLantern",1); else -- "Unexpectedly, the Ducal Guard's lantern refuses to light." player:messageSpecial(REFUSE_TO_LIGHT); end elseif(LanternOrder == 1) then if(X >= 251 and X <= 265 and Z >= 91 and Z <= 108) then --(H-7) -- "The light of Ducal Guard's lantern has intensified." player:messageSpecial(THE_LIGHT_HAS_INTENSIFIED); player:setVar("saveMySisterFireLantern",2); else -- "For some strange reason, the light of the Ducal Guard's lantern goes out..." player:messageSpecial(LANTERN_GOES_OUT); player:setVar("saveMySisterFireLantern",0); end elseif(LanternOrder == 2) then if(X >= 94 and X <= 105 and Z >= 91 and Z <= 108) then --(F-7) -- "The light of Ducal Guard's lantern has intensified." player:messageSpecial(THE_LIGHT_HAS_INTENSIFIED); player:setVar("saveMySisterFireLantern",3); else -- "For some strange reason, the light of the Ducal Guard's lantern goes out..." player:messageSpecial(LANTERN_GOES_OUT); player:setVar("saveMySisterFireLantern",0); end elseif(LanternOrder == 3) then if(X >= 251 and X <= 265 and Z >= -68 and Z <= -51) then --(H-9) -- "The Ducal Guard's lantern is fully lit!" player:messageSpecial(THE_LIGHT_IS_FULLY_LIT); player:setVar("saveMySisterFireLantern",4); else -- "For some strange reason, the light of the Ducal Guard's lantern goes out..." player:messageSpecial(LANTERN_GOES_OUT); player:setVar("saveMySisterFireLantern",0); end end end end;
gpl-3.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/World/AutoSaver.lua
1
4298
--[[ Title: Auto saver Author(s): LiXizhi Date: 2017/8/16 Desc: mostly a singleton class. Use Lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/World/AutoSaver.lua"); local AutoSaver = commonlib.gettable("MyCompany.Aries.Creator.Game.AutoSaver"); GameLogic.CreateGetAutoSaver():SetInterval(10) GameLogic.CreateGetAutoSaver():SetSaveMode(); GameLogic.CreateGetAutoSaver():SetTipMode(); GameLogic.CreateGetAutoSaver():SetAutoSaveOperationCount(15); ------------------------------------------------------- ]] NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/UndoManager.lua"); local UndoManager = commonlib.gettable("MyCompany.Aries.Game.UndoManager"); local AutoSaver = commonlib.inherit(nil,commonlib.gettable("MyCompany.Aries.Creator.Game.AutoSaver")); local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic") -- default to 10 mins AutoSaver.interval = 10 * 60 * 1000; AutoSaver.autosave_operation_count = 15; AutoSaver.mode = "tip"; AutoSaver.operation_count = 0; AutoSaver.timeout = false; function AutoSaver:ctor() GameLogic:Connect("WorldLoaded", self, self.OnEnterWorld, "UniqueConnection"); GameLogic:Connect("WorldUnloaded", self, self.OnLeaveWorld, "UniqueConnection"); GameLogic:Connect("WorldSaved", self, self.ResetTimer, "UniqueConnection"); self:SetTipMode(); end -- @param intervalMins: number mins to do auto save. default to 10 function AutoSaver:SetInterval(intervalMins) if(intervalMins) then self.interval = intervalMins * 1000 * 60; self:ResetTimer(); end end -- each user operation will increase the count by 1. -- When the operation count reach autosave_operation_count, we will automatically save. -- @param nCount: default to 1 function AutoSaver:IncreaseOperation(nCount) self.operation_count = self.operation_count + (nCount or 1); if(self.timeout and self.autosave_operation_count > 0 and self.operation_count > self.autosave_operation_count) then --self.operation_count = 1; self:DoAutoSave(); self:ResetTimer(); end end -- When the operation count reach autosave_operation_count, we will automatically save. function AutoSaver:SetAutoSaveOperationCount(nCount) self.autosave_operation_count = nCount; end -- default to tip mode, which will only show tips to user. -- If save mode, it will really save world to disk. function AutoSaver:SetSaveMode() self.mode = "save"; LOG.std(nil, "info", "AutoSaver", "save mode is on"); end -- default to tip mode, which will only show tips to user. -- If save mode, it will really save world to disk. function AutoSaver:SetTipMode() self.mode = "tip"; LOG.std(nil, "info", "AutoSaver", "tip mode is on"); end function AutoSaver:IsSaveMode() return self.mode == "save"; end function AutoSaver:Init() self.timer = self.timer or commonlib.Timer:new({callbackFunc = function(timer) self:DoAutoSave(); end}) self:ResetTimer(); end function AutoSaver:DoAutoSave() if(GameLogic.GameMode:IsEditor()) then if(self.autosave_operation_count > 0 and self.operation_count > self.autosave_operation_count) then self.timeout = false; self.operation_count = 1; if (self:IsSaveMode()) then -- save mode GameLogic.QuickSave(); else -- tip mode if(not GameLogic.IsRemoteWorld() and not ParaMovie.IsRecording()) then if(System.options.IsMobilePlatform) then GameLogic.AddBBS("UndoManager", L"记得保存你的世界~", 5000, "0 255 0"); else GameLogic.AddBBS("UndoManager", L"记得保存你的世界哦~(Ctrl+S)", 5000, "0 255 0"); end end end else self.timeout = true; end end end function AutoSaver:OnEnterWorld() UndoManager:Connect("commandAdded", self, self.IncreaseOperation, "UniqueConnection"); self:Init(); end function AutoSaver:OnLeaveWorld() UndoManager:Disconnect("commandAdded", self, self.IncreaseOperation); if(self:IsSaveMode()) then -- TODO: shall we save on leave, currently this is done manually by external logics. end if(self.timer) then self.timer:Change(); end -- always revert to tip mode, this is safer self:SetTipMode(); end -- when the user manually saved the world, we should reset timer. function AutoSaver:ResetTimer() if (self.timer) then self.timer:Change(self.interval, self.interval); end end
gpl-2.0
electrodude/pipeworks
teleport_tube.lua
2
7775
local filename=minetest.get_worldpath() .. "/teleport_tubes" local tp_tube_db = nil -- nil forces a read local tp_tube_db_version = 2.0 local function hash(pos) return string.format("%d", minetest.hash_node_position(pos)) end local function save_tube_db() local file, err = io.open(filename, "w") if file then tp_tube_db.version = tp_tube_db_version file:write(minetest.serialize(tp_tube_db)) tp_tube_db.version = nil io.close(file) else error(err) end end local function migrate_tube_db() local tmp_db = {} tp_tube_db.version = nil for key, val in pairs(tp_tube_db) do if(val.channel ~= "") then -- skip unconfigured tubes tmp_db[hash(val)] = val end end tp_tube_db = tmp_db save_tube_db() end local function read_tube_db() local file = io.open(filename, "r") if file ~= nil then local file_content = file:read("*all") io.close(file) if file_content and file_content ~= "" then tp_tube_db = minetest.deserialize(file_content) if(not tp_tube_db.version or tonumber(tp_tube_db.version) < tp_tube_db_version) then migrate_tube_db() end tp_tube_db.version = nil -- we add it back when saving return tp_tube_db -- we read sucessfully end end tp_tube_db = {} return tp_tube_db end -- updates or adds a tube local function set_tube(pos, channel, can_receive) local tubes = tp_tube_db or read_tube_db() local hash = hash(pos) local tube = tubes[hash] if tube then tube.channel = channel tube.cr = can_receive save_tube_db() return end -- we haven't found any tp tube to update, so lets add it tp_tube_db[hash] = {x=pos.x,y=pos.y,z=pos.z,channel=channel,cr=can_receive} save_tube_db() end local function remove_tube(pos) local tubes = tp_tube_db or read_tube_db() tubes[hash(pos)] = nil save_tube_db() end local function read_node_with_vm(pos) local vm = VoxelManip() local MinEdge, MaxEdge = vm:read_from_map(pos, pos) local data = vm:get_data() local area = VoxelArea:new({MinEdge = MinEdge, MaxEdge = MaxEdge}) return minetest.get_name_from_content_id(data[area:index(pos.x, pos.y, pos.z)]) end local function get_receivers(pos, channel) local tubes = tp_tube_db or read_tube_db() local receivers = {} local dirty = false for key, val in pairs(tubes) do -- skip all non-receivers and the tube that it came from as early as possible, as this is called often if (val.cr == 1 and val.channel == channel and (val.x ~= pos.x or val.y ~= pos.y or val.z ~= pos.z)) then local is_loaded = (minetest.get_node_or_nil(val) ~= nil) local node_name = is_loaded and minetest.get_node(pos).name or read_node_with_vm(val) if minetest.registered_nodes[node_name] and minetest.registered_nodes[node_name].is_teleport_tube then table.insert(receivers, val) else tp_tube_db[key] = nil dirty = true end end end if dirty then save_tube_db() end return receivers end local function update_meta(meta, can_receive) meta:set_int("can_receive", can_receive and 1 or 0) local cr_state = can_receive and "on" or "off" meta:set_string("formspec","size[8.6,2.2]".. "field[0.6,0.6;7,1;channel;Channel:;${channel}]".. "label[7.3,0;Receive]".. "image_button[7.3,0.3;1,0.6;pipeworks_button_" .. cr_state .. ".png;cr" .. (can_receive and 0 or 1) .. ";;;false;pipeworks_button_interm.png]".. "image[0.3,1.3;1,1;pipeworks_teleport_tube_inv.png]".. "label[1.6,1.2;channels are public by default]" .. "label[1.6,1.5;use <player>:<channel> for fully private channels]" .. "label[1.6,1.8;use <player>\\;<channel> for private receivers]" .. default.gui_bg.. default.gui_bg_img) end pipeworks.register_tube("pipeworks:teleport_tube", { description = "Teleporting Pneumatic Tube Segment", inventory_image = "pipeworks_teleport_tube_inv.png", noctr = { "pipeworks_teleport_tube_noctr.png" }, plain = { "pipeworks_teleport_tube_plain.png" }, ends = { "pipeworks_teleport_tube_end.png" }, short = "pipeworks_teleport_tube_short.png", node_def = { is_teleport_tube = true, tube = { can_go = function(pos,node,velocity,stack) velocity.x = 0 velocity.y = 0 velocity.z = 0 local channel = minetest.get_meta(pos):get_string("channel") if channel == "" then return {} end local target = get_receivers(pos, channel) if target[1] == nil then return {} end local d = math.random(1,#target) pos.x = target[d].x pos.y = target[d].y pos.z = target[d].z return pipeworks.meseadjlist end }, on_construct = function(pos) local meta = minetest.get_meta(pos) update_meta(meta, true) meta:set_string("infotext", "unconfigured Teleportation Tube") end, on_receive_fields = function(pos,formname,fields,sender) if not fields.channel -- ignore escaping or clientside manipulation of the form or not pipeworks.may_configure(pos, sender) then return end local new_channel = tostring(fields.channel):trim() local meta = minetest.get_meta(pos) local can_receive = meta:get_int("can_receive") -- check for private channels each time before actually changing anything -- to not even allow switching between can_receive states of private channels if new_channel ~= "" then local sender_name = sender:get_player_name() local name, mode = new_channel:match("^([^:;]+)([:;])") if name and mode and name ~= sender_name then --channels starting with '[name]:' can only be used by the named player if mode == ":" then minetest.chat_send_player(sender_name, "Sorry, channel '"..new_channel.."' is reserved for exclusive use by "..name) return --channels starting with '[name];' can be used by other players, but cannot be received from elseif mode == ";" and (fields.cr1 or (can_receive ~= 0 and not fields.cr0)) then minetest.chat_send_player(sender_name, "Sorry, receiving from channel '"..new_channel.."' is reserved for "..name) return end end end local dirty = false -- was the channel changed? local channel = meta:get_string("channel") if new_channel ~= channel then channel = new_channel meta:set_string("channel", channel) dirty = true end -- test if a can_receive button was pressed if fields.cr0 and can_receive ~= 0 then can_receive = 0 update_meta(meta, false) dirty = true elseif fields.cr1 and can_receive ~= 1 then can_receive = 1 update_meta(meta, true) dirty = true end -- save if we changed something, handle the empty channel while we're at it if dirty then if channel ~= "" then set_tube(pos, channel, can_receive) local cr_description = (can_receive == 1) and "sending and receiving" or "sending" meta:set_string("infotext", string.format("Teleportation Tube %s on '%s'", cr_description, channel)) else -- remove empty channel tubes, to not have to search through them remove_tube(pos) meta:set_string("infotext", "unconfigured Teleportation Tube") end end end, on_destruct = function(pos) remove_tube(pos) end }, }) minetest.register_craft( { output = "pipeworks:teleport_tube_1 2", recipe = { { "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" }, { "default:desert_stone", "default:mese", "default:desert_stone" }, { "homedecor:plastic_sheeting", "homedecor:plastic_sheeting", "homedecor:plastic_sheeting" } }, }) if minetest.get_modpath("mesecons_mvps") ~= nil then mesecon.register_on_mvps_move(function(moved_nodes) for _, n in ipairs(moved_nodes) do if string.find(n.node.name, "pipeworks:teleport_tube") ~= nil then local meta = minetest.get_meta(n.pos) set_tube(n.pos, meta:get_string("channel"), meta:get_int("can_receive")) end end end) end
lgpl-2.1
pixeljetstream/luajit_gfx_sandbox
runtime/lua/lanes.lua
3
22280
-- -- LANES.LUA -- -- Multithreading and -core support for Lua -- -- Authors: Asko Kauppi <akauppi@gmail.com> -- Benoit Germain <bnt.germain@gmail.com> -- -- History: see CHANGES -- --[[ =============================================================================== Copyright (C) 2007-10 Asko Kauppi <akauppi@gmail.com> Copyright (C) 2010-13 Benoit Germain <bnt.germain@gmail.com> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. =============================================================================== ]]-- local core = require "lanes.core" -- Lua 5.1: module() creates a global variable -- Lua 5.2: module() is gone -- almost everything module() does is done by require() anyway -- -> simply create a table, populate it, return it, and be done local lanes = {} -- this function is available in the public interface until it is called, after which it disappears lanes.configure = function( settings_) -- This check is for sublanes requiring Lanes -- -- TBD: We could also have the C level expose 'string.gmatch' for us. But this is simpler. -- if not string then error( "To use 'lanes', you will also need to have 'string' available.", 2) end -- -- Cache globals for code that might run under sandboxing -- local assert = assert local string_gmatch = assert( string.gmatch) local select = assert( select) local type = assert( type) local pairs = assert( pairs) local tostring = assert( tostring) local error = assert( error) local default_params = { nb_keepers = 1, on_state_create = nil, shutdown_timeout = 0.25, with_timers = true, track_lanes = false, demote_full_userdata = nil, verbose_errors = false, -- LuaJIT provides a thread-unsafe allocator by default, so we need to protect it when used in parallel lanes protect_allocator = (jit and jit.version) and true or false } local boolean_param_checker = function( val_) -- non-'boolean-false' should be 'boolean-true' or nil return val_ and (val_ == true) or true end local param_checkers = { nb_keepers = function( val_) -- nb_keepers should be a number > 0 return type( val_) == "number" and val_ > 0 end, with_timers = boolean_param_checker, protect_allocator = boolean_param_checker, on_state_create = function( val_) -- on_state_create may be nil or a function return val_ and type( val_) == "function" or true end, shutdown_timeout = function( val_) -- shutdown_timeout should be a number >= 0 return type( val_) == "number" and val_ >= 0 end, track_lanes = boolean_param_checker, demote_full_userdata = boolean_param_checker, verbose_errors = boolean_param_checker } local params_checker = function( settings_) if not settings_ then return default_params end -- make a copy of the table to leave the provided one unchanged, *and* to help ensure it won't change behind our back local settings = {} if type( settings_) ~= "table" then error "Bad parameter #1 to lanes.configure(), should be a table" end -- any setting not present in the provided parameters takes the default value for key, checker in pairs( param_checkers) do local my_param = settings_[key] local param if my_param ~= nil then param = my_param else param = default_params[key] end if not checker( param) then error( "Bad " .. key .. ": " .. tostring( param), 2) end settings[key] = param end return settings end local settings = core.configure and core.configure( params_checker( settings_)) or core.settings local thread_new = assert( core.thread_new) local max_prio = assert( core.max_prio) lanes.ABOUT = { author= "Asko Kauppi <akauppi@gmail.com>, Benoit Germain <bnt.germain@gmail.com>", description= "Running multiple Lua states in parallel", license= "MIT/X11", copyright= "Copyright (c) 2007-10, Asko Kauppi; (c) 2011-13, Benoit Germain", version = assert( core.version) } -- Making copies of necessary system libs will pass them on as upvalues; -- only the first state doing "require 'lanes'" will need to have 'string' -- and 'table' visible. -- local function WR(str) io.stderr:write( str.."\n" ) end local function DUMP( tbl ) if not tbl then return end local str="" for k,v in pairs(tbl) do str= str..k.."="..tostring(v).."\n" end WR(str) end ---=== Laning ===--- -- lane_h[1..n]: lane results, same as via 'lane_h:join()' -- lane_h[0]: can be read to make sure a thread has finished (always gives 'true') -- lane_h[-1]: error message, without propagating the error -- -- Reading a Lane result (or [0]) propagates a possible error in the lane -- (and execution does not return). Cancelled lanes give 'nil' values. -- -- lane_h.state: "pending"/"running"/"waiting"/"done"/"error"/"cancelled" -- -- Note: Would be great to be able to have '__ipairs' metamethod, that gets -- called by 'ipairs()' function to custom iterate objects. We'd use it -- for making sure a lane has ended (results are available); not requiring -- the user to precede a loop by explicit 'h[0]' or 'h:join()'. -- -- Or, even better, 'ipairs()' should start valuing '__index' instead -- of using raw reads that bypass it. -- ----- -- lanes.gen( [libs_str|opt_tbl [, ...],] lane_func ) ( [...] ) -> h -- -- 'libs': nil: no libraries available (default) -- "": only base library ('assert', 'print', 'unpack' etc.) -- "math,os": math + os + base libraries (named ones + base) -- "*": all standard libraries available -- -- 'opt': .priority: int (-3..+3) smaller is lower priority (0 = default) -- -- .cancelstep: bool | uint -- false: cancellation check only at pending Linda operations -- (send/receive) so no runtime performance penalty (default) -- true: adequate cancellation check (same as 100) -- >0: cancellation check every x Lua lines (small number= faster -- reaction but more performance overhead) -- -- .globals: table of globals to set for a new thread (passed by value) -- -- .required: table of packages to require -- -- .gc_cb: function called when the lane handle is collected -- -- ... (more options may be introduced later) ... -- -- Calling with a function parameter ('lane_func') ends the string/table -- modifiers, and prepares a lane generator. One can either finish here, -- and call the generator later (maybe multiple times, with different parameters) -- or add on actual thread arguments to also ignite the thread on the same call. local valid_libs= { ["package"] = true, ["table"] = true, ["io"] = true, ["os"] = true, ["string"] = true, ["math"] = true, ["debug"] = true, ["bit32"] = true, -- Lua 5.2 only, ignored silently under 5.1 -- ["base"] = true, ["coroutine"] = true, -- part of "base" in Lua 5.1 ["lanes.core"] = true } -- PUBLIC LANES API local function gen( ... ) local opt= {} local libs= nil local lev= 2 -- level for errors local n= select('#',...) if n==0 then error( "No parameters!" ) end for i=1,n-1 do local v= select(i,...) if type(v)=="string" then libs= libs and libs..","..v or v elseif type(v)=="table" then for k,vv in pairs(v) do opt[k]= vv end elseif v==nil then -- skip else error( "Bad parameter: "..tostring(v) ) end end local func= select(n,...) local functype = type(func) if functype ~= "function" and functype ~= "string" then error( "Last parameter not function or string: "..tostring(func)) end -- Check 'libs' already here, so the error goes in the right place -- (otherwise will be noticed only once the generator is called) -- "*" is a special case that doesn't require individual checking -- if libs and libs ~= "*" then local found = {} -- check that the caller only provides reserved library names for s in string_gmatch(libs, "[%a%d.]+") do if not valid_libs[s] then error( "Bad library name: " .. s) else found[s] = (found[s] or 0) + 1 if found[s] > 1 then error( "libs specification contains '" .. s .. "' more than once") end end end end local prio, cs, g_tbl, package_tbl, required, gc_cb for k,v in pairs(opt) do if k == "priority" then prio = (type( v) == "number") and v or error( "Bad 'prio' option: expecting number, got " .. type( v), lev) elseif k=="cancelstep" then cs = (v==true) and 100 or (v==false) and 0 or type(v)=="number" and v or error( "Bad cancelstep: "..tostring(v), lev ) elseif k=="globals" then g_tbl= v elseif k=="package" then package_tbl = (type( v) == "table") and v or error( "Bad package: " .. tostring( v), lev) elseif k=="required" then required= (type( v) == "table") and v or error( "Bad 'required' option: expecting table, got " .. type( v), lev) elseif k == "gc_cb" then gc_cb = (type( v) == "function") and v or error( "Bad 'gc_cb' option: expecting function, got " .. type( v), lev) --.. elseif k==1 then error( "unkeyed option: ".. tostring(v), lev ) else error( "Bad option: ".. tostring(k), lev ) end end if not package_tbl then package_tbl = package end -- Lane generator -- return function(...) return thread_new( func, libs, cs, prio, g_tbl, package_tbl, required, gc_cb, ...) -- args end end ---=== Timers ===--- -- PUBLIC LANES API local timer = function() error "timers are not active" end local timer_lane = nil local timers = timer if settings.with_timers ~= false then local timer_gateway = assert( core.timer_gateway) -- -- On first 'require "lanes"', a timer lane is spawned that will maintain -- timer tables and sleep in between the timer events. All interaction with -- the timer lane happens via a 'timer_gateway' Linda, which is common to -- all that 'require "lanes"'. -- -- Linda protocol to timer lane: -- -- TGW_KEY: linda_h, key, [wakeup_at_secs], [repeat_secs] -- local TGW_KEY= "(timer control)" -- the key does not matter, a 'weird' key may help debugging local TGW_QUERY, TGW_REPLY = "(timer query)", "(timer reply)" local first_time_key= "first time" local first_time= timer_gateway:get(first_time_key) == nil timer_gateway:set(first_time_key,true) -- -- Timer lane; initialize only on the first 'require "lanes"' instance (which naturally -- has 'table' always declared) -- if first_time then local now_secs = core.now_secs assert( type( now_secs) == "function") ----- -- Snore loop (run as a lane on the background) -- -- High priority, to get trustworthy timings. -- -- We let the timer lane be a "free running" thread; no handle to it -- remains. -- local timer_body = function() set_debug_threadname( "LanesTimer") -- -- { [deep_linda_lightuserdata]= { [deep_linda_lightuserdata]=linda_h, -- [key]= { wakeup_secs [,period_secs] } [, ...] }, -- } -- -- Collection of all running timers, indexed with linda's & key. -- -- Note that we need to use the deep lightuserdata identifiers, instead -- of 'linda_h' themselves as table indices. Otherwise, we'd get multiple -- entries for the same timer. -- -- The 'hidden' reference to Linda proxy is used in 'check_timers()' but -- also important to keep the Linda alive, even if all outside world threw -- away pointers to it (which would ruin uniqueness of the deep pointer). -- Now we're safe. -- local collection = {} local table_insert = assert( table.insert) local get_timers = function() local r = {} for deep, t in pairs( collection) do -- WR( tostring( deep)) local l = t[deep] for key, timer_data in pairs( t) do if key ~= deep then table_insert( r, {l, key, timer_data}) end end end return r end -- get_timers() -- -- set_timer( linda_h, key [,wakeup_at_secs [,period_secs]] ) -- local set_timer = function( linda, key, wakeup_at, period) assert( wakeup_at == nil or wakeup_at > 0.0) assert( period == nil or period > 0.0) local linda_deep = linda:deep() assert( linda_deep) -- Find or make a lookup for this timer -- local t1 = collection[linda_deep] if not t1 then t1 = { [linda_deep] = linda} -- proxy to use the Linda collection[linda_deep] = t1 end if wakeup_at == nil then -- Clear the timer -- t1[key]= nil -- Remove empty tables from collection; speeds timer checks and -- lets our 'safety reference' proxy be gc:ed as well. -- local empty = true for k, _ in pairs( t1) do if k ~= linda_deep then empty = false break end end if empty then collection[linda_deep] = nil end -- Note: any unread timer value is left at 'linda[key]' intensionally; -- clearing a timer just stops it. else -- New timer or changing the timings -- local t2 = t1[key] if not t2 then t2= {} t1[key]= t2 end t2[1] = wakeup_at t2[2] = period -- can be 'nil' end end -- set_timer() ----- -- [next_wakeup_at]= check_timers() -- Check timers, and wake up the ones expired (if any) -- Returns the closest upcoming (remaining) wakeup time (or 'nil' if none). local check_timers = function() local now = now_secs() local next_wakeup for linda_deep,t1 in pairs(collection) do for key,t2 in pairs(t1) do -- if key==linda_deep then -- no 'continue' in Lua :/ else -- 't2': { wakeup_at_secs [,period_secs] } -- local wakeup_at= t2[1] local period= t2[2] -- may be 'nil' if wakeup_at <= now then local linda= t1[linda_deep] assert(linda) linda:set( key, now ) -- 'pairs()' allows the values to be modified (and even -- removed) as far as keys are not touched if not period then -- one-time timer; gone -- t1[key]= nil wakeup_at= nil -- no 'continue' in Lua :/ else -- repeating timer; find next wakeup (may jump multiple repeats) -- repeat wakeup_at= wakeup_at+period until wakeup_at > now t2[1]= wakeup_at end end if wakeup_at and ((not next_wakeup) or (wakeup_at < next_wakeup)) then next_wakeup= wakeup_at end end end -- t2 loop end -- t1 loop return next_wakeup -- may be 'nil' end -- check_timers() local timer_gateway_batched = timer_gateway.batched set_finalizer( function( err, stk) if err and type( err) ~= "userdata" then WR( "LanesTimer error: "..tostring(err)) --elseif type( err) == "userdata" then -- WR( "LanesTimer after cancel" ) --else -- WR("LanesTimer finalized") end end) while true do local next_wakeup = check_timers() -- Sleep until next timer to wake up, or a set/clear command -- local secs if next_wakeup then secs = next_wakeup - now_secs() if secs < 0 then secs = 0 end end local key, what = timer_gateway:receive( secs, TGW_KEY, TGW_QUERY) if key == TGW_KEY then assert( getmetatable( what) == "Linda") -- 'what' should be a linda on which the client sets a timer local _, key, wakeup_at, period = timer_gateway:receive( 0, timer_gateway_batched, TGW_KEY, 3) assert( key) set_timer( what, key, wakeup_at, period and period > 0 and period or nil) elseif key == TGW_QUERY then if what == "get_timers" then timer_gateway:send( TGW_REPLY, get_timers()) else timer_gateway:send( TGW_REPLY, "unknown query " .. what) end --elseif secs == nil then -- got no value while block-waiting? -- WR( "timer lane: no linda, aborted?") end end end -- timer_body() timer_lane = gen( "*", { package= {}, priority = max_prio}, timer_body)() -- "*" instead of "io,package" for LuaJIT compatibility... end -- first_time ----- -- = timer( linda_h, key_val, date_tbl|first_secs [,period_secs] ) -- -- PUBLIC LANES API timer = function( linda, key, a, period ) if getmetatable( linda) ~= "Linda" then error "expecting a Linda" end if a == 0.0 then -- Caller expects to get current time stamp in Linda, on return -- (like the timer had expired instantly); it would be good to set this -- as late as possible (to give most current time) but also we want it -- to precede any possible timers that might start striking. -- linda:set( key, core.now_secs()) if not period or period==0.0 then timer_gateway:send( TGW_KEY, linda, key, nil, nil ) -- clear the timer return -- nothing more to do end a= period end local wakeup_at= type(a)=="table" and core.wakeup_conv(a) -- given point of time or (a and core.now_secs()+a or nil) -- queue to timer -- timer_gateway:send( TGW_KEY, linda, key, wakeup_at, period ) end ----- -- {[{linda, slot, when, period}[,...]]} = timers() -- -- PUBLIC LANES API timers = function() timer_gateway:send( TGW_QUERY, "get_timers") local _, r = timer_gateway:receive( TGW_REPLY) return r end end -- settings.with_timers -- avoid pulling the whole core module as upvalue when cancel_error is enough local cancel_error = assert( core.cancel_error) ---=== Lock & atomic generators ===--- -- These functions are just surface sugar, but make solutions easier to read. -- Not many applications should even need explicit locks or atomic counters. -- -- [true [, ...]= trues(uint) -- local function trues( n) if n > 0 then return true, trues( n - 1) end end -- -- lock_f = lanes.genlock( linda_h, key [,N_uint=1] ) -- -- = lock_f( +M ) -- acquire M -- ...locked... -- = lock_f( -M ) -- release M -- -- Returns an access function that allows 'N' simultaneous entries between -- acquire (+M) and release (-M). For binary locks, use M==1. -- -- PUBLIC LANES API local genlock = function( linda, key, N) -- clear existing data and set the limit N = N or 1 if linda:set( key) == cancel_error or linda:limit( key, N) == cancel_error then return cancel_error end -- use an optimized version for case N == 1 return (N == 1) and function( M, mode_) local timeout = (mode_ == "try") and 0 or nil if M > 0 then -- 'nil' timeout allows 'key' to be numeric return linda:send( timeout, key, true) -- suspends until been able to push them else local k = linda:receive( nil, key) -- propagate cancel_error if we got it, else return true or false return k and ((k ~= cancel_error) and true or k) or false end end or function( M, mode_) local timeout = (mode_ == "try") and 0 or nil if M > 0 then -- 'nil' timeout allows 'key' to be numeric return linda:send( timeout, key, trues(M)) -- suspends until been able to push them else local k = linda:receive( nil, linda.batched, key, -M) -- propagate cancel_error if we got it, else return true or false return k and ((k ~= cancel_error) and true or k) or false end end end -- -- atomic_f = lanes.genatomic( linda_h, key [,initial_num=0.0]) -- -- int|cancel_error = atomic_f( [diff_num = 1.0]) -- -- Returns an access function that allows atomic increment/decrement of the -- number in 'key'. -- -- PUBLIC LANES API local genatomic = function( linda, key, initial_val) -- clears existing data (also queue). the slot may contain the stored value, and an additional boolean value if linda:limit( key, 2) == cancel_error or linda:set( key, initial_val or 0.0) == cancel_error then return cancel_error end return function( diff) -- 'nil' allows 'key' to be numeric -- suspends until our 'true' is in if linda:send( nil, key, true) == cancel_error then return cancel_error end local val = linda:get( key) if val ~= cancel_error then val = val + (diff or 1.0) -- set() releases the lock by emptying queue if linda:set( key, val) == cancel_error then val = cancel_error end end return val end end -- activate full interface lanes.require = core.require lanes.gen = gen lanes.linda = core.linda lanes.cancel_error = core.cancel_error lanes.nameof = core.nameof lanes.set_singlethreaded = core.set_singlethreaded lanes.threads = core.threads or function() error "lane tracking is not available" end -- core.threads isn't registered if settings.track_lanes is false lanes.set_thread_priority = core.set_thread_priority lanes.timer = timer lanes.timer_lane = timer_lane lanes.timers = timers lanes.genlock = genlock lanes.now_secs = core.now_secs lanes.genatomic = genatomic lanes.configure = nil -- no need to call configure() ever again return lanes end -- lanes.configure -- no need to force calling configure() excepted the first time if core.settings then return lanes.configure() else return lanes end --the end return lanes
mit
gleachkr/luakit
build-utils/docgen/gen.lua
3
17745
local lfs = require "lfs" local lousy = { util = require "lib.lousy.util" } local markdown = require "lib.markdown" local index = {} local text_macros = { available = function (arg) return ({ ui = '<div class="alert warn">This module is only available from the UI process Lua state.</div>', web = '<div class="alert warn">This module is only available from web process Lua states.</div>', })[arg] or error("available macro: expected ui, web, or both as argument") end, alert = function (str) return '<div class="alert warn">' .. str .. '</div>' end, } local format_text = function (text) local ret = text:gsub("DOCMACRO%((%w+):?([^%)]-)%)", function (macro, args) if not text_macros[macro] then error("Bad macro '" .. macro .. "'") end return (text_macros[macro])(args) end) ret = ret:gsub('@ref{([^}]+)}', function (ref) local r, reftext = ref:match("^(.*)%|(.*)$") ref, reftext = r or ref, reftext or ref:gsub(".*/", "") assert(index[ref] ~= false, "ambiguous ref '" .. ref .. "', prefix with doc/") assert(index[ref], "invalid ref '" .. ref .. "'") local doc, item = index[ref].doc, index[ref].item local group, name = doc.module and "modules" or "classes", doc.name local fragment = item and ("#%s-%s"):format(item.type, item.name) or "" return ('<a href="../%s/%s.html%s">`%s`</a>'):format(group, name, fragment, reftext) end) -- Format with markdown ret = markdown(ret) ret = ret:gsub("<pre><code>(.-)</code></pre>", function (code) -- Add syntax highlighting if lxsh is installed local ok, lxsh = pcall(require, "lxsh") if ok then code = lxsh.highlighters.lua( lousy.util.unescape(code), -- Fix < and > being escaped inside code -_- fail { formatter = lxsh.formatters.html, external = true } ) else code = "<pre class='sourcecode lua'>" .. code .. "</pre>" end return code end) return ret end local shift_hdr = function (text, n) return ("\n"..text):gsub("\n#", "\n" .. string.rep("#", n+1)):sub(2) end local generate_typestr_html = function (typestr) if not typestr then return "<span class=any_type>any type</span>" end local alts = {} for sub in typestr:gmatch("[^%|]+") do table.insert(alts, "<span class=type>" .. sub .. "</span>") end return table.concat(alts, " or ") end local html_unwrap_first_p = function (html) return html:gsub("</?p>", "", 2) -- Remove first two open/closing p tags end local generate_deprecated_html = function (item) if not item.deprecated then return "" end return text_macros.alert("Deprecated: " .. html_unwrap_first_p(format_text(item.deprecated))) end local generate_function_param_html = function (param) local html_template = [==[ <li class=parameter> <div class=two-col> <div> <span class=parameter>{name}</span> <div>{typestr}</div> <div>{optional}</div> <div>{default}</div> </div> <div>{desc}</div> </div> </li> ]==] local html = string.gsub(html_template, "{(%w+)}", { name = param.name, typestr = "Type: " .. generate_typestr_html(param.typestr), desc = html_unwrap_first_p(format_text(shift_hdr(param.desc, 3))), optional = param.optional and "Optional" or "", default = param.default and "Default: " .. html_unwrap_first_p(format_text(param.default)) or "", }) return html end local generate_function_return_html = function (ret) local html_template = [==[ <li> <div class=two-col> <div>{typestr}</div><div>{desc}</div> </div> </li> ]==] local html = string.gsub(html_template, "{(%w+)}", { typestr = generate_typestr_html(ret.typestr), desc = html_unwrap_first_p(format_text(shift_hdr(ret.desc, 3))), }) return html end local generate_function_params_html = function (params) if #params == 0 then return "" end local param_html = {"<h4>Parameters</h4>"} table.insert(param_html, "<ul>") for _, param in ipairs(params) do table.insert(param_html, generate_function_param_html(param)) end table.insert(param_html, "</ul>") return table.concat(param_html, "\n") end local generate_function_returns_html = function (returns) if #returns == 0 then return "" end local return_html = {"<h4>Return Values</h4>"} table.insert(return_html, "<ul>") for _, ret in ipairs(returns) do table.insert(return_html, generate_function_return_html(ret)) end table.insert(return_html, "</ul>") return table.concat(return_html, "\n") end local generate_function_body_html = function (func) local html_template = [==[ <div> {deprecated} {desc} {params} {returns} </div> ]==] local html = string.gsub(html_template, "{([%w_]+)}", { deprecated = generate_deprecated_html(func), desc = format_text(shift_hdr(func.desc, 3)), params = generate_function_params_html(func.params), returns = generate_function_returns_html(func.returns), }) return html end local generate_function_html = function (func, prefix) if func.name == "__call" then prefix = prefix:gsub(".$", "") func.name = "" end local html_template = [==[ <div class=function id="{type}-{name}"> <h3> <a href="#{type}-{name}">{prefix}{name} ({param_names})</a> </h3> {body} </div> ]==] local param_names = {} for _, param in ipairs(func.params) do table.insert(param_names, (param.opt and "["..param.name.."]" or param.name)) end local html = string.gsub(html_template, "{([%w_]+)}", { prefix = prefix, type = func.type, name = func.name, param_names = table.concat(param_names, ", "), body = generate_function_body_html(func), }) return html end local generate_signal_html = function (func) local html_template = [==[ <div class=function id="signal-{name}"> <h3> <a href="#signal-{name}">"{name}"</a> </h3> {body} </div> ]==] local html = string.gsub(html_template, "{([%w_]+)}", { name = func.name, body = generate_function_body_html(func), }) return html end local generate_attribution_html = function (doc) if #doc.copyright == 0 then return "" end local html = { "<h2>Attribution</h2>" } table.insert(html, "<div class=attr-wrap>") table.insert(html, " <h4>Copyright</h4><ul class=copyright>") for _, copy in ipairs(doc.copyright) do copy = copy:gsub(" %<.-%>$", ""):gsub("(%d+)%-(%d+)", "%1&ndash;%2") table.insert(html, " <li>" .. copy) end table.insert(html, " </ul>") table.insert(html, "</div>") return table.concat(html, "\n") end local generate_property_html = function (prop, prefix) local html_template = [==[ <div class=property id="property-{name}"> <h3> <a href="#property-{name}">{prefix}{name}</a> </h3> {deprecated} <div class="two-col property-body"> <div> <div>{typestr}</div> <div>{default}</div> <div>{readwrite}</div> </div> <div>{desc}</div> </div> </div> ]==] assert(prop.readonly or prop.readwrite, "Property " .. prop.name .. " missing RO/RW annotation") local html = string.gsub(html_template, "{([%w_]+)}", { prefix = prefix, name = prop.name, deprecated = generate_deprecated_html(prop), typestr = "Type: " .. generate_typestr_html(prop.typestr), desc = html_unwrap_first_p(format_text(shift_hdr(prop.desc, 3))), default = prop.default and "Default: " .. html_unwrap_first_p(format_text(prop.default)) or "", readwrite = (prop.readonly and "Read-only") or (prop.readwrite and "Read-write") }) return html end local generate_list_html = function (heading, list, item_func, ...) if not list or #list == 0 then return "" end local html = "<h2>" .. heading .. "</h2>\n" for _, item in ipairs(list) do html = html .. "\n" .. item_func(item, ...) end return html end local generate_doc_html = function (doc) local html_template = [==[ <h1>{type} <code>{title}</code></h1> <!-- status indicator --> <span class=tagline>{tagline}</span> {desc} {functions} {attribution} ]==] -- Determine function name prefix local prefix = doc.prefix or doc.name local func_prefix, method_prefix = prefix .. ".", prefix .. ":" local fhtml = "" .. "<!-- modes and binds -->" .. generate_list_html("Functions", doc.functions, generate_function_html, func_prefix) .. generate_list_html("Methods", doc.methods, generate_function_html, method_prefix) .. generate_list_html("Properties", doc.properties, generate_property_html, func_prefix) .. generate_list_html("Signals", doc.signals, generate_signal_html) .. generate_list_html("Callback Types", doc.callbacks, generate_function_html, "") local html = string.gsub(html_template, "{(%w+)}", { type = doc.module and "Module" or "Class", title = doc.name, tagline = doc.tagline:gsub("%.$",""), desc = format_text(shift_hdr(doc.desc, 1)), functions = fhtml, attribution = generate_attribution_html(doc) }) return html end local generate_sidebar_html = function (docs, current_doc) local html = "" for _, name in ipairs{"pages", "modules", "classes"} do local section = assert(docs[name], "Missing " .. name .. " section") html = html .. ("<h3>%s</h3>\n"):format(name:gsub("^%l", string.upper)) html = html .. "<ul class=" .. name .. ">\n" for _, doc in ipairs(section) do if doc == current_doc then html = html .. (' <li><span>%s</span></li>\n'):format(doc.name) else html = html .. (' <li><a href="../%s/%s.html">%s</a></li>\n'):format(name, doc.filename or doc.name, doc.name) end end html = html .. "</ul>\n" end return html end local generate_pagination_html = function (pagination) return ("<div style='display:none'>{prv}{nxt}</div>"):gsub("{(%w+)}", { prv = pagination.prv and ("<a rel=prev href='../" .. pagination.prv .. "'></a>") or "", nxt = pagination.nxt and ("<a rel=next href='../" .. pagination.nxt .. "'></a>") or "", }) end local generate_module_html = function (doc, style, docs, pagination) local html_template = [==[ <!doctype html> <html> <head> <meta charset="utf-8"> <title>{title} - Luakit</title> <style>{style}</style> </head> <body> <div id=hdr> <h1>Luakit Documentation &nbsp;&nbsp;/&nbsp;&nbsp; {section} &nbsp;&nbsp;/ &nbsp;&nbsp;{title}</h1> </div> <div id=wrap> <div id=sidebar> <h2>Table of Contents</h2> {sidebar} </div> <div id=content> {body} </div> {pagination} </div> </body> ]==] local html = string.gsub(html_template, "{(%w+)}", { title = doc.name, style = style, section = doc.module and "Modules" or doc.class and "Classes" or "Pages", body = generate_doc_html(doc), sidebar = generate_sidebar_html(docs, doc), pagination = generate_pagination_html(pagination), }) return html end local generate_page_html = function (doc, style, docs, pagination) local html_template = [==[ <!doctype html> <html> <head> <meta charset="utf-8"> <title>{title} - Luakit</title> <style>{style}</style> </head> <body> <div id=hdr> <h1>Luakit Documentation &nbsp;&nbsp;/&nbsp;&nbsp; Pages &nbsp;&nbsp;/ &nbsp;&nbsp;{title}</h1> </div> <div id=wrap> <div id=sidebar> <h2>Table of Contents</h2> {sidebar} </div> <div id=content> {body} </div> {pagination} </div> </body> ]==] local html = string.gsub(html_template, "{(%w+)}", { title = doc.name, style = style, body = format_text(assert(doc.text, "No page text")), sidebar = generate_sidebar_html(docs, doc), pagination = generate_pagination_html(pagination), }) return html end local generate_index_html = function (style, docs) local html_template = [==[ <!doctype html> <html> <head> <meta charset="utf-8"> <title>Luakit Documentation</title> <style> {style} #wrap { padding-top: 0; } ul { column-count: 3; list-style-position: inside; padding-left: 1.5rem; } @media (max-width: 650px) { ul { column-count: 2; } } @media (max-width: 400px) { ul { column-count: 1; } } </style> </head> <body> <div id=hdr> <h1>Luakit Documentation &nbsp;&nbsp;/&nbsp;&nbsp; Index</h1> </div> <div id=wrap> <div id=content> <h2>Pages</h2> {pages} <h2>Modules</h2> {modules} <h2>Classes</h2> {classes} </div> </div> </body> ]==] local lists = {} for _, name in ipairs{"pages", "modules", "classes"} do local html = "" local section = assert(docs[name], "Missing " .. name .. " section") html = html .. "<ul>\n" for _, doc in ipairs(section) do html = html .. (' <li><a href="%s/%s.html">%s</a></li>\n'):format(name, doc.filename or doc.name, doc.name) end for _=1,(3-#section%3)%3 do html = html .. ' <li class=dummy></li>\n' end lists[name] = html .. "</ul>\n" end local html = string.gsub(html_template, "{(%w+)}", { style = style, pages = lists.pages, modules = lists.modules, classes = lists.classes, }) return html end local generate_documentation = function (docs, out_dir) -- Utility functions local mkdir = function (path) if lfs.attributes(path, "mode") == "directory" then return end assert(lfs.mkdir(path)) end local write_file = function (path, html) local f = assert(io.open(path, "w")) f:write(html) f:close() end -- Load doc stylesheet local f = assert(io.open(docs.stylesheet, "r"), "no stylesheet found") local style = f:read("*a") f:close() -- Create output directory assert(out_dir, "no output directory specified") out_dir = out_dir:match("/$") and out_dir or out_dir .. "/" mkdir(out_dir) -- Build symbol index do local add_index_obj = function (doc, item) local name = item and (item.type == "signal" and '"'..item.name..'"' or item.name) local short_name = name or doc.name local long_name = doc.name .. "/" .. (name or "") -- Always allow using the long name assert(not index[long_name], "Name conflict for " .. long_name) index[long_name] = { doc = doc, item = item } -- Allow using the short name, but blacklist it on collision if index[short_name] == nil then index[short_name] = { doc = doc, item = item } else index[short_name] = false end end for _, doc in ipairs(lousy.util.table.join(docs.modules, docs.classes)) do add_index_obj(doc) for _, t in ipairs {"functions", "methods", "properties", "signals", "callbacks"} do for _, item in ipairs(doc[t] or {}) do add_index_obj(doc, item) end end end end local pages = {} mkdir(out_dir .. "pages") for _, page in ipairs(docs.pages) do pages[#pages+1] = { doc = page, gen = generate_page_html, path = "pages/" .. page.filename .. ".html", } end for _, section_name in ipairs{"modules", "classes"} do mkdir(out_dir .. section_name) local section_docs = docs[section_name] for _, doc in ipairs(section_docs) do pages[#pages+1] = { doc = doc, gen = generate_module_html, path = section_name .. "/" .. doc.name .. ".html", } end end for i, page in ipairs(pages) do print("Generating '" .. page.path .. "'...") local pagination = { nxt = (pages[i+1] or {}).path, prv = (pages[i-1] or {}).path, } write_file(out_dir .. page.path, page.gen(page.doc, style, docs, pagination)) end -- Generate index local path = out_dir .. "index.html" print("Generating '" .. path .. "'...") write_file(path, generate_index_html(style, docs)) end return { generate_documentation = generate_documentation, } -- vim: et:sw=4:ts=8:sts=4:tw=80
gpl-3.0
madpilot78/ntopng
scripts/lua/modules/host_pools_migration.lua
1
23446
-- -- (C) 2017-21 - ntop.org -- dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?/init.lua;" .. package.path local ntop_info = ntop.getInfo() local os_utils = require "os_utils" local host_pools_migration = {} host_pools_migration.DEFAULT_POOL_ID = "0" host_pools_migration.DEFAULT_ROUTING_POLICY_ID = "1" host_pools_migration.FIRST_AVAILABLE_POOL_ID = "1" host_pools_migration.DEFAULT_POOL_NAME = "Not Assigned" host_pools_migration.MAX_NUM_POOLS = 128 -- Note: keep in sync with C -- -- BEGIN NEDGE specific code -- function host_pools_migration.usernameToPoolId(username) local res = ntop.getPref("ntopng.user."..string.lower(username)..".host_pool_id") return ternary(not isEmptyString(res), res, nil) end function host_pools_migration.poolIdToUsername(pool_id) local ifid = getInterfaceId(ifname) return host_pools_migration.getPoolName(ifid, pool_id) end function host_pools_migration.getUserUrl(pool_id) return ntop.getHttpPrefix() .."/lua/pro/nedge/admin/nf_edit_user.lua?username=" .. ternary(tostring(pool_id) == host_pools_migration.DEFAULT_POOL_ID, "", host_pools_migration.poolIdToUsername(pool_id)) end -- -- END NEDGE specific code -- host_pools_migration.LIMITED_NUMBER_POOL_MEMBERS = ntop_info["constants.max_num_pool_members"] -- this takes into account the special pools host_pools_migration.LIMITED_NUMBER_TOTAL_HOST_POOLS = ntop_info["constants.max_num_host_pools"] -- this does not take into account the special pools host_pools_migration.LIMITED_NUMBER_USER_HOST_POOLS = host_pools_migration.LIMITED_NUMBER_TOTAL_HOST_POOLS - 1 local function get_pool_members_key(ifid, pool_id) return "ntopng.prefs." .. ifid .. ".host_pools.members." .. pool_id end local function get_pool_ids_key(ifid) return "ntopng.prefs." .. ifid .. ".host_pools.pool_ids" end local function get_pool_details_key(ifid, pool_id) return "ntopng.prefs." .. ifid .. ".host_pools.details." .. pool_id end local function get_pools_serialized_key(ifid) return "ntopng.serialized_host_pools.ifid_" .. ifid end -- It is safe to call this multiple times local function initInterfacePools(ifid) host_pools_migration.createPool(ifid, host_pools_migration.DEFAULT_POOL_ID, host_pools_migration.DEFAULT_POOL_NAME) end function host_pools_migration.getPoolDetail(ifid, pool_id, detail) local details_key = get_pool_details_key(ifid, pool_id) return ntop.getHashCache(details_key, detail) end function host_pools_migration.setPoolDetail(ifid, pool_id, detail, value) local details_key = get_pool_details_key(ifid, pool_id) return ntop.setHashCache(details_key, detail, tostring(value)) end local function traceHostPoolEvent(severity, event) if ntop.getPref("ntopng.prefs.enable_host_pools_log") ~= "1" then return end local f_name = debug.getinfo(2, "n").name if f_name ~= nil then f_name = string.format("[%s] ", f_name) end traceError(severity, TRACE_CONSOLE, string.format("%s%s", f_name or '', event)) end local function addMemberToRedisPool(ifid, pool_id, member_key) if pool_id == host_pools_migration.DEFAULT_POOL_ID then -- avoid adding default pool members explicitly traceHostPoolEvent(TRACE_NORMAL, string.format("Setting DEFAULT_POOL_ID (aka 'Not Assigned'). [pool_id: %d][member: %s]", host_pools_migration.DEFAULT_POOL_ID, member_key)) return true end local members_key = get_pool_members_key(ifid, pool_id) local n = table.len(ntop.getMembersCache(members_key) or {}) if n >= host_pools_migration.LIMITED_NUMBER_POOL_MEMBERS then traceHostPoolEvent(TRACE_ERROR, string.format("Unable to set host pool, maximum number of pool members hit. [max num pool members: %d][member: %s] [members_key: %s]", host_pools_migration.LIMITED_NUMBER_POOL_MEMBERS, member_key, members_key)) return false end ntop.setMembersCache(members_key, member_key) traceHostPoolEvent(TRACE_NORMAL, string.format("Member added to pool. [member: %s] [members_key: %s]", member_key, members_key)) return true end -------------------------------------------------------------------------------- function host_pools_migration.getPoolMembersRaw(ifid, pool_id) local members_key = get_pool_members_key(ifid, pool_id) return ntop.getMembersCache(members_key) or {} end -- Export host pools function host_pools_migration.export(ifid) local pools = {} for _,pool in pairs(host_pools_migration.getPoolsList(ifid)) do pool.members = host_pools_migration.getPoolMembersRaw(ifid, pool.id) pools[pool.id] = pool end return pools end -- Import host pools, in case of conflict (same name) the pool is replaced function host_pools_migration.import(pools, ifid) local existing_pools = host_pools_migration.getPoolsList(ifid) local retval = true -- Import pools for _,pool in pairs(pools) do for k,existing_pool in pairs(existing_pools) do if pool.name == existing_pool.name then -- Same name, delete the old pool and reuse the id pool.id = existing_pool.id host_pools_migration.emptyPool(ifid, existing_pool.id) host_pools_migration.deletePool(ifid, existing_pool.id) end end -- Add pool host_pools_migration.createPool(ifid, pool.id, pool.name, pool.children_safe, pool.enforce_quotas_per_pool_member, pool. enforce_shapers_per_pool_member, true) -- Add members for _,member in ipairs(pool.members) do local success = addMemberToRedisPool(ifid, pool.id, member) if not success then retval = false end end end return retval end -------------------------------------------------------------------------------- function host_pools_migration.createPool(ifid, pool_id, pool_name, children_safe, enforce_quotas_per_pool_member, enforce_shapers_per_pool_member, ignore_exist) local details_key = get_pool_details_key(ifid, pool_id) local ids_key = get_pool_ids_key(ifid) local members = ntop.getMembersCache(ids_key) or {} local n = table.len(members) if n >= host_pools_migration.LIMITED_NUMBER_TOTAL_HOST_POOLS then return false end if not ignore_exist then for _, m in pairs(members) do if m == pool_id then return true end end end ntop.setMembersCache(ids_key, pool_id) ntop.setHashCache(details_key, "name", pool_name) ntop.setHashCache(details_key, "children_safe", tostring(children_safe or false)) ntop.setHashCache(details_key, "enforce_quotas_per_pool_member", tostring(enforce_quotas_per_pool_member or false)) ntop.setHashCache(details_key, "enforce_shapers_per_pool_member", tostring(enforce_shapers_per_pool_member or false)) ntop.setHashCache(details_key, "forge_global_dns", "true") return true end function host_pools_migration.deletePool(ifid, pool_id) local ts_utils = require "ts_utils" local rrd_base = host_pools_migration.getRRDBase(ifid, pool_id) local ids_key = get_pool_ids_key(ifid) local details_key = get_pool_details_key(ifid, pool_id) local members_key = get_pool_members_key(ifid, pool_id) local serialized_key = get_pools_serialized_key(ifid) host_pools_migration.emptyPool(ifid, pool_id) ntop.delMembersCache(ids_key, pool_id) ntop.delCache(details_key) ntop.delCache(members_key) ntop.delHashCache(serialized_key, pool_id) ts_utils.delete("host_pool", {ifid = ifid, pool = pool_id}) end function getMembershipInfo(member_and_vlan) -- Check if the member is already in another pool local hostinfo = hostkey2hostinfo(member_and_vlan) local addr, mask = splitNetworkPrefix(hostinfo["host"]) local vlan = hostinfo["vlan"] local is_mac = isMacAddress(addr) if not is_mac then addr = ntop.networkPrefix(addr, mask) end local find_info = interface.findMemberPool(addr, vlan, is_mac) -- This is the normalized key, which should always be used to refer to the member local key if not is_mac then key = host2member(addr, vlan, mask) else key = addr end local info = {key=key} local exists = false if find_info ~= nil then -- The host has been found if is_mac or ((not is_mac) and (find_info.matched_prefix == addr) and (find_info.matched_bitmask == mask)) then info["existing_member_pool"] = find_info.pool_id exists = true end end return exists, info end -- -- Note: -- -- When strict_host_mode is not set, hosts which have a MAC address will have the -- MAC address changed instead of the IP address when their MAC address is already bound to -- a pool. -- function host_pools_migration.changeMemberPool(ifid, member_and_vlan, new_pool, info --[[optional]], strict_host_mode --[[optional]]) traceHostPoolEvent(TRACE_NORMAL, string.format("Pool change requested. [member: %s][new_pool: %s][strict_host_mode: %s]", member_and_vlan, new_pool, tostring(strict_host_mode))) if not strict_host_mode then local hostkey, is_network = host_pools_migration.getMemberKey(member_and_vlan) if (not is_network) and (not isMacAddress(member_and_vlan)) then -- this is a single host, try to get the MAC address if info == nil then local hostinfo = hostkey2hostinfo(hostkey) info = interface.getHostInfo(hostinfo["host"], hostinfo["vlan"]) end if not isEmptyString(info["mac"]) and (info["mac"] ~= "00:00:00:00:00:00") then local mac_has_pool, mac_pool_info = getMembershipInfo(info["mac"]) -- Two cases: -- 1. if we are moving to a well defined pool, we must set the mac pool -- 2. if we are moving to the default pool, we must set the mac pool only -- if the mac already has a pool, otherwise we set the ip pool if (new_pool ~= host_pools_migration.DEFAULT_POOL_ID) or mac_has_pool then -- we must change the MAC address in order to change the host pool member_and_vlan = info["mac"] end end end end local member_exists, info = getMembershipInfo(member_and_vlan) local prev_pool if member_exists then -- use the normalized key member_and_vlan = info.key prev_pool = info.existing_member_pool else prev_pool = host_pools_migration.DEFAULT_POOL_ID end if prev_pool == new_pool then traceHostPoolEvent(TRACE_ERROR, string.format("Pool did't change. Exiting. [member: %s][prev_pool: %s][new_pool: %s]", member_and_vlan, prev_pool, new_pool)) return false end traceHostPoolEvent(TRACE_NORMAL, string.format("Pool change prepared. [member: %s][info.key: %s][prev_pool: %s][new_pool: %s]", member_and_vlan, tostring(info.key), prev_pool, new_pool)) host_pools_migration.deletePoolMember(ifid, prev_pool, info.key) addMemberToRedisPool(ifid, new_pool, info.key) return true end function host_pools_migration.addPoolMember(ifid, pool_id, member_and_vlan) traceHostPoolEvent(TRACE_NORMAL, string.format("Pool member addition requested. [member: %s][pool_id: %s]", member_and_vlan, pool_id)) local member_exists, info = getMembershipInfo(member_and_vlan) if member_exists then traceHostPoolEvent(TRACE_NORMAL, string.format("Member already in pool. [pool_id: %d] [member: %s]", pool_id, member_and_vlan)) return false, info else local rv = addMemberToRedisPool(ifid, pool_id, info.key) return rv, info end end function host_pools_migration.deletePoolMember(ifid, pool_id, member_and_vlan) traceHostPoolEvent(TRACE_NORMAL, string.format("Pool member deletion requested. [member: %s][pool_id: %s]", member_and_vlan, pool_id)) local members_key = get_pool_members_key(ifid, pool_id) -- Possible delete non-volatile member ntop.delMembersCache(members_key, member_and_vlan) end function host_pools_migration.getPoolsList(ifid, without_info) local ids_key = get_pool_ids_key(ifid) local ids = ntop.getMembersCache(ids_key) if not ids then ids = {} end for i, id in pairs(ids) do ids[i] = tonumber(id) end local pools = {} initInterfacePools(ifid) for _, pool_id in pairsByValues(ids, asc) do pool_id = tostring(pool_id) local pool if without_info then pool = {id=pool_id} else pool = { id = pool_id, name = host_pools_migration.getPoolName(ifid, pool_id), children_safe = host_pools_migration.getChildrenSafe(ifid, pool_id), enforce_quotas_per_pool_member = host_pools_migration.getEnforceQuotasPerPoolMember(ifid, pool_id), enforce_shapers_per_pool_member = host_pools_migration.getEnforceShapersPerPoolMember(ifid, pool_id), } end pools[#pools + 1] = pool end return pools end function host_pools_migration.getPoolMembers(ifid, pool_id) local members_key = get_pool_members_key(ifid, pool_id) local members = {} local all_members = ntop.getMembersCache(members_key) or {} for _,v in pairsByValues(all_members, asc) do local hostinfo = hostkey2hostinfo(v) members[#members + 1] = {address=hostinfo["host"], vlan=hostinfo["vlan"], key=v} end return members end function host_pools_migration.getMemberKey(member) -- handle vlan local is_network local host_key local address = hostkey2hostinfo(member)["host"] if isMacAddress(address) then host_key = address is_network = false else local network, prefix = splitNetworkPrefix(address) if(((isIPv4(network)) and (prefix ~= 32)) or ((isIPv6(network)) and (prefix ~= 128))) then -- this is a network host_key = address is_network = true else -- this is an host host_key = network is_network = false end end return host_key, is_network end function host_pools_migration.getPoolName(ifid, pool_id) return host_pools_migration.getPoolDetail(ifid, pool_id, "name") end function host_pools_migration.getChildrenSafe(ifid, pool_id) return toboolean(host_pools_migration.getPoolDetail(ifid, pool_id, "children_safe")) end function host_pools_migration.setChildrenSafe(ifid, pool_id, value) host_pools_migration.setPoolDetail(ifid, pool_id, "children_safe", ternary(value, "true", "false")) end function host_pools_migration.getForgeGlobalDNS(ifid, pool_id) return toboolean(host_pools_migration.getPoolDetail(ifid, pool_id, "forge_global_dns")) end function host_pools_migration.setForgeGlobalDNS(ifid, pool_id, value) host_pools_migration.setPoolDetail(ifid, pool_id, "forge_global_dns", ternary(value, "true", "false")) end function host_pools_migration.getRoutingPolicyId(ifid, pool_id) local routing_policy_id = host_pools_migration.getPoolDetail(ifid, pool_id, "routing_policy_id") if isEmptyString(routing_policy_id) then routing_policy_id = host_pools_migration.DEFAULT_ROUTING_POLICY_ID end return routing_policy_id end function host_pools_migration.setRoutingPolicyId(ifid, pool_id, routing_policy_id) return host_pools_migration.setPoolDetail(ifid, pool_id, "routing_policy_id", routing_policy_id) end function host_pools_migration.getEnforceQuotasPerPoolMember(ifid, pool_id) return toboolean(host_pools_migration.getPoolDetail(ifid, pool_id, "enforce_quotas_per_pool_member")) end function host_pools_migration.getEnforceShapersPerPoolMember(ifid, pool_id) return toboolean(host_pools_migration.getPoolDetail(ifid, pool_id, "enforce_shapers_per_pool_member")) end function host_pools_migration.emptyPool(ifid, pool_id) local members_key = get_pool_members_key(ifid, pool_id) -- Remove non-volatile members ntop.delCache(members_key) end function host_pools_migration.emptyPools() for _, ifname in pairs(interface.getIfNames()) do local ifid = getInterfaceId(ifname) local ifstats = interface.getStats() local pools_list = host_pools_migration.getPoolsList(ifid) for _, pool in pairs(pools_list) do host_pools_migration.emptyPool(ifid, pool["id"]) end end end function host_pools_migration.initPools() for _, ifname in pairs(interface.getIfNames()) do local ifid = getInterfaceId(ifname) local ifstats = interface.getStats() -- Note: possible shapers are initialized in shaper_utils::initShapers initInterfacePools(ifid) end end function host_pools_migration.getMacPool(mac_address) local exists, info = getMembershipInfo(mac_address) if exists then return tostring(info.existing_member_pool) else return host_pools_migration.DEFAULT_POOL_ID end end function host_pools_migration.getUndeletablePools(ifid) local pools = {} for user_key,_ in pairs(ntop.getKeysCache("ntopng.user.*.host_pool_id") or {}) do local pool_id = ntop.getCache(user_key) if tonumber(pool_id) ~= nil then local username = string.split(user_key, "%.")[3] local allowed_ifname = ntop.getCache("ntopng.user."..username..".allowed_ifname") -- verify if the Captive Portal User is actually active for the interface if getInterfaceName(ifid) == allowed_ifname then pools[pool_id] = true end end end return pools end function host_pools_migration.getRRDBase(ifid, pool_id) local dirs = ntop.getDirs() return os_utils.fixPath(dirs.workingdir .. "/" .. ifid .. "/host_pools/" .. pool_id) end function host_pools_migration.updateRRDs(ifid, dump_ndpi, verbose) local ts_utils = require "ts_utils" require "ts_5min" -- NOTE: requires graph_utils for pool_id, pool_stats in pairs(interface.getHostPoolsStats() or {}) do ts_utils.append("host_pool:traffic", {ifid=ifid, pool=pool_id, bytes_sent=pool_stats["bytes.sent"], bytes_rcvd=pool_stats["bytes.rcvd"]}, when) if pool_id ~= tonumber(host_pools_migration.DEFAULT_POOL_ID) then local flows_dropped = pool_stats["flows.dropped"] or 0 ts_utils.append("host_pool:blocked_flows", {ifid=ifid, pool=pool_id, num_flows=flows_dropped}, when) end -- nDPI stats if dump_ndpi then for proto,v in pairs(pool_stats["ndpi"] or {}) do ts_utils.append("host_pool:ndpi", {ifid=ifid, pool=pool_id, protocol=proto, bytes_sent=v["bytes.sent"], bytes_rcvd=v["bytes.rcvd"]}, when) end end end -- Also write info on the number of members per pool, both in terms of hosts and l2 devices local pools = interface.getHostPoolsInfo() or {} for pool, info in pairs(pools.num_members_per_pool or {}) do ts_utils.append("host_pool:hosts", {ifid = ifid, pool = pool, num_hosts = info["num_hosts"]}, when) ts_utils.append("host_pool:devices", {ifid = ifid, pool = pool, num_devices = info["num_l2_devices"]}, when) end end function host_pools_migration.hostpool2record(ifid, pool_id, pool) local record = {} record["key"] = tostring(pool_id) local pool_name = host_pools_migration.getPoolName(ifid, pool_id) local pool_link = "<A HREF='"..ntop.getHttpPrefix()..'/lua/hosts_stats.lua?pool='..pool_id.."' title='"..pool_name.."'>"..pool_name..'</A>' record["column_id"] = pool_link record["column_hosts"] = pool["num_hosts"].."" record["column_since"] = secondsToTime(os.time() - pool["seen.first"] + 1) record["column_num_dropped_flows"] = (pool["flows.dropped"] or 0).."" local sent2rcvd = round((pool["bytes.sent"] * 100) / (pool["bytes.sent"] + pool["bytes.rcvd"]), 0) record["column_breakdown"] = "<div class='progress'><div class='progress-bar bg-warning' style='width: " .. sent2rcvd .."%;'>Sent</div><div class='progress-bar bg-success' style='width: " .. (100-sent2rcvd) .. "%;'>Rcvd</div></div>" if(throughput_type == "pps") then record["column_thpt"] = pktsToSize(pool["throughput_pps"]) else record["column_thpt"] = bitsToSize(8*pool["throughput_bps"]) end record["column_traffic"] = bytesToSize(pool["bytes.sent"] + pool["bytes.rcvd"]) record["column_chart"] = "" if areHostPoolsTimeseriesEnabled(ifid) then record["column_chart"] = '<A HREF="'..ntop.getHttpPrefix()..'/lua/pool_details.lua?pool='..pool_id..'&page=historical"><i class=\'fas fa-chart-area fa-lg\'></i></A>' end return record end function host_pools_migration.printQuotas(pool_id, host, page_params) local pools_stats = interface.getHostPoolsStats() local pool_stats = pools_stats and pools_stats[tonumber(pool_id)] local ndpi_stats = pool_stats.ndpi local category_stats = pool_stats.ndpi_categories local quota_and_protos = shaper_utils.getPoolProtoShapers(ifId, pool_id) local cross_traffic_quota, cross_time_quota = shaper_utils.getCrossApplicationQuotas(ifId, pool_id) -- Empty check local empty = (cross_traffic_quota == shaper_utils.NO_QUOTA) and (cross_time_quota == shaper_utils.NO_QUOTA) if empty then for _, proto in pairs(quota_and_protos) do if ((tonumber(proto.traffic_quota) > 0) or (tonumber(proto.time_quota) > 0)) then -- at least a quota is set empty = false break end end end if empty then local url = "/lua/pro/nedge/admin/nf_edit_user.lua?page=protocols&username=" .. host_pools_migration.poolIdToUsername(pool_id) print("<div class=\"alert alert alert-danger\"><i class='fas fa-exclamation-triangle fa-lg fa-ntopng-warning'></i> "..i18n("shaping.no_quota_data").. ". " .. i18n("host_pools.create_new_quotas_here", {url=ntop.getHttpPrefix()..url}) .. "</div>") else print[[ <table class="table table-bordered table-striped"> <thead> <tr> <th>]] print(i18n("application")) print[[</th> <th class="text-center">]] print(i18n("shaping.daily_traffic")) print[[</th> <th class="text-center">]] print(i18n("shaping.daily_time")) print[[</th> </tr> </thead> <tbody id="pool_quotas_ndpi_tbody"> </tbody> </table> <script> function update_ndpi_table() { $.ajax({ type: 'GET', url: ']] print(getPageUrl(ntop.getHttpPrefix().."/lua/pro/pool_details_ndpi.lua").."', data: ") print(tableToJsObject(page_params)) print[[, success: function(content) { if(content) $('#pool_quotas_ndpi_tbody').html(content); else $('#pool_quotas_ndpi_tbody').html('<tr><td colspan="3"><i>]] print(i18n("shaping.no_quota_traffic")) print[[</i></td></tr>'); } }); } setInterval(update_ndpi_table, 5000); update_ndpi_table(); </script>]] end end function host_pools_migration.getFirstAvailablePoolId(ifid) local ids_key = get_pool_ids_key(ifid) local ids = ntop.getMembersCache(ids_key) or {} for i, id in pairs(ids) do ids[i] = tonumber(id) end local host_pool_id = tonumber(host_pools_migration.FIRST_AVAILABLE_POOL_ID) for _, pool_id in pairsByValues(ids, asc) do if pool_id > host_pool_id then break end host_pool_id = math.max(pool_id + 1, host_pool_id) end return tostring(host_pool_id) end function host_pools_migration.resetPoolsQuotas(ifid, pool_filter) local serialized_key = get_pools_serialized_key(ifid) local keys_to_del if pool_filter ~= nil then keys_to_del = {[pool_filter]=1, } else keys_to_del = ntop.getHashKeysCache(serialized_key) or {} end -- Delete the redis serialization for key in pairs(keys_to_del) do ntop.delHashCache(serialized_key, tostring(key)) end -- Delete the in-memory stats interface.resetPoolsQuotas(pool_filter) end host_pools_migration.traceHostPoolEvent = traceHostPoolEvent return host_pools_migration
gpl-3.0
fmassa/nn
L1Penalty.lua
42
1129
local L1Penalty, parent = torch.class('nn.L1Penalty','nn.Module') --This module acts as an L1 latent state regularizer, adding the --[gradOutput] to the gradient of the L1 loss. The [input] is copied to --the [output]. function L1Penalty:__init(l1weight, sizeAverage, provideOutput) parent.__init(self) self.l1weight = l1weight self.sizeAverage = sizeAverage or false if provideOutput == nil then self.provideOutput = true else self.provideOutput = provideOutput end end function L1Penalty:updateOutput(input) local m = self.l1weight if self.sizeAverage == true then m = m/input:nElement() end local loss = m*input:norm(1) self.loss = loss self.output = input return self.output end function L1Penalty:updateGradInput(input, gradOutput) local m = self.l1weight if self.sizeAverage == true then m = m/input:nElement() end self.gradInput:resizeAs(input):copy(input):sign():mul(m) if self.provideOutput == true then self.gradInput:add(gradOutput) end return self.gradInput end
bsd-3-clause
pakoito/ToME---t-engine4
game/engines/default/modules/boot/data/rooms/rocky_snowy_trees.lua
6
1692
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Heightmap = require "engine.Heightmap" return function(gen, id) local w = rng.range(5, 12) local h = rng.range(5, 12) return { name="rocky_snowy_trees"..w.."x"..h, w=w, h=h, generator = function(self, x, y, is_lit) -- make the fractal heightmap local hm = Heightmap.new(self.w, self.h, 2, {middle=Heightmap.min, up_left=Heightmap.max, down_left=Heightmap.max, up_right=Heightmap.max, down_right=Heightmap.max}) hm:generate() for i = 1, self.w do for j = 1, self.h do if hm.hmap[i][j] >= Heightmap.max * 5.4 / 6 then gen.map(i-1+x, j-1+y, Map.TERRAIN, gen:resolve('#')) elseif hm.hmap[i][j] >= Heightmap.max * 4.3 / 6 then gen.map(i-1+x, j-1+y, Map.TERRAIN, gen:resolve('T')) else gen.map.room_map[i-1+x][j-1+y].room = id gen.map(i-1+x, j-1+y, Map.TERRAIN, gen:resolve('.')) end if is_lit then gen.map.lites(i-1+x, j-1+y, true) end end end end} end
gpl-3.0
fmassa/nn
MulConstant.lua
32
1071
local MulConstant, parent = torch.class('nn.MulConstant', 'nn.Module') function MulConstant:__init(constant_scalar,ip) parent.__init(self) assert(type(constant_scalar) == 'number', 'input is not scalar!') self.constant_scalar = constant_scalar -- default for inplace is false self.inplace = ip or false if (ip and type(ip) ~= 'boolean') then error('in-place flag must be boolean') end end function MulConstant:updateOutput(input) if self.inplace then input:mul(self.constant_scalar) self.output = input else self.output:resizeAs(input) self.output:copy(input) self.output:mul(self.constant_scalar) end return self.output end function MulConstant:updateGradInput(input, gradOutput) if self.inplace then gradOutput:mul(self.constant_scalar) self.gradInput = gradOutput -- restore previous input value input:div(self.constant_scalar) else self.gradInput:resizeAs(gradOutput) self.gradInput:copy(gradOutput) self.gradInput:mul(self.constant_scalar) end return self.gradInput end
bsd-3-clause
RyMarq/Zero-K
units/gunshipbomb.lua
1
3169
return { gunshipbomb = { unitname = [[gunshipbomb]], name = [[Blastwing]], description = [[Flying Bomb (Burrows)]], acceleration = 0.25, brakeRate = 0.2, buildCostMetal = 45, builder = false, buildPic = [[gunshipbomb.png]], canFly = true, canGuard = true, canMove = true, canPatrol = true, canSubmerge = false, category = [[GUNSHIP]], collide = false, collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[20 20 20]], collisionVolumeType = [[ellipsoid]], selectionVolumeOffsets = [[0 0 0]], selectionVolumeScales = [[32 32 32]], selectionVolumeType = [[ellipsoid]], corpse = [[DEAD]], cruiseAlt = 30, customParams = { landflystate = [[1]], idle_cloak = 1, }, explodeAs = [[gunshipbomb_EXPLOSION]], --fireState = 0, floater = true, footprintX = 2, footprintZ = 2, hoverAttack = true, iconType = [[gunshipspecial]], idleAutoHeal = 5, idleTime = 1800, kamikaze = true, kamikazeDistance = 60, kamikazeUseLOS = true, maneuverleashlength = [[1240]], maxDamage = 100, maxSlope = 36, maxVelocity = 8.2, minCloakDistance = 75, noAutoFire = false, noChaseCategory = [[TERRAFORM SATELLITE SUB]], objectName = [[f-1.s3o]], script = [[gunshipbomb.lua]], selfDestructAs = [[gunshipbomb_EXPLOSION]], selfDestructCountdown = 0, sightDistance = 450, turnRate = 1144, upright = false, workerTime = 0, featureDefs = { DEAD = { blocking = false, featureDead = [[HEAP]], footprintX = 3, footprintZ = 3, object = [[wreck2x2b.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2c.s3o]], }, }, weaponDefs = { gunshipbomb_EXPLOSION = { name = "Blastwing Explosion", areaOfEffect = 256, craterBoost = 1, craterMult = 3.5, customParams = { setunitsonfire = "1", burntime = 30, area_damage = 1, area_damage_radius = 128, area_damage_dps = 18, area_damage_duration = 20, --lups_heat_fx = [[firewalker]], }, damage = { default = 80, planes = 80, subs = 4, }, edgeeffectiveness = 0.7, explosionGenerator = [[custom:napalm_gunshipbomb]], explosionSpeed = 10000, firestarter = 180, impulseBoost = 0, impulseFactor = 0.4, soundHit = "explosion/ex_med17", }, } } }
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Northern_San_dOria/npcs/Ailbeche.lua
1
6991
----------------------------------- -- Area: Northern San d'Oria -- NPC: Ailbeche -- Starts and Finishes Quest: Father and Son, Sharpening the Sword, A Boy's Dream (start) -- @zone 231 -- @pos 4 -1 24 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if(player:getQuestStatus(SANDORIA, FATHER_AND_SON) == QUEST_COMPLETED and player:getVar("returnedAilbecheRod") ~= 1) then if(trade:hasItemQty(17391,1) == true and trade:getItemCount() == 1) then player:startEvent(0x003d); -- Finish Quest "Father and Son" (part2) (trading fishing rod) end end if(player:getVar("aBoysDreamCS") >= 3) then if(trade:hasItemQty(17001,1) == true and trade:getItemCount() == 1 and player:hasItem(4562) == false) then player:startEvent(0x000f); -- During Quest "A Boy's Dream" (trading bug) madame ? elseif(trade:hasItemQty(4562,1) == true and trade:getItemCount() == 1) then player:startEvent(0x002f); -- During Quest "A Boy's Dream" (trading odontotyrannus) end end if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(MagicmartFlyer,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) fatherAndSon = player:getQuestStatus(SANDORIA, FATHER_AND_SON); sharpeningTheSword = player:getQuestStatus(SANDORIA, SHARPENING_THE_SWORD); aBoysDream = player:getQuestStatus(SANDORIA, A_BOY_S_DREAM); -- Checking levels and jobs for af quest mLvl = player:getMainLvl(); mJob = player:getMainJob(); -- Check if they have key item "Ordelle whetStone" OrdelleWhetstone = player:hasKeyItem(ORDELLE_WHETSTONE); sharpeningTheSwordCS = player:getVar("sharpeningTheSwordCS"); aBoysDreamCS = player:getVar("aBoysDreamCS"); -- "Father and Son" Event Dialogs if(fatherAndSon == QUEST_AVAILABLE) then player:startEvent(0x01fc); -- Start Quest "Father and Son" elseif(fatherAndSon == QUEST_ACCEPTED and player:getVar("QuestfatherAndSonVar") == 1) then player:startEvent(0x01fd); -- Finish Quest "Father and Son" (part1) elseif(sharpeningTheSword == QUEST_AVAILABLE and player:getVar("returnedAilbecheRod") == 1) then if(mJob == 7 and mLvl < 40 or mJob ~= 7) then player:startEvent(0x000c); -- Dialog after "Father and Son" (part2) -- "Sharpening the Sword" Quest Dialogs elseif(mJob == 7 and mLvl >= 40 and sharpeningTheSwordCS == 0) then player:startEvent(0x002d); -- Start Quest "Sharpening the Sword" with thank you for the rod elseif(mJob == 7 and mLvl >= 40 and sharpeningTheSwordCS == 1) then player:startEvent(0x002b); -- Start Quest "Sharpening the Sword" end elseif(sharpeningTheSword == QUEST_ACCEPTED and OrdelleWhetstone == false) then player:startEvent(0x002a); -- During Quest "Sharpening the Sword" elseif(sharpeningTheSword == QUEST_ACCEPTED and OrdelleWhetstone == true) then player:startEvent(0x002c); -- Finish Quest "Sharpening the Sword" -- "A Boy's Dream" Quest Dialogs elseif(aBoysDream == QUEST_AVAILABLE and mJob == 7 and mLvl >= 50) then if(aBoysDreamCS == 0) then player:startEvent(0x0029); -- Start Quest "A Boy's Dream" (long cs) else player:startEvent(0x0028); -- Start Quest "A Boy's Dream" (shot cs) end elseif(aBoysDreamCS == 2) then player:startEvent(0x002e); -- During Quest "A Boy's Dream" elseif(aBoysDreamCS == 3) then player:startEvent(0x0027); -- During Quest "A Boy's Dream" (after exoroche cs) elseif(aBoysDreamCS == 4) then player:startEvent(0x003c); -- During Quest "A Boy's Dream" (after trading bug) madame ? elseif(aBoysDreamCS == 5) then player:startEvent(0x002f); -- During Quest "A Boy's Dream" (after trading odontotyrannus) elseif(aBoysDreamCS >= 6) then player:startEvent(0x0019); -- During Quest "A Boy's Dream" (after Zaldon CS) else player:startEvent(0x0364); -- 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); -- "Father and Son" if(csid == 0x01fc) then player:addQuest(SANDORIA,FATHER_AND_SON); elseif(csid == 0x01fd) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17391); else player:addItem(17391); player:messageSpecial(ITEM_OBTAINED, 17391); -- Willow Fishing Rod player:setTitle(LOST_CHILD_OFFICER); player:setVar("QuestfatherAndSonVar",0); player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,FATHER_AND_SON); end elseif(csid == 0x003d) then player:setVar("returnedAilbecheRod",1); player:setTitle(FAMILY_COUNSELOR); player:tradeComplete(); -- "Sharpening the Sword" elseif((csid == 0x002d or csid == 0x002b) and option == 1) then player:addQuest(SANDORIA,SHARPENING_THE_SWORD); player:setVar("sharpeningTheSwordCS",2); player:setVar("returnedAilbecheRod",0); elseif(csid == 0x002d and option == 0) then player:setVar("sharpeningTheSwordCS",1); elseif(csid == 0x002c) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17643); else player:delKeyItem(ORDELLE_WHETSTONE); player:addItem(17643); player:messageSpecial(ITEM_OBTAINED, 17643); -- Honor Sword player:setVar("sharpeningTheSwordCS",0); player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,SHARPENING_THE_SWORD); end -- "A Boy's Dream" elseif((csid == 0x0029 or csid == 0x0028) and option == 1) then player:addQuest(SANDORIA,A_BOY_S_DREAM); player:setVar("aBoysDreamCS",2); elseif(csid == 0x0029 and option == 0) then player:setVar("aBoysDreamCS",1); elseif(csid == 0x000f and player:getVar("aBoysDreamCS") == 3) then player:setVar("aBoysDreamCS",4); elseif(csid == 0x002f and player:getVar("aBoysDreamCS") == 4) then player:setVar("aBoysDreamCS",5); elseif(csid == 0x0019 and player:getVar("aBoysDreamCS") == 6) then player:setVar("aBoysDreamCS",7); end end;
gpl-3.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Lower_Jeuno/npcs/Morefie.lua
37
1171
----------------------------------- -- Area: Lower Jeuno -- NPC: Morefie -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MOREFIE_SHOP_DIALOG); stock = {0x340F,1250, -- Silver Earring 0x3490,1250, -- Silver Ring 0x3410,4140} -- Mythril Earring 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
flyzjhz/witi-openwrt
package/ramips/ui/luci-mtk/src/modules/base/luasrc/tools/status.lua
49
5227
--[[ LuCI - Lua Configuration Interface Copyright 2011 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 ]]-- module("luci.tools.status", package.seeall) local uci = require "luci.model.uci".cursor() local function dhcp_leases_common(family) local rv = { } local nfs = require "nixio.fs" local leasefile = "/var/dhcp.leases" uci:foreach("dhcp", "dnsmasq", function(s) if s.leasefile and nfs.access(s.leasefile) then leasefile = s.leasefile return false end end) local fd = io.open(leasefile, "r") if fd then while true do local ln = fd:read("*l") if not ln then break else local ts, mac, ip, name, duid = ln:match("^(%d+) (%S+) (%S+) (%S+) (%S+)") if ts and mac and ip and name and duid then if family == 4 and not ip:match(":") then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), macaddr = mac, ipaddr = ip, hostname = (name ~= "*") and name } elseif family == 6 and ip:match(":") then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), ip6addr = ip, duid = (duid ~= "*") and duid, hostname = (name ~= "*") and name } end end end end fd:close() end local fd = io.open("/tmp/hosts/odhcpd", "r") if fd then while true do local ln = fd:read("*l") if not ln then break else local iface, duid, iaid, name, ts, id, length, ip = ln:match("^# (%S+) (%S+) (%S+) (%S+) (%d+) (%S+) (%S+) (.*)") if ip and iaid ~= "ipv4" and family == 6 then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), duid = duid, ip6addr = ip, hostname = (name ~= "-") and name } elseif ip and iaid == "ipv4" and family == 4 then rv[#rv+1] = { expires = os.difftime(tonumber(ts) or 0, os.time()), macaddr = duid, ipaddr = ip, hostname = (name ~= "-") and name } end end end fd:close() end return rv end function dhcp_leases() return dhcp_leases_common(4) end function dhcp6_leases() return dhcp_leases_common(6) end function wifi_networks() local rv = { } local ntm = require "luci.model.network".init() local dev for _, dev in ipairs(ntm:get_wifidevs()) do local rd = { up = dev:is_up(), device = dev:name(), name = dev:get_i18n(), networks = { } } local net for _, net in ipairs(dev:get_wifinets()) do rd.networks[#rd.networks+1] = { name = net:shortname(), link = net:adminlink(), up = net:is_up(), mode = net:active_mode(), ssid = net:active_ssid(), bssid = net:active_bssid(), encryption = net:active_encryption(), frequency = net:frequency(), channel = net:channel(), signal = net:signal(), quality = net:signal_percent(), noise = net:noise(), bitrate = net:bitrate(), ifname = net:ifname(), assoclist = net:assoclist(), country = net:country(), txpower = net:txpower(), txpoweroff = net:txpower_offset() } end rv[#rv+1] = rd end return rv end function wifi_network(id) local ntm = require "luci.model.network".init() local net = ntm:get_wifinet(id) if net then local dev = net:get_device() if dev then return { id = id, name = net:shortname(), link = net:adminlink(), up = net:is_up(), mode = net:active_mode(), ssid = net:active_ssid(), bssid = net:active_bssid(), encryption = net:active_encryption(), frequency = net:frequency(), channel = net:channel(), signal = net:signal(), quality = net:signal_percent(), noise = net:noise(), bitrate = net:bitrate(), ifname = net:ifname(), assoclist = net:assoclist(), country = net:country(), txpower = net:txpower(), txpoweroff = net:txpower_offset(), device = { up = dev:is_up(), device = dev:name(), name = dev:get_i18n() } } end end return { } end function switch_status(devs) local dev local switches = { } for dev in devs:gmatch("[^%s,]+") do local ports = { } local swc = io.popen("swconfig dev %q show" % dev, "r") if swc then local l repeat l = swc:read("*l") if l then local port, up = l:match("port:(%d+) link:(%w+)") if port then local speed = l:match(" speed:(%d+)") local duplex = l:match(" (%w+)-duplex") local txflow = l:match(" (txflow)") local rxflow = l:match(" (rxflow)") local auto = l:match(" (auto)") ports[#ports+1] = { port = tonumber(port) or 0, speed = tonumber(speed) or 0, link = (up == "up"), duplex = (duplex == "full"), rxflow = (not not rxflow), txflow = (not not txflow), auto = (not not auto) } end end until not l swc:close() end switches[dev] = ports end return switches end
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Kazham-Jeuno_Airship/Zone.lua
1
1198
----------------------------------- -- -- Zone: Kazham-Jeuno_Airship -- ----------------------------------- ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; return cs; end; ----------------------------------- -- onTransportEvent ----------------------------------- function onTransportEvent(player,transport) player:startEvent(0x000A); 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 == 0x000A) then prevzone = player:getPreviousZone(); if (prevzone == 250) then player:setPos(0,0,0,0,246); elseif (prevzone == 246) then player:setPos(0,0,0,0,250); end end end;
gpl-3.0
madpilot78/ntopng
scripts/lua/rest/get/pcap/live_extraction.lua
1
1438
-- -- (C) 2013-21 - ntop.org -- local dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path require "lua_utils" local json = require("dkjson") local recording_utils = require "recording_utils" local function send_error(msg) sendHTTPContentTypeHeader('application/json') local res = {} res.error = msg print(json.encode(res)) end if not recording_utils.isExtractionAvailable() then send_error(i18n("traffic_recording.not_granted")) else if _GET["epoch_begin"] == nil or _GET["epoch_end"] == nil then send_error(i18n("traffic_recording.missing_parameters")) else interface.select(ifname) local ifid = tonumber(_GET["ifid"]) local filter = _GET["bpf_filter"] local time_from = tonumber(_GET["epoch_begin"]) local time_to = tonumber(_GET["epoch_end"]) if ifid == nil then local ifstats = interface.getStats() ifid = ifstats.id end if filter == nil then filter = "" end local timeline_path if recording_utils.getCurrentTrafficRecordingProvider(ifid) ~= "ntopng" then timeline_path = recording_utils.getCurrentTrafficRecordingProviderTimelinePath(ifid) end local fname = time_from.."-"..time_to..".pcap" sendHTTPContentTypeHeader('application/vnd.tcpdump.pcap', 'attachment; filename="'..fname..'"') ntop.runLiveExtraction(ifid, time_from, time_to, filter, timeline_path) end end
gpl-3.0
madpilot78/ntopng
scripts/plugins/monitors/network/active_monitoring/web_gui/active_monitoring_stats.lua
1
7399
-- -- (C) 2013-21 - ntop.org -- local dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path require "lua_utils" local page_utils = require("page_utils") local alert_consts = require("alert_consts") local plugins_utils = require("plugins_utils") local ui_utils = require("ui_utils") local template = require("template_utils") local json = require("dkjson") local active_monitoring_utils = plugins_utils.loadModule("active_monitoring", "am_utils") local active_monitoring_pools = require("active_monitoring_pools") local am_pool = active_monitoring_pools:create() local graph_utils = require("graph_utils") local alert_utils = require("alert_utils") local checks = require("checks") local auth = require "auth" local ts_creation = plugins_utils.timeseriesCreationEnabled() if not isAllowedSystemInterface() then return end sendHTTPContentTypeHeader('text/html') page_utils.set_active_menu_entry(page_utils.menu_entries.active_monitor) dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua") local host = _GET["am_host"] local page = _GET["page"] or ('overview') local measurement = _GET["measurement"] local base_url = plugins_utils.getUrl("active_monitoring_stats.lua") .. "?ifid=" .. getInterfaceId(ifname) local url = base_url local info = ntop.getInfo() local measurement_info if (not checks.isSystemScriptEnabled("active_monitoring")) then -- The active monitoring is disabled print [[<div class="alert alert-warning" role="alert">]] print(i18n("host_config.active_monitor_enable", { url = ntop.getHttpPrefix() .. '/lua/admin/edit_configset.lua?subdir=system&check=active_monitoring#all' })) print [[</div>]] dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua") return end if (not isEmptyString(host) and not isEmptyString(measurement)) then host = active_monitoring_utils.getHost(host, measurement) if host then measurement_info = active_monitoring_utils.getMeasurementInfo(host.measurement) end else host = nil end if host then url = url .. "&am_host=" .. host.host .. "&measurement=" .. host.measurement end local title = i18n("graphs.active_monitoring") local host_label = "" if (host ~= nil) then host_label = active_monitoring_utils.formatAmHost(host.host, host.measurement, true) end if auth.has_capability(auth.capabilities.active_monitoring) then if (_POST["action"] == "reset_config") then active_monitoring_utils.resetConfig() end end local navbar_title = ui_utils.create_navbar_title(title, host_label, "/plugins/active_monitoring_stats.lua") page_utils.print_navbar(navbar_title, url, { { active = page == "overview" or not page, page_name = "overview", label = "<i class=\"fas fa-lg fa-home\"></i>", url = (host ~= nil and url or base_url) }, { hidden = (host == nil) or not ts_creation, active = page == "historical", page_name = "historical", label = "<i class='fas fa-lg fa-chart-area'></i>" }, { hidden = not areAlertsEnabled(), active = page == "alerts", page_name = "alerts", label = "<i class=\"fas fa-lg fa-exclamation-triangle\"></i>", url = ntop.getHttpPrefix().."/lua/alert_stats.lua?&status=engaged&page=am_host" } }) -- ####################################################### if (page == "overview") then -- Create a filter list to use inside the overview page -- to filter the datatable local pool_filters = {} for key, value in pairs(am_pool:get_all_pools()) do pool_filters[#pool_filters + 1] = {key = "pool-" .. key, label = value.name, regex = tostring(value.pool_id)} end local measurements_info = {} -- This information is required in active_monitoring_utils.js in order to properly -- render the template for key, info in pairs(active_monitoring_utils.getMeasurementsInfo()) do measurements_info[key] = { label = i18n(info.i18n_label) or info.i18n_label, granularities = active_monitoring_utils.getAvailableGranularities( key), operator = info.operator, unit = i18n(info.i18n_unit) or info.i18n_unit, force_host = info.force_host, max_threshold = info.max_threshold, default_threshold = info.default_threshold } end local context = { json = json, template_utils = template, plugins_utils = plugins_utils, generate_select = generate_select, ui_utils = ui_utils, am_stats = { pool_filters = pool_filters, measurements_info = measurements_info, get_host = (_GET["am_host"] or ""), pools = am_pool, notes = { i18n("active_monitoring_stats.note3", {product = info.product}), i18n("active_monitoring_stats.note_alert"), i18n("active_monitoring_stats.note_availability") } } } -- template render print(plugins_utils.renderTemplate("active_monitoring", "active_monitoring_stats.template", context)) elseif ((page == "historical") and (host ~= nil) and (measurement_info ~= nil)) then local suffix = "_" .. host.granularity local schema = _GET["ts_schema"] or ("am_host:val" .. suffix) local selected_epoch = _GET["epoch"] or "" local tags = { ifid = getSystemInterfaceId(), host = host.host, metric = host.measurement --[[ note: measurement is a reserved InfluxDB keyword ]] } local am_ts_label local am_metric_label local notes = {{content = i18n("graphs.red_line_unreachable")}} if measurement_info.i18n_am_ts_label then am_ts_label = i18n(measurement_info.i18n_am_ts_label) or measurement_info.i18n_am_ts_label else -- Fallback am_ts_label = i18n("graphs.num_ms_rtt") end if measurement_info.i18n_am_ts_metric then am_metric_label = i18n(measurement_info.i18n_am_ts_metric) or measurement_info.i18n_am_ts_metric else am_metric_label = i18n("flow_details.round_trip_time") end url = url .. "&page=historical" local timeseries = { { schema = "am_host:val" .. suffix, label = am_ts_label, value_formatter = measurement_info.value_js_formatter or "NtopUtils.fmillis", metrics_labels = {am_metric_label}, show_unreachable = true -- Show the unreachable host status as a red line } } for _, note in ipairs(measurement_info.i18n_chart_notes or {}) do notes[#notes + 1] = {content = i18n(note) or note} end for _, ts_info in ipairs(measurement_info.additional_timeseries or {}) do -- Add the per-granularity suffix (e.g. _min) ts_info.schema = ts_info.schema .. suffix timeseries[#timeseries + 1] = ts_info end graph_utils.drawGraphs(getSystemInterfaceId(), schema, tags, _GET["zoom"], url, selected_epoch, {timeseries = timeseries, notes = notes}) end -- ####################################################### dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
gpl-3.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Tasks/SchoolCenter/XcodePage.lua
1
2507
--[[ Title: XcodePage Author(s): yangguiyi Date: 2021/6/2 Desc: Use Lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/SchoolCenter/XcodePage.lua").Show(); --]] local KeepWorkItemManager = NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/KeepWorkItemManager.lua"); local HttpWrapper = NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/HttpWrapper.lua"); local XcodePage = NPL.export(); local server_time = 0 local page local TypeToImg = { ["lesson_progress"] = "Texture/Aries/Creator/keepwork/SchoolCenter/lesson_progress_32bits.jpg#0 0 128 128", ["work_progress"] = "Texture/Aries/Creator/keepwork/SchoolCenter/work_progress_32bits.jpg#0 0 128 128", ["teach_statistics"] = "Texture/Aries/Creator/keepwork/SchoolCenter/teach_statistics_32bits.jpg#0 0 128 128", ["personal_data_statistics"] = "Texture/Aries/Creator/keepwork/SchoolCenter/personal_data_statistics_32bits.jpg#0 0 128 128", ["3d_school_management"] = "Texture/Aries/Creator/keepwork/SchoolCenter/3d_school_management_32bits.jpg#0 0 128 128", } function XcodePage.OnInit() page = document:GetPageCtrl(); page.OnClose = XcodePage.CloseView end function XcodePage.Show(type) XcodePage.type = type or "lesson_progress" XcodePage.ShowView() end function XcodePage.ShowView() if page and page:IsVisible() then return end XcodePage.HandleData() local params = { url = "script/apps/Aries/Creator/Game/Tasks/SchoolCenter/XcodePage.html", name = "XcodePage.Show", isShowTitleBar = false, DestroyOnClose = true, style = CommonCtrl.WindowFrame.ContainerStyle, allowDrag = true, enable_esc_key = true, zorder = 0, app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key, directPosition = true, align = "_ct", x = -452/2, y = -280/2, width = 452, height = 280, }; System.App.Commands.Call("File.MCMLWindowFrame", params); end function XcodePage.FreshView() local parent = page:GetParentUIObject() end function XcodePage.OnRefresh() if(page)then page:Refresh(0); end XcodePage.FreshView() end function XcodePage.CloseView() XcodePage.ClearData() end function XcodePage.ClearData() end function XcodePage.HandleData() end function XcodePage.GetXcodeImg() local img = TypeToImg[XcodePage.type] return string.format("background:url(%s);", img) end
gpl-2.0
pakoito/ToME---t-engine4
game/modules/tome/data/zones/high-peak/grids.lua
3
8976
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org load("/data/general/grids/basic.lua") load("/data/general/grids/water.lua") load("/data/general/grids/forest.lua") load("/data/general/grids/lava.lua") load("/data/general/grids/cave.lua") newEntity{ define_as = "FAR_EAST_PORTAL", name = "Farportal: the Far East", display = '&', color_r=255, color_g=0, color_b=220, back_color=colors.VIOLET, image = "terrain/marble_floor.png", notice = true, always_remember = true, show_tooltip = true, desc = [[A farportal is a way to travel incredible distances in the blink of an eye. They usually require an external item to use. You have no idea if it is even two-way. This one seems to go to the Far East.]], orb_portal = { change_level = 1, change_zone = "wilderness", change_wilderness = { spot = {type="farportal-end", subtype="fareast"}, }, message = "#VIOLET#You enter the swirling portal and in the blink of an eye you set foot on the Far East, with no trace of the portal...", on_use = function(self, who) end, }, } newEntity{ base = "FAR_EAST_PORTAL", define_as = "CFAR_EAST_PORTAL", image = "terrain/marble_floor.png", add_displays = {class.new{image="terrain/farportal-base.png", display_x=-1, display_y=-1, display_w=3, display_h=3}}, on_added = function(self, level, x, y) level.map:particleEmitter(x, y, 3, "farportal_vortex") level.map:particleEmitter(x, y, 3, "farportal_lightning") level.map:particleEmitter(x, y, 3, "farportal_lightning") level.map:particleEmitter(y, y, 3, "farportal_lightning") end, } newEntity{ define_as = "WEST_PORTAL", name = "Farportal: Iron Throne", display = '&', color_r=255, color_g=0, color_b=220, back_color=colors.VIOLET, image = "terrain/marble_floor.png", notice = true, always_remember = true, show_tooltip = true, desc = [[A farportal is a way to travel incredible distances in the blink of an eye. They usually require an external item to use. You have no idea if it is even two-way. This one seems to go to the Iron Throne in the West.]], orb_portal = { change_level = 1, change_zone = "wilderness", change_wilderness = { spot = {type="farportal-end", subtype="iron-throne"}, }, message = "#VIOLET#You enter the swirling portal and in the blink of an eye you set foot on the slopes of the Iron Throne, with no trace of the portal...", on_use = function(self, who) end, }, } newEntity{ base = "WEST_PORTAL", define_as = "CWEST_PORTAL", image = "terrain/marble_floor.png", add_displays = {class.new{image="terrain/farportal-base.png", display_x=-1, display_y=-1, display_w=3, display_h=3}}, on_added = function(self, level, x, y) level.map:particleEmitter(x, y, 3, "farportal_vortex") level.map:particleEmitter(x, y, 3, "farportal_lightning") level.map:particleEmitter(x, y, 3, "farportal_lightning") level.map:particleEmitter(x, y, 3, "farportal_lightning") end, } newEntity{ define_as = "VOID_PORTAL", name = "Farportal: the Void", display = '&', color=colors.DARK_GREY, back_color=colors.VIOLET, image = "terrain/marble_floor.png", notice = true, always_remember = true, show_tooltip = true, desc = [[A farportal is a way to travel incredible distances in the blink of an eye. They usually require an external item to use. You have no idea if it is even two-way. This one seems to go to an unknown place, seemingly out of this world. You dare not use it.]], } newEntity{ base = "VOID_PORTAL", define_as = "CVOID_PORTAL", image = "terrain/marble_floor.png", add_displays = {class.new{image="terrain/farportal-base.png", display_x=-1, display_y=-1, display_w=3, display_h=3}}, on_added = function(self, level, x, y) level.map:particleEmitter(x, y, 3, "farportal_vortex", {vortex="shockbolt/terrain/farportal-void-vortex"}) level.map:particleEmitter(x, y, 3, "farportal_lightning") level.map:particleEmitter(x, y, 3, "farportal_lightning") level.map:particleEmitter(y, y, 3, "farportal_lightning") end, } local invocation_close = function(self, who) if not who:hasQuest("high-peak") or who:hasQuest("high-peak"):isEnded() then return end -- Remove the level spot local spot = game.level:pickSpot{type="portal", subtype=self.summon} if not spot then return end game.logPlayer(who, "#LIGHT_BLUE#You use the orb on the portal, shutting it down easily.") for i = 1, #game.level.spots do if game.level.spots[i] == spot then table.remove(game.level.spots, i) break end end local g = game.level.map(spot.x, spot.y, engine.Map.TERRAIN) g.name = g.name .. " (disabled)" g.color_r = colors.WHITE.r g.color_g = colors.WHITE.g g.color_b = colors.WHITE.b g:removeAllMOs() game.level.map:updateMap(spot.x, spot.y) who:setQuestStatus("high-peak", engine.Quest.COMPLETED, "closed-portal-"..self.summon) end newEntity{ define_as = "ORB_UNDEATH", name = "Invocation Portal: Undeath", image = "terrain/marble_floor.png", add_mos = {{image="terrain/demon_portal4.png"}}, display = '&', color=colors.GREY, back_color=colors.PURPLE, notice = true, always_remember = true, show_tooltip = true, desc = [[An invocation portal, perpetually summoning beings through it.]], orb_command = { summon = "undead", special = invocation_close, }, } newEntity{ define_as = "ORB_ELEMENTS", name = "Invocation Portal: Elements", image = "terrain/marble_floor.png", add_mos = {{image="terrain/demon_portal4.png"}}, display = '&', color=colors.LIGHT_RED, back_color=colors.PURPLE, notice = true, always_remember = true, show_tooltip = true, desc = [[An invocation portal, perpetually summoning beings through it.]], orb_command = { summon = "elemental", special = invocation_close, }, } newEntity{ define_as = "ORB_DRAGON", name = "Invocation Portal: Dragons", image = "terrain/marble_floor.png", add_mos = {{image="terrain/demon_portal4.png"}}, display = '&', color=colors.LIGHT_BLUE, back_color=colors.PURPLE, notice = true, always_remember = true, show_tooltip = true, desc = [[An invocation portal, perpetually summoning beings through it.]], orb_command = { summon = "dragon", special = invocation_close, }, } newEntity{ define_as = "ORB_DESTRUCTION", name = "Invocation Portal: Destruction", image = "terrain/marble_floor.png", add_mos = {{image="terrain/demon_portal4.png"}}, display = '&', color=colors.WHITE, back_color=colors.PURPLE, notice = true, always_remember = true, show_tooltip = true, desc = [[An invocation portal, perpetually summoning beings through it.]], orb_command = { summon = "demon", special = invocation_close, }, } newEntity{ define_as = "PORTAL_BOSS", name = "Portal: The Sanctum", image = "terrain/marble_floor.png", add_mos = {{image="terrain/demon_portal4.png"}}, display = '&', color=colors.LIGHT_BLUE, back_color=colors.PURPLE, notice = true, always_remember = true, show_tooltip = true, desc = [[This portal seems to connect to another part of this level.]], change_level_check = function() game.bignews:say(60, "#GOLD#This portal looks like it reacts only to the Orb of Many Ways.") return true end, change_level = 1, orb_portal = { nothing = true, message = "#VIOLET#You enter the swirling portal and appear in a large room with other portals and the two wizards.", on_use = function() game:changeLevel(11, nil, {direct_switch=true}) -- Special level, can not get to it any other way if game.player:hasQuest("high-peak"):isCompleted("sanctum-chat") then return end local Chat = require "engine.Chat" local chat = Chat.new("sorcerer-fight", {name="Elandar"}, game.player) chat:invoke() game.player:hasQuest("high-peak"):setStatus(engine.Quest.COMPLETED, "sanctum-chat") game.player:hasQuest("high-peak"):start_end_combat() end, }, } newEntity{ define_as = "HIGH_PEAK_UP", image = "terrain/marble_floor.png", add_mos = {{image = "terrain/stair_up.png"}}, name = "next level", display = '>', color_r=255, color_g=255, color_b=0, notice = true, always_remember = true, change_level = 1, } newEntity{ define_as = "CAVE_HIGH_PEAK_UP", image = "terrain/cave/cave_floor_1_01.png", add_displays = {class.new{image="terrain/cave/cave_stairs_up_2_01.png"}}, name = "next level", display = '>', color_r=255, color_g=255, color_b=0, notice = true, always_remember = true, change_level = 1, }
gpl-3.0
pakoito/ToME---t-engine4
game/modules/tome/data/general/encounters/fareast.lua
2
3442
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org newEntity{ name = "Underwater Cave", type = "harmless", subtype = "special", unique = true, level_range = {30, 40}, rarity = 1, special_filter = function(self) return self:findSpotGeneric(game.player, function(map, x, y) local enc = map:checkAllEntities(x, y, "can_encounter") return enc and enc == "water" end) and true or false end, on_encounter = function(self, who) local x, y = self:findSpotGeneric(who, function(map, x, y) local enc = map:checkAllEntities(x, y, "can_encounter") return enc and enc == "water" end) if not x then return end local g = game.level.map(x, y, engine.Map.TERRAIN):cloneFull() g:removeAllMOs() g.name = "Entrance to an underwater cave" g.display='>' g.color_r=colors.AQUAMARINE.r g.color_g=colors.AQUAMARINE.g g.color_b=colors.AQUAMARINE.b g.notice = true g.change_level=1 g.change_zone="flooded-cave" g.glow=true g.add_displays = g.add_displays or {} g.add_displays[#g.add_displays+1] = mod.class.Grid.new{image="terrain/underwater/subsea_cave_entrance_01.png", z=4, display_h=2, display_y=-1} g.does_block_move = nil g:altered() g:initGlow() game.zone:addEntity(game.level, g, "terrain", x, y) game.logPlayer(who, "#LIGHT_BLUE#You notice an entrance to an underwater cave.") return true end, } newEntity{ name = "Shadow Crypt", type = "hostile", subtype = "special", unique = true, immediate = {"world-encounter", "fareast"}, on_encounter = function(self, who) local x, y = self:findSpot(who) if not x then return end local g = game.level.map(x, y, engine.Map.TERRAIN):cloneFull() g.name = "Entrance to a dark crypt" g.display='>' g.color_r=128 g.color_g=128 g.color_b=128 g.notice = true g.change_level=1 g.change_zone="shadow-crypt" g.glow=true g.add_displays = g.add_displays or {} g.add_displays[#g.add_displays+1] = mod.class.Grid.new{image="terrain/dungeon_entrance_closed02.png", z=5} g:altered() g:initGlow() game.zone:addEntity(game.level, g, "terrain", x, y) return true end } --[[ -- A little more context; this made people so annoyed on both sides, taht I've had enough of it. -- This was never intended as a reference to any real world thing and if people are annoyed at it i'm sorry -- It's gone now newEntity{ name = "Orc Breeding Pits", type = "harmless", subtype = "special", unique = true, level_range = {35, 50}, rarity = 20, on_world_encounter = "orc-breeding-pits", on_encounter = function(self, who) who.energy.value = game.energy_to_act game.paused = true who:runStop() local Chat = require "engine.Chat" local chat = Chat.new("orc-breeding-pits", {name="Dying sun paladin"}, who) chat:invoke() return true end, } ]]
gpl-3.0
pakoito/ToME---t-engine4
game/engines/default/engine/dialogs/DisplayResolution.lua
3
4072
-- TE4 - T-Engine 4 -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" local Dialog = require "engine.ui.Dialog" local List = require "engine.ui.List" local Checkbox = require "engine.ui.Checkbox" module(..., package.seeall, class.inherit(Dialog)) function _M:init(on_change) self.on_change = on_change self:generateList() local w, h, fullscreen, borderless = core.display.size() Dialog.init(self, "Switch Resolution", 300, 20) self.c_list = List.new{width=self.iw, nb_items=#self.list, list=self.list, fct=function(item) self:use(item) end} self.c_fs = Checkbox.new{title="Fullscreen", default=fullscreen, fct=function() end, on_change=function(s) if s then self.c_bl.checked = false end end } self.c_bl = Checkbox.new{title="Borderless", default=borderless, fct=function() end, on_change=function(s) if s then self.c_fs.checked = false end end } self:loadUI{ {left=0, top=0, ui=self.c_fs}, {left=self.c_fs.w + 5, top=0, ui=self.c_bl}, {left=0, top=self.c_fs.h, ui=self.c_list}, } self:setFocus(self.c_list) self:setupUI(true, true) self.key:addBinds{ EXIT = function() game:unregisterDialog(self) end, } end function _M:use(item) local mode = " Windowed" if self.c_fs.checked then mode = " Fullscreen" elseif self.c_bl.checked then mode = " Borderless" end local r = item.r..mode local _, _, w, h = r:find("^([0-9]+)x([0-9]+)") -- See if we need a restart (confirm). if core.display.setWindowSizeRequiresRestart(w, h, self.c_fs.checked , self.c_bl.checked) then Dialog:yesnoPopup("Engine Restart Required" , "Continue?" .. (game.creating_player and "" or " (progress will be saved)") , function(restart) if restart then local resetPos = Dialog:yesnoPopup("Reset Window Position?" , "Simply restart or restart+reset window position?" , function(simplyRestart) if not simplyRestart then core.display.setWindowPos(0, 0) game:onWindowMoved(0, 0) end game:setResolution(r, true) -- Save game and reboot if not game.creating_player then game:saveGame() end util.showMainMenu(false, nil, nil , game.__mod_info.short_name, game.save_name , false) end, "Restart", "Restart with reset") end end, "Yes", "No") else game:setResolution(r, true) end game:unregisterDialog(self) if self.on_change then self.on_change(r) end end function _M:generateList() local l = {} local seen = {} for r, d in pairs(game.available_resolutions) do seen[d[1]] = seen[d[1]] or {} if not seen[d[1]][d[2]] then l[#l+1] = r seen[d[1]][d[2]] = true end end table.sort(l, function(a,b) if game.available_resolutions[a][2] == game.available_resolutions[b][2] then return (game.available_resolutions[a][3] and 1 or 0) < (game.available_resolutions[b][3] and 1 or 0) elseif game.available_resolutions[a][1] == game.available_resolutions[b][1] then return game.available_resolutions[a][2] < game.available_resolutions[b][2] else return game.available_resolutions[a][1] < game.available_resolutions[b][1] end end) -- Makes up the list local list = {} local i = 0 for _, r in ipairs(l) do local _, _, w, h = r:find("^([0-9]+)x([0-9]+)") local r = w.."x"..h list[#list+1] = { name=string.char(string.byte('a') + i)..") "..r, r=r } i = i + 1 end self.list = list end
gpl-3.0
devFRIND/M.F.I_BOT
plugins/isup.lua
741
3095
do local socket = require("socket") local cronned = load_from_file('data/isup.lua') local function save_cron(msg, url, delete) local origin = get_receiver(msg) if not cronned[origin] then cronned[origin] = {} end if not delete then table.insert(cronned[origin], url) else for k,v in pairs(cronned[origin]) do if v == url then table.remove(cronned[origin], k) end end end serialize_to_file(cronned, 'data/isup.lua') return 'Saved!' end local function is_up_socket(ip, port) print('Connect to', ip, port) local c = socket.try(socket.tcp()) c:settimeout(3) local conn = c:connect(ip, port) if not conn then return false else c:close() return true end end local function is_up_http(url) -- Parse URL from input, default to http local parsed_url = URL.parse(url, { scheme = 'http', authority = '' }) -- Fix URLs without subdomain not parsed properly if not parsed_url.host and parsed_url.path then parsed_url.host = parsed_url.path parsed_url.path = "" end -- Re-build URL local url = URL.build(parsed_url) local protocols = { ["https"] = https, ["http"] = http } local options = { url = url, redirect = false, method = "GET" } local response = { protocols[parsed_url.scheme].request(options) } local code = tonumber(response[2]) if code == nil or code >= 400 then return false end return true end local function isup(url) local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$' local ip,port = string.match(url, pattern) local result = nil -- !isup 8.8.8.8:53 if ip then port = port or '80' result = is_up_socket(ip, port) else result = is_up_http(url) end return result end local function cron() for chan, urls in pairs(cronned) do for k,url in pairs(urls) do print('Checking', url) if not isup(url) then local text = url..' looks DOWN from here. 😱' send_msg(chan, text, ok_cb, false) end end end end local function run(msg, matches) if matches[1] == 'cron delete' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2], true) elseif matches[1] == 'cron' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2]) elseif isup(matches[1]) then return matches[1]..' looks UP from here. 😃' else return matches[1]..' looks DOWN from here. 😱' end end return { description = "Check if a website or server is up.", usage = { "!isup [host]: Performs a HTTP request or Socket (ip:port) connection", "!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)", "!isup cron delete [host]: Disable checking that host." }, patterns = { "^!isup (cron delete) (.*)$", "^!isup (cron) (.*)$", "^!isup (.*)$", "^!ping (.*)$", "^!ping (cron delete) (.*)$", "^!ping (cron) (.*)$" }, run = run, cron = cron } end
gpl-2.0
hfjgjfg/sss25
plugins/isup.lua
741
3095
do local socket = require("socket") local cronned = load_from_file('data/isup.lua') local function save_cron(msg, url, delete) local origin = get_receiver(msg) if not cronned[origin] then cronned[origin] = {} end if not delete then table.insert(cronned[origin], url) else for k,v in pairs(cronned[origin]) do if v == url then table.remove(cronned[origin], k) end end end serialize_to_file(cronned, 'data/isup.lua') return 'Saved!' end local function is_up_socket(ip, port) print('Connect to', ip, port) local c = socket.try(socket.tcp()) c:settimeout(3) local conn = c:connect(ip, port) if not conn then return false else c:close() return true end end local function is_up_http(url) -- Parse URL from input, default to http local parsed_url = URL.parse(url, { scheme = 'http', authority = '' }) -- Fix URLs without subdomain not parsed properly if not parsed_url.host and parsed_url.path then parsed_url.host = parsed_url.path parsed_url.path = "" end -- Re-build URL local url = URL.build(parsed_url) local protocols = { ["https"] = https, ["http"] = http } local options = { url = url, redirect = false, method = "GET" } local response = { protocols[parsed_url.scheme].request(options) } local code = tonumber(response[2]) if code == nil or code >= 400 then return false end return true end local function isup(url) local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$' local ip,port = string.match(url, pattern) local result = nil -- !isup 8.8.8.8:53 if ip then port = port or '80' result = is_up_socket(ip, port) else result = is_up_http(url) end return result end local function cron() for chan, urls in pairs(cronned) do for k,url in pairs(urls) do print('Checking', url) if not isup(url) then local text = url..' looks DOWN from here. 😱' send_msg(chan, text, ok_cb, false) end end end end local function run(msg, matches) if matches[1] == 'cron delete' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2], true) elseif matches[1] == 'cron' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2]) elseif isup(matches[1]) then return matches[1]..' looks UP from here. 😃' else return matches[1]..' looks DOWN from here. 😱' end end return { description = "Check if a website or server is up.", usage = { "!isup [host]: Performs a HTTP request or Socket (ip:port) connection", "!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)", "!isup cron delete [host]: Disable checking that host." }, patterns = { "^!isup (cron delete) (.*)$", "^!isup (cron) (.*)$", "^!isup (.*)$", "^!ping (.*)$", "^!ping (cron delete) (.*)$", "^!ping (cron) (.*)$" }, run = run, cron = cron } end
gpl-2.0
BinChengfei/openwrt-3.10.14
package/ramips/ui/luci-mtk/src/modules/admin-mini/luasrc/controller/mini/system.lua
71
6669
--[[ 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$ ]]-- module("luci.controller.mini.system", package.seeall) function index() entry({"mini", "system"}, alias("mini", "system", "index"), _("System"), 40).index = true entry({"mini", "system", "index"}, cbi("mini/system", {autoapply=true}), _("General"), 1) entry({"mini", "system", "passwd"}, form("mini/passwd"), _("Admin Password"), 10) entry({"mini", "system", "backup"}, call("action_backup"), _("Backup / Restore"), 80) entry({"mini", "system", "upgrade"}, call("action_upgrade"), _("Flash Firmware"), 90) entry({"mini", "system", "reboot"}, call("action_reboot"), _("Reboot"), 100) end function action_backup() local reset_avail = os.execute([[grep '"rootfs_data"' /proc/mtd >/dev/null 2>&1]]) == 0 local restore_cmd = "gunzip | tar -xC/ >/dev/null 2>&1" local backup_cmd = "tar -c %s | gzip 2>/dev/null" local restore_fpi luci.http.setfilehandler( function(meta, chunk, eof) if not restore_fpi then restore_fpi = io.popen(restore_cmd, "w") end if chunk then restore_fpi:write(chunk) end if eof then restore_fpi:close() end end ) local upload = luci.http.formvalue("archive") local backup = luci.http.formvalue("backup") local reset = reset_avail and luci.http.formvalue("reset") if upload and #upload > 0 then luci.template.render("mini/applyreboot") luci.sys.reboot() elseif backup then local reader = ltn12_popen(backup_cmd:format(_keep_pattern())) luci.http.header('Content-Disposition', 'attachment; filename="backup-%s-%s.tar.gz"' % { luci.sys.hostname(), os.date("%Y-%m-%d")}) luci.http.prepare_content("application/x-targz") luci.ltn12.pump.all(reader, luci.http.write) elseif reset then luci.template.render("mini/applyreboot") luci.util.exec("mtd -r erase rootfs_data") else luci.template.render("mini/backup", {reset_avail = reset_avail}) end end function action_reboot() local reboot = luci.http.formvalue("reboot") luci.template.render("mini/reboot", {reboot=reboot}) if reboot then luci.sys.reboot() end end function action_upgrade() require("luci.model.uci") local tmpfile = "/tmp/firmware.img" local function image_supported() -- XXX: yay... return ( 0 == os.execute( ". /lib/functions.sh; " .. "include /lib/upgrade; " .. "platform_check_image %q >/dev/null" % tmpfile ) ) end local function image_checksum() return (luci.sys.exec("md5sum %q" % tmpfile):match("^([^%s]+)")) end local function storage_size() local size = 0 if nixio.fs.access("/proc/mtd") then for l in io.lines("/proc/mtd") do local d, s, e, n = l:match('^([^%s]+)%s+([^%s]+)%s+([^%s]+)%s+"([^%s]+)"') if n == "linux" then size = tonumber(s, 16) break end end elseif nixio.fs.access("/proc/partitions") then for l in io.lines("/proc/partitions") do local x, y, b, n = l:match('^%s*(%d+)%s+(%d+)%s+([^%s]+)%s+([^%s]+)') if b and n and not n:match('[0-9]') then size = tonumber(b) * 1024 break end end end return size end -- Install upload handler local file luci.http.setfilehandler( function(meta, chunk, eof) if not nixio.fs.access(tmpfile) and not file and chunk and #chunk > 0 then file = io.open(tmpfile, "w") end if file and chunk then file:write(chunk) end if file and eof then file:close() end end ) -- Determine state local keep_avail = true local step = tonumber(luci.http.formvalue("step") or 1) local has_image = nixio.fs.access(tmpfile) local has_support = image_supported() local has_platform = nixio.fs.access("/lib/upgrade/platform.sh") local has_upload = luci.http.formvalue("image") -- This does the actual flashing which is invoked inside an iframe -- so don't produce meaningful errors here because the the -- previous pages should arrange the stuff as required. if step == 4 then if has_platform and has_image and has_support then -- Mimetype text/plain luci.http.prepare_content("text/plain") luci.http.write("Starting luci-flash...\n") -- Now invoke sysupgrade local keepcfg = keep_avail and luci.http.formvalue("keepcfg") == "1" local flash = ltn12_popen("/sbin/luci-flash %s %q" %{ keepcfg and "-k %q" % _keep_pattern() or "", tmpfile }) luci.ltn12.pump.all(flash, luci.http.write) -- Make sure the device is rebooted luci.sys.reboot() end -- -- This is step 1-3, which does the user interaction and -- image upload. -- -- Step 1: file upload, error on unsupported image format elseif not has_image or not has_support or step == 1 then -- If there is an image but user has requested step 1 -- or type is not supported, then remove it. if has_image then nixio.fs.unlink(tmpfile) end luci.template.render("mini/upgrade", { step=1, bad_image=(has_image and not has_support or false), keepavail=keep_avail, supported=has_platform } ) -- Step 2: present uploaded file, show checksum, confirmation elseif step == 2 then luci.template.render("mini/upgrade", { step=2, checksum=image_checksum(), filesize=nixio.fs.stat(tmpfile).size, flashsize=storage_size(), keepconfig=(keep_avail and luci.http.formvalue("keepcfg") == "1") } ) -- Step 3: load iframe which calls the actual flash procedure elseif step == 3 then luci.template.render("mini/upgrade", { step=3, keepconfig=(keep_avail and luci.http.formvalue("keepcfg") == "1") } ) end end function _keep_pattern() local kpattern = "" local files = luci.model.uci.cursor():get_all("luci", "flash_keep") if files then kpattern = "" for k, v in pairs(files) do if k:sub(1,1) ~= "." and nixio.fs.glob(v)() then kpattern = kpattern .. " " .. v end end end return kpattern end function ltn12_popen(command) local fdi, fdo = nixio.pipe() local pid = nixio.fork() if pid > 0 then fdo:close() local close return function() local buffer = fdi:read(2048) local wpid, stat = nixio.waitpid(pid, "nohang") if not close and wpid and stat == "exited" then close = true end if buffer and #buffer > 0 then return buffer elseif close then fdi:close() return nil end end elseif pid == 0 then nixio.dup(fdo, nixio.stdout) fdi:close() fdo:close() nixio.exec("/bin/sh", "-c", command) end end
gpl-2.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Items/ItemTimeSeriesOverlay.lua
1
2092
--[[ Title: ItemTimeSeriesOverlay Author(s): LiXizhi Date: 2016/1/3 Desc: use the lib: ------------------------------------------------------------ NPL.load("(gl)script/apps/Aries/Creator/Game/Items/ItemTimeSeriesOverlay.lua"); local ItemTimeSeriesOverlay = commonlib.gettable("MyCompany.Aries.Game.Items.ItemTimeSeriesOverlay"); local item_ = ItemTimeSeriesOverlay:new({}); ------------------------------------------------------- ]] NPL.load("(gl)script/ide/math/vector.lua"); NPL.load("(gl)script/apps/Aries/Creator/Game/Movie/ActorOverlay.lua"); local ActorOverlay = commonlib.gettable("MyCompany.Aries.Game.Movie.ActorOverlay"); local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager"); local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine") local TaskManager = commonlib.gettable("MyCompany.Aries.Game.TaskManager") local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types") local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic") local ItemTimeSeriesOverlay = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Items.ItemTimeSeries"), commonlib.gettable("MyCompany.Aries.Game.Items.ItemTimeSeriesOverlay")); block_types.RegisterItemClass("ItemTimeSeriesOverlay", ItemTimeSeriesOverlay); -- @param template: icon -- @param radius: the half radius of the object. function ItemTimeSeriesOverlay:ctor() end -- create actor from item stack. -- @param isReuseActor: whether we will reuse actor in the scene with the same name instead of creating a new entity. default to false. -- @param name: if not provided, it will use the name in itemStack function ItemTimeSeriesOverlay:CreateActorFromItemStack(itemStack, movieclipEntity, isReuseActor, name, movieclip) local actor = ActorOverlay:new():Init(itemStack, movieclipEntity, isReuseActor, name, movieclip); return actor; end function ItemTimeSeriesOverlay:GetTooltipFromItemStack(itemStack) local name = itemStack:GetDisplayName(); if(not name and name~="") then return self:GetTooltip(); else return format(L"%s:右键编辑", name); end end
gpl-2.0
pakoito/ToME---t-engine4
game/modules/tome/data/general/objects/random-artifacts/ammo.lua
2
13651
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org local Stats = require "engine.interface.ActorStats" local Talents = require "engine.interface.ActorTalents" ---------------------------------------------------------------- -- Ammo Properties ---------------------------------------------------------------- newEntity{ theme={physical=true}, name="damage", points = 1, rarity = 10, level_range = {1, 50}, combat = { dam = resolvers.randartmax(2, 20), }, } newEntity{ theme={physical=true}, name="apr", points = 1, rarity = 10, level_range = {1, 50}, combat = { apr = resolvers.randartmax(1, 15), }, } newEntity{ theme={physical=true}, name="crit", points = 1, rarity = 10, level_range = {1, 50}, combat = { physcrit = resolvers.randartmax(1, 15), }, } newEntity{ theme={physical=true}, name="ammo reload", points = 1, rarity = 10, level_range = {1, 50}, wielder = { ammo_reload_speed = resolvers.randartmax(1, 4), }, } newEntity{ theme={physical=true}, name="travel speed", points = 1, rarity = 10, level_range = {1, 50}, combat = { travel_speed = resolvers.randartmax(1, 2), }, } ---------------------------------------------------------------- -- Melee damage projection ---------------------------------------------------------------- newEntity{ theme={physical=true}, name="physical ranged", points = 1, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.PHYSICAL] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={mind=true, mental=true}, name="mind ranged", points = 1, rarity = 24, level_range = {1, 50}, combat = { ranged_project = {[DamageType.MIND] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={acid=true}, name="acid ranged", points = 1, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ACID] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={lightning=true}, name="lightning ranged", points = 1, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.LIGHTNING] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={fire=true}, name="fire ranged", points = 1, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.FIRE] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={cold=true}, name="cold ranged", points = 1, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.COLD] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={light=true}, name="light ranged", points = 1, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.LIGHT] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={dark=true}, name="dark ranged", points = 1, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.DARKNESS] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={blight=true, spell=true}, name="blight ranged", points = 1, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.BLIGHT] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={nature=true}, name="nature ranged", points = 1, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.NATURE] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={arcane=true, spell=true}, name="arcane ranged", points = 2, rarity = 24, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ARCANE] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={temporal=true}, name="temporal ranged", points = 2, rarity = 24, level_range = {1, 50}, combat = { ranged_project = {[DamageType.TEMPORAL] = resolvers.randartmax(4, 40), }, }, } ---------------------------------------------------------------- --Ranged damage Projection (rare) ---------------------------------------------------------------- newEntity{ theme={blight=true}, name="corrupted blood melee", points = 2, rarity = 20, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ITEM_BLIGHT_DISEASE] = resolvers.randartmax(20, 40), }, }, } newEntity{ theme={temporal=true}, name="temporal energize melee", points = 2, rarity = 20, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ITEM_TEMPORAL_ENERGIZE] = resolvers.randartmax(20, 40), }, }, } newEntity{ theme={blight=true}, name="gloom mind melee", points = 2, rarity = 20, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ITEM_MIND_GLOOM] = resolvers.randartmax(20, 40), }, }, } newEntity{ theme={acid=true}, name="acid corrode melee", points = 2, rarity = 20, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ITEM_ACID_CORRODE] = resolvers.randartmax(20, 40), }, }, } newEntity{ theme={light=true}, name="light blind melee", points = 2, rarity = 20, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ITEM_LIGHT_BLIND] = resolvers.randartmax(20, 40), }, }, } newEntity{ theme={lightning=true}, name="lightning daze melee", points = 2, rarity = 20, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ITEM_LIGHTNING_DAZE] = resolvers.randartmax(20, 40), }, }, } newEntity{ theme={antimagic=true}, name="manaburn melee", points = 2, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ITEM_ANTIMAGIC_MANABURN] = resolvers.randartmax(20, 40), }, }, } newEntity{ theme={nature=true, antimagic=true}, name="slime melee", points = 2, rarity = 18, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ITEM_NATURE_SLOW] = resolvers.randartmax(20, 40), }, }, } newEntity{ theme={dark=true}, name="dark numbing melee", points = 2, rarity = 24, level_range = {1, 50}, combat = { ranged_project = {[DamageType.ITEM_DARKNESS_NUMBING] = resolvers.randartmax(20, 40), }, }, } ---------------------------------------------------------------- -- Melee damage burst ---------------------------------------------------------------- newEntity{ theme={physical=true}, name="physical burst", points = 2, rarity = 24, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.PHYSICAL] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={mind=true, mental=true}, name="mind burst", points = 2, rarity = 30, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.MIND] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={acid=true}, name="acid burst", points = 2, rarity = 24, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.ACID] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={lightning=true}, name="lightning burst", points = 2, rarity = 24, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.LIGHTNING] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={fire=true}, name="fire burst", points = 2, rarity = 24, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.FIRE] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={cold=true}, name="cold burst", points = 2, rarity = 24, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.COLD] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={light=true}, name="light burst", points = 2, rarity = 24, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.LIGHT] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={dark=true}, name="dark burst", points = 2, rarity = 24, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.DARKNESS] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={blight=true}, name="blight burst", points = 2, rarity = 24, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.BLIGHT] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={nature=true}, name="nature burst", points = 2, rarity = 24, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.NATURE] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={arcane=true}, name="arcane burst", points = 4, rarity = 30, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.ARCANE] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={temporal=true}, name="temporal burst", points = 4, rarity = 30, level_range = {1, 50}, combat = { burst_on_hit = {[DamageType.TEMPORAL] = resolvers.randartmax(4, 40), }, }, } ---------------------------------------------------------------- -- Melee damage burst(crit) ---------------------------------------------------------------- newEntity{ theme={physical=true}, name="physical burst (crit)", points = 3, rarity = 28, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.PHYSICAL] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={mind=true, mental=true}, name="mind burst (crit)", points = 3, rarity = 36, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.MIND] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={acid=true}, name="acid burst (crit)", points = 3, rarity = 28, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.ACID] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={lightning=true}, name="lightning burst (crit)", points = 3, rarity = 28, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.LIGHTNING] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={fire=true}, name="fire burst (crit)", points = 3, rarity = 28, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.FIRE] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={cold=true}, name="cold burst (crit)", points = 3, rarity = 28, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.COLD] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={light=true}, name="light burst (crit)", points = 3, rarity = 28, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.LIGHT] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={dark=true}, name="dark burst (crit)", points = 3, rarity = 28, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.DARKNESS] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={blight=true}, name="blight burst (crit)", points = 3, rarity = 28, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.BLIGHT] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={nature=true}, name="nature burst (crit)", points = 3, rarity = 28, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.NATURE] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={arcane=true}, name="arcane burst (crit)", points = 6, rarity = 36, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.ARCANE] = resolvers.randartmax(4, 40), }, }, } newEntity{ theme={temporal=true}, name="temporal burst (crit)", points = 6, rarity = 36, level_range = {1, 50}, combat = { burst_on_crit = {[DamageType.TEMPORAL] = resolvers.randartmax(4, 40), }, }, } ---------------------------------------------------------------- -- Melee damage conversion ---------------------------------------------------------------- -- Removed due to essentially being downsides more often than not, double dipping defenses and creating massive log spam ---------------------------------------------------------------- -- Slaying ---------------------------------------------------------------- --[[ newEntity{ theme={physical=true}, name="slay humanoid", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {humanoid=resolvers.randartmax(5, 25),},}, } newEntity{ theme={physical=true}, name="slay undead", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {undead=resolvers.randartmax(5, 25),},}, } newEntity{ theme={physical=true}, name="slay demon", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {demon=resolvers.randartmax(5, 25),},}, } newEntity{ theme={physical=true}, name="slay dragon", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {dragon=resolvers.randartmax(5, 25),},}, } newEntity{ theme={physical=true}, name="slay animal", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {animal=resolvers.randartmax(5, 25),},}, } newEntity{ theme={physical=true}, name="slay giant", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {giant=resolvers.randartmax(5, 25),},}, } newEntity{ theme={physical=true}, name="slay elemental", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {elemental=resolvers.randartmax(5, 25),},}, } newEntity{ theme={physical=true}, name="slay horror", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {horror=resolvers.randartmax(5, 25),},}, } newEntity{ theme={physical=true}, name="slay vermin", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {vermin=resolvers.randartmax(5, 25),},}, } newEntity{ theme={physical=true}, name="slay insect", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {insect=resolvers.randartmax(5, 25),},}, } newEntity{ theme={physical=true}, name="slay spiderkin", points = 1, rarity = 22, level_range = {1, 50}, combat = { inc_damage_type = {spiderkin=resolvers.randartmax(5, 25),},}, } --]]
gpl-3.0
hfjgjfg/eli25
plugins/channels.lua
356
1732
-- Checks if bot was disabled on specific chat local function is_channel_disabled( receiver ) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end local function enable_channel(receiver) if not _config.disabled_channels then _config.disabled_channels = {} end if _config.disabled_channels[receiver] == nil then return 'Channel isn\'t disabled' end _config.disabled_channels[receiver] = false save_config() return "Channel re-enabled" end local function disable_channel( receiver ) if not _config.disabled_channels then _config.disabled_channels = {} end _config.disabled_channels[receiver] = true save_config() return "Channel disabled" end local function pre_process(msg) local receiver = get_receiver(msg) -- If sender is moderator then re-enable the channel --if is_sudo(msg) then if is_momod(msg) then if msg.text == "!channel enable" then enable_channel(receiver) end end if is_channel_disabled(receiver) then msg.text = "" end return msg end local function run(msg, matches) local receiver = get_receiver(msg) -- Enable a channel if matches[1] == 'enable' then return enable_channel(receiver) end -- Disable a channel if matches[1] == 'disable' then return disable_channel(receiver) end end return { description = "Plugin to manage channels. Enable or disable channel.", usage = { "!channel enable: enable current channel", "!channel disable: disable current channel" }, patterns = { "^!channel? (enable)", "^!channel? (disable)" }, run = run, --privileged = true, moderated = true, pre_process = pre_process }
gpl-2.0
mysql/mysql-proxy
tests/unit/lua/proxy-parser.lua
4
1574
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2012, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --- -- test the proxy.auto-config module -- -- local tests = require("proxy.test") local command = require("proxy.commands") tests.ProxyBaseTest.setDefaultScope() -- file under test local tokenizer = require("proxy.tokenizer") local parser = require("proxy.parser") TestScript = tests.ProxyBaseTest:new() function TestScript:setUp() proxy.global.config.test = { } end function TestScript:testGetTables() local cmd = command.parse(string.char(proxy.COM_QUERY) .. "SELECT * FROM db.tbl") local tokens = tokenizer.tokenize(cmd.query); local tables = parser.get_tables(tokens) assertEquals(tables["db.tbl"], "read") -- and it is db.tbl end --- -- the test suite runner local suite = tests.Suite:new({ result = tests.Result:new()}) suite:run() suite.result:print() return suite:exit_code()
gpl-2.0
jsj2008/ValyriaTear
img/sprites/map/npcs/npc_girl01_idle.lua
4
1054
-- Sprite animation file descriptor -- This file will describe the frames used to load the sprite animations -- This files is following a special format compared to other animation scripts. local ANIM_SOUTH = vt_map.MapMode.ANIM_SOUTH; local ANIM_NORTH = vt_map.MapMode.ANIM_NORTH; local ANIM_WEST = vt_map.MapMode.ANIM_WEST; local ANIM_EAST = vt_map.MapMode.ANIM_EAST; sprite_animation = { -- The file to load the frames from image_filename = "img/sprites/map/npcs/npc_girl01_spritesheet.png", -- The number of rows and columns of images, will be used to compute -- the images width and height, and also the frames number (row x col) rows = 4, columns = 6, -- The frames duration in milliseconds frames = { [ANIM_SOUTH] = { [0] = { id = 0, duration = 150 } }, [ANIM_NORTH] = { [0] = { id = 6, duration = 150 } }, [ANIM_WEST] = { [0] = { id = 12, duration = 150 } }, [ANIM_EAST] = { [0] = { id = 18, duration = 150 } } } }
gpl-2.0
TerminalShell/zombiesurvival
entities/weapons/weapon_zs_resupply/shared.lua
1
1169
SWEP.ViewModel = "models/weapons/v_pistol.mdl" SWEP.WorldModel = Model("models/Items/ammocrate_ar2.mdl") SWEP.AmmoIfHas = true SWEP.Primary.ClipSize = 1 SWEP.Primary.DefaultClip = 1 SWEP.Primary.Ammo = "helicoptergun" SWEP.Primary.Delay = 1 SWEP.Primary.Automatic = true SWEP.Secondary.ClipSize = -1 SWEP.Secondary.DefaultClip = -1 SWEP.Secondary.Automatic = false SWEP.Secondary.Ammo = "none" SWEP.WalkSpeed = 200 SWEP.FullWalkSpeed = 180 function SWEP:Initialize() self:SetWeaponHoldType("fist") self:SetDeploySpeed(1.1) self:HideViewAndWorldModel() end function SWEP:SetReplicatedAmmo(count) self:SetDTInt(0, count) end function SWEP:GetReplicatedAmmo() return self:GetDTInt(0) end function SWEP:GetWalkSpeed() if self:GetPrimaryAmmoCount() > 0 then return self.FullWalkSpeed end end function SWEP:SecondaryAttack() end function SWEP:Reload() end function SWEP:CanPrimaryAttack() if self.Owner:IsHolding() or self.Owner:GetBarricadeGhosting() then return false end if self:GetPrimaryAmmoCount() <= 0 then self:SetNextPrimaryFire(CurTime() + self.Primary.Delay) return false end return true end function SWEP:Holster() return true end
gpl-3.0
tarantool/luarocks
src/luarocks/loader.lua
1
9654
--- A module which installs a Lua package loader that is LuaRocks-aware. -- This loader uses dependency information from the LuaRocks tree to load -- correct versions of modules. It does this by constructing a "context" -- table in the environment, which records which versions of packages were -- used to load previous modules, so that the loader chooses versions -- that are declared to be compatible with the ones loaded earlier. local loaders = package.loaders or package.searchers local require, ipairs, table, type, next, tostring, error = require, ipairs, table, type, next, tostring, error local unpack = unpack or table.unpack local loader = {} local is_clean = not package.loaded["luarocks.core.cfg"] -- This loader module depends only on core modules. local cfg = require("luarocks.core.cfg") local cfg_ok, err = cfg.init() if cfg_ok then cfg.init_package_paths() end local path = require("luarocks.core.path") local manif = require("luarocks.core.manif") local vers = require("luarocks.core.vers") local util = require("luarocks.core.util") local require = nil -------------------------------------------------------------------------------- local temporary_global = false loader.context = {} -- Contains a table when rocks trees are loaded, -- or 'false' to indicate rocks trees failed to load. -- 'nil' indicates rocks trees were not attempted to be loaded yet. loader.rocks_trees = nil function loader.load_rocks_trees() local any_ok = false local trees = {} for _, tree in ipairs(cfg.rocks_trees or {}) do local manifest, err = manif.fast_load_local_manifest(path.rocks_dir(tree)) if manifest then any_ok = true table.insert(trees, {tree=tree, manifest=manifest}) end end if not any_ok then loader.rocks_trees = false return false end loader.rocks_trees = trees return true end --- Process the dependencies of a package to determine its dependency -- chain for loading modules. -- @param name string: The name of an installed rock. -- @param version string: The version of the rock, in string format function loader.add_context(name, version) -- assert(type(name) == "string") -- assert(type(version) == "string") if temporary_global then -- The first thing a wrapper does is to call add_context. -- From here on, it's safe to clean the global environment. luarocks = nil temporary_global = false end if loader.context[name] then return end loader.context[name] = version if not loader.rocks_trees and not loader.load_rocks_trees() then return nil end for _, tree in ipairs(loader.rocks_trees) do local manifest = tree.manifest local pkgdeps if manifest.dependencies and manifest.dependencies[name] then pkgdeps = manifest.dependencies[name][version] end if not pkgdeps then return nil end for _, dep in ipairs(pkgdeps) do local pkg, constraints = dep.name, dep.constraints for _, tree in ipairs(loader.rocks_trees) do local entries = tree.manifest.repository[pkg] if entries then for ver, pkgs in util.sortedpairs(entries, vers.compare_versions) do if (not constraints) or vers.match_constraints(vers.parse_version(ver), constraints) then loader.add_context(pkg, version) end end end end end end end --- Internal sorting function. -- @param a table: A provider table. -- @param b table: Another provider table. -- @return boolean: True if the version of a is greater than that of b. local function sort_versions(a,b) return a.version > b.version end --- Request module to be loaded through other loaders, -- once the proper name of the module has been determined. -- For example, in case the module "socket.core" has been requested -- to the LuaRocks loader and it determined based on context that -- the version 2.0.2 needs to be loaded and it is not the current -- version, the module requested for the other loaders will be -- "socket.core_2_0_2". -- @param module The module name requested by the user, such as "socket.core" -- @param name The rock name, such as "luasocket" -- @param version The rock version, such as "2.0.2-1" -- @param module_name The actual module name, such as "socket.core" or "socket.core_2_0_2". -- @return table or (nil, string): The module table as returned by some other loader, -- or nil followed by an error message if no other loader managed to load the module. local function call_other_loaders(module, name, version, module_name) for _, a_loader in ipairs(loaders) do if a_loader ~= loader.luarocks_loader then local results = { a_loader(module_name) } if type(results[1]) == "function" then return unpack(results) end end end return "Failed loading module "..module.." in LuaRocks rock "..name.." "..version end local function add_providers(providers, entries, tree, module, filter_file_name) for i, entry in ipairs(entries) do local name, version = entry:match("^([^/]*)/(.*)$") local file_name = tree.manifest.repository[name][version][1].modules[module] if type(file_name) ~= "string" then error("Invalid data in manifest file for module "..tostring(module).." (invalid data for "..tostring(name).." "..tostring(version)..")") end file_name = filter_file_name(file_name, name, version, tree.tree, i) if loader.context[name] == version then return name, version, file_name end version = vers.parse_version(version) table.insert(providers, {name = name, version = version, module_name = file_name, tree = tree}) end end --- Search for a module in the rocks trees -- @param module string: module name (eg. "socket.core") -- @param filter_file_name function(string, string, string, string, number): -- a function that takes the module file name (eg "socket/core.so"), the rock name -- (eg "luasocket"), the version (eg "2.0.2-1"), the path of the rocks tree -- (eg "/usr/local"), and the numeric index of the matching entry, so the -- filter function can know if the matching module was the first entry or not. -- @return string, string, string, (string or table): -- * name of the rock containing the module (eg. "luasocket") -- * version of the rock (eg. "2.0.2-1") -- * return value of filter_file_name -- * tree of the module (string or table in `rocks_trees` format) local function select_module(module, filter_file_name) --assert(type(module) == "string") --assert(type(filter_module_name) == "function") if not loader.rocks_trees and not loader.load_rocks_trees() then return nil end local providers = {} local initmodule for _, tree in ipairs(loader.rocks_trees) do local entries = tree.manifest.modules[module] if entries then add_providers(providers, entries, tree, module, filter_file_name) else initmodule = initmodule or module .. ".init" entries = tree.manifest.modules[initmodule] if entries then add_providers(providers, entries, tree, initmodule, filter_file_name) end end end if next(providers) then table.sort(providers, sort_versions) local first = providers[1] return first.name, first.version.string, first.module_name, first.tree end end --- Search for a module -- @param module string: module name (eg. "socket.core") -- @return string, string, string, (string or table): -- * name of the rock containing the module (eg. "luasocket") -- * version of the rock (eg. "2.0.2-1") -- * name of the module (eg. "socket.core", or "socket.core_2_0_2" if file is stored versioned). -- * tree of the module (string or table in `rocks_trees` format) local function pick_module(module) return select_module(module, function(file_name, name, version, tree, i) if i > 1 then file_name = path.versioned_name(file_name, "", name, version) end return path.path_to_module(file_name) end) end --- Return the pathname of the file that would be loaded for a module. -- @param module string: module name (eg. "socket.core") -- @return filename of the module (eg. "/usr/local/lib/lua/5.1/socket/core.so"), -- the rock name and the rock version. function loader.which(module) local rock_name, rock_version, file_name = select_module(module, path.which_i) return file_name, rock_name, rock_version end --- Package loader for LuaRocks support. -- A module is searched in installed rocks that match the -- current LuaRocks context. If module is not part of the -- context, or if a context has not yet been set, the module -- in the package with the highest version is used. -- @param module string: The module name, like in plain require(). -- @return table: The module table (typically), like in plain -- require(). See <a href="http://www.lua.org/manual/5.1/manual.html#pdf-require">require()</a> -- in the Lua reference manual for details. function loader.luarocks_loader(module) local name, version, module_name = pick_module(module) if not name then return "No LuaRocks module found for "..module else loader.add_context(name, version) return call_other_loaders(module, name, version, module_name) end end table.insert(loaders, 1, loader.luarocks_loader) if is_clean then for modname, _ in pairs(package.loaded) do if modname:match("^luarocks%.") then package.loaded[modname] = nil end end end return loader
mit
TeamHypersomnia/Hypersomnia
hypersomnia/content/gfx/metropolis_torso_heavy_gtm_6.meta.lua
2
2836
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.43000000715255737, amplification = 140, light_colors = { "89 31 168 255", "48 42 88 255", "61 16 123 0" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = -6, y = -11 }, rotation = 46.468799591064453 }, head = { pos = { x = 2, y = -2 }, rotation = 26.565052032470703 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 10, y = 27 }, rotation = -33.690067291259766 }, secondary_hand = { pos = { x = 36, y = 10 }, rotation = 90 }, secondary_shoulder = { pos = { x = -1, y = 18 }, rotation = -167 }, shoulder = { pos = { x = 20, y = -11 }, rotation = -122 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
Laterus/Darkstar-Linux-Fork
scripts/globals/items/icefish.lua
1
1180
----------------------------------------- -- ID: 4470 -- Item: icefish -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 3 -- Mind -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:getRace() ~= 7) then result = 247; elseif (target:hasStatusEffect(EFFECT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,0,4470); 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
jsj2008/ValyriaTear
dat/maps/layna_village/layna_village_kalya_house_path_small_house_script.lua
4
4060
-- Set the namespace according to the map name. local ns = {}; setmetatable(ns, {__index = _G}); layna_village_kalya_house_path_small_house_script = ns; setfenv(1, ns); -- The map name, subname and location image map_name = "Mountain Village of Layna" map_image_filename = "img/menus/locations/mountain_village.png" map_subname = "" -- The music file used as default background music on this map. -- Other musics will have to handled through scripting. music_filename = "mus/Caketown_1-OGA-mat-pablo.ogg" -- c++ objects instances local Map = {}; local ObjectManager = {}; local DialogueManager = {}; local EventManager = {}; -- the main character handler local bronann = {}; -- the main map loading code function Load(m) Map = m; ObjectManager = Map.object_supervisor; DialogueManager = Map.dialogue_supervisor; EventManager = Map.event_supervisor; Map.unlimited_stamina = true; _CreateCharacters(); _CreateObjects(); -- Set the camera focus on bronann Map:SetCamera(bronann); _CreateEvents(); _CreateZones(); -- The entrance sound AudioManager:PlaySound("snd/door_close.wav"); end -- the map update function handles checks done on each game tick. function Update() -- Check whether the character is in one of the zones _CheckZones(); end -- Character creation function _CreateCharacters() bronann = CreateSprite(Map, "Bronann", 28, 15); bronann:SetDirection(vt_map.MapMode.SOUTH); bronann:SetMovementSpeed(vt_map.MapMode.NORMAL_SPEED); Map:AddGroundObject(bronann); end function _CreateObjects() object = {} -- Bronann's room object = CreateObject(Map, "Bed1", 34, 28); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Box1", 21, 22); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Chair1_inverted", 31, 19); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Small Wooden Table", 34, 20); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Left Window Light", 21, 21); object:SetCollisionMask(vt_map.MapMode.NO_COLLISION); object:SetDrawOnSecondPass(true); -- Above any other ground object if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Flower Pot1", 21, 26); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Flower Pot2", 21, 24); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Right Window Light", 35, 21); object:SetDrawOnSecondPass(true); -- Above any other ground object object:SetCollisionMask(vt_map.MapMode.NO_COLLISION); if (object ~= nil) then Map:AddGroundObject(object) end; object = CreateObject(Map, "Flower Pot1", 35, 22); if (object ~= nil) then Map:AddGroundObject(object) end; end -- Creates all events and sets up the entire event sequence chain function _CreateEvents() local event = {}; local dialogue = {}; local text = {}; -- Triggered events event = vt_map.MapTransitionEvent("exit floor", "dat/maps/layna_village/layna_village_kalya_house_path_map.lua", "dat/maps/layna_village/layna_village_kalya_house_path_script.lua", "from grandma house"); EventManager:RegisterEvent(event); end -- zones local room_exit_zone = {}; -- Create the different map zones triggering events function _CreateZones() -- N.B.: left, right, top, bottom room_exit_zone = vt_map.CameraZone(26, 30, 12, 13); Map:AddZone(room_exit_zone); end -- Check whether the active camera has entered a zone. To be called within Update() function _CheckZones() if (room_exit_zone:IsCameraEntering() == true) then bronann:SetMoving(false); EventManager:StartEvent("exit floor"); AudioManager:PlaySound("snd/door_open2.wav"); end end -- Map Custom functions -- Used through scripted events map_functions = { }
gpl-2.0
RyMarq/Zero-K
effects/shellshocker.lua
25
3144
-- shellshockflash -- shellshockgound -- shellshockshells return { ["shellshockflash"] = { muzzleflash = { air = true, class = [[CSimpleParticleSystem]], count = 3, ground = true, water = true, properties = { airdrag = 1, colormap = [[1 1 1 1 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 0, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 5, particlelifespread = 0, particlesize = 0.1, particlesizespread = 3, particlespeed = [[0.01 i7]], particlespeedspread = 1, pos = [[0, 1, 0]], sizegrowth = [[3 i3]], sizemod = 1.0, texture = [[kfoam]], }, }, muzzlesmoke = { air = true, class = [[CSimpleParticleSystem]], count = 10, ground = true, water = true, properties = { airdrag = 0.8, colormap = [[1 0.6 0 1 0.4 0.4 0.4 1 0.05 0.05 0.05 0.1]], directional = true, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, 0, 0]], numparticles = 1, particlelife = 50, particlelifespread = 0, particlesize = [[15 i-0.9]], particlesizespread = 1, particlespeed = [[10 i-1]], particlespeedspread = 1, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[orangesmoke2]], }, }, }, ["shellshockgound"] = { groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 60, ttl = 8, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, }, ["shellshockshells"] = { shells = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 1 1 1 1 1]], directional = true, emitrot = 0, emitrotspread = 10, emitvector = [[dir]], gravity = [[0, -0.5, 0]], numparticles = 1, particlelife = 25, particlelifespread = 0, particlesize = 5, particlesizespread = 0, particlespeed = 6, particlespeedspread = 0, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[shell]], }, }, }, }
gpl-2.0
BinChengfei/openwrt-3.10.14
package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/model/cbi/luci_statistics/unixsock.lua
80
1455
--[[ Luci configuration model for statistics - collectd unixsock 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("Unixsock Plugin Configuration"), translate( "The unixsock plugin creates a unix socket which can be used " .. "to read collected data from a running collectd instance." )) -- collectd_unixsock config section s = m:section( NamedSection, "collectd_unixsock", "luci_statistics" ) -- collectd_unixsock.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_unixsock.socketfile (SocketFile) socketfile = s:option( Value, "SocketFile" ) socketfile.default = "/var/run/collect-query.socket" socketfile:depends( "enable", 1 ) -- collectd_unixsock.socketgroup (SocketGroup) socketgroup = s:option( Value, "SocketGroup" ) socketgroup.default = "nobody" socketgroup.rmempty = true socketgroup.optional = true socketgroup:depends( "enable", 1 ) -- collectd_unixsock.socketperms (SocketPerms) socketperms = s:option( Value, "SocketPerms" ) socketperms.default = "0770" socketperms.rmempty = true socketperms.optional = true socketperms:depends( "enable", 1 ) return m
gpl-2.0
llX8Xll/DEVKEEPER1
plugins/stats.lua
3
4650
--[[ _____ _ _ _ _____ Dev @lIMyIl |_ _|__| |__ / \ | | _| ____| Dev @li_XxX_il | |/ __| '_ \ / _ \ | |/ / _| Dev @h_k_a | |\__ \ | | |/ ___ \| <| |___ Dev @Aram_omar22 |_||___/_| |_/_/ \_\_|\_\_____| Dev @IXX_I_XXI CH > @lTSHAKEl_CH --]] do -- Returns a table with `name` and `msgs` 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_stats(receiver, chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' 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 text = 'Users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' 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 text = 'Users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'th3boss' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /teleseed ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' or msg.to.type == 'channel' then local receiver = get_receiver(msg) local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(receiver, chat_id) else return end end if matches[2] == "th3boss" then -- Put everything you like :) if not is_admin1(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin1(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[#!/]([Ss]tats)$", "^[#!/]([Ss]tatslist)$", "^[#!/]([Ss]tats) (group) (%d+)", "^[#!/]([Ss]tats) (th3boss)", "^[#!/]([Tt]h3boss)" }, run = run } end --[[ _____ _ _ _ _____ Dev @lIMyIl |_ _|__| |__ / \ | | _| ____| Dev @li_XxX_il | |/ __| '_ \ / _ \ | |/ / _| Dev @h_k_a | |\__ \ | | |/ ___ \| <| |___ Dev @Aram_omar22 |_||___/_| |_/_/ \_\_|\_\_____| Dev @IXX_I_XXI CH > @lTSHAKEl_CH --]]
gpl-2.0
Ferk/Dungeontest
mods/default/nodes.lua
1
40285
-- mods/default/nodes.lua --[[ Node name convention: Although many node names are in combined-word form, the required form for new node names is words separated by underscores. If both forms are used in written language (for example pinewood and pine wood) the underscore form should be used. --]] --[[ Index: Stone ----- (1. Material 2. Cobble variant 3. Brick variant [4. Modified forms]) default:stone default:cobble default:stonebrick default:mossycobble default:desert_stone default:desert_cobble default:desert_stonebrick default:sandstone default:sandstonebrick default:obsidian default:obsidianbrick Soft / Non-Stone ---------------- (1. Material [2. Modified forms]) default:dirt default:dirt_with_grass default:dirt_with_grass_footsteps default:dirt_with_dry_grass default:dirt_with_snow default:sand default:desert_sand default:gravel default:clay default:snow default:snowblock default:ice Trees ----- (1. Trunk 2. Fabricated trunk 3. Leaves 4. Sapling [5. Fruits]) default:tree default:wood default:leaves default:sapling default:apple default:jungletree default:junglewood default:jungleleaves default:junglesapling default:pine_tree default:pine_wood default:pine_needles default:pine_sapling default:acacia_tree default:acacia_wood default:acacia_leaves default:acacia_sapling Ores ---- (1. In stone 2. Block) default:stone_with_coal default:coalblock default:stone_with_iron default:steelblock default:stone_with_copper default:copperblock default:bronzeblock default:stone_with_gold default:goldblock default:stone_with_mese default:mese default:stone_with_diamond default:diamondblock Plantlife (non-cubic) --------------------- default:cactus default:papyrus default:dry_shrub default:junglegrass default:grass_1 default:grass_2 default:grass_3 default:grass_4 default:grass_5 default:dry_grass_1 default:dry_grass_2 default:dry_grass_3 default:dry_grass_4 default:dry_grass_5 Liquids ------- (1. Source 2. Flowing) default:water_source default:water_flowing default:river_water_source default:river_water_flowing default:lava_source default:lava_flowing Tools / "Advanced" crafting / Non-"natural" ------------------------------------------- default:torch default:bookshelf default:sign_wall default:ladder default:fence_wood default:glass default:obsidian_glass default:rail default:brick default:meselamp Misc ---- default:cloud --]] -- -- Stone -- minetest.register_node("default:stone", { description = "Stone", tiles = {"default_stone.png"}, groups = {cracky=3, stone=1}, drop = 'default:cobble', drops = "", legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:cobble", { description = "Cobblestone", tiles = {"default_cobble.png"}, is_ground_content = false, drops = "", groups = {cracky=3, stone=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stonebrick", { description = "Stone Brick", tiles = {"default_stone_brick.png"}, is_ground_content = false, drops = "", groups = {cracky=2, stone=1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:mossycobble", { description = "Mossy Cobblestone", tiles = {"default_mossycobble.png"}, is_ground_content = false, drops = "", groups = {cracky=3, stone=1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_stone", { description = "Desert Stone", tiles = {"default_desert_stone.png"}, groups = {cracky=3, stone=1}, drops = "", drop = 'default:desert_cobble', legacy_mineral = true, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_cobble", { description = "Desert Cobblestone", tiles = {"default_desert_cobble.png"}, drops = "", is_ground_content = false, groups = {cracky=3, stone=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:desert_stonebrick", { description = "Desert Stone Brick", tiles = {"default_desert_stone_brick.png"}, drops = "", is_ground_content = false, groups = {cracky=2, stone=1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:sandstone", { description = "Sandstone", tiles = {"default_sandstone.png"}, drops = "", groups = {crumbly=2,cracky=3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:sandstonebrick", { description = "Sandstone Brick", tiles = {"default_sandstone_brick.png"}, drops = "", is_ground_content = false, groups = {cracky=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:obsidian", { description = "Obsidian", tiles = {"default_obsidian.png"}, drops = "", sounds = default.node_sound_stone_defaults(), groups = {cracky=1,level=2}, }) minetest.register_node("default:obsidianbrick", { description = "Obsidian Brick", tiles = {"default_obsidian_brick.png"}, drops = "", is_ground_content = false, sounds = default.node_sound_stone_defaults(), groups = {cracky=1,level=2}, }) -- -- Soft / Non-Stone -- minetest.register_node("default:dirt", { description = "Dirt", tiles = {"default_dirt.png"}, drops = "", groups = {crumbly=3,soil=1}, sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("default:dirt_with_grass", { description = "Dirt with Grass", tiles = {"default_grass.png", "default_dirt.png", {name = "default_dirt.png^default_grass_side.png", tileable_vertical = false}}, groups = {crumbly=3,soil=1}, drops = "", sounds = default.node_sound_dirt_defaults({ footstep = {name="default_grass_footstep", gain=0.25}, }), }) minetest.register_node("default:dirt_with_grass_footsteps", { description = "Dirt with Grass and Footsteps", tiles = {"default_grass.png^default_footprint.png", "default_dirt.png", {name = "default_dirt.png^default_grass_side.png", tileable_vertical = false}}, groups = {crumbly=3,soil=1,not_in_creative_inventory=1}, drops = "", sounds = default.node_sound_dirt_defaults({ footstep = {name="default_grass_footstep", gain=0.25}, }), }) minetest.register_node("default:dirt_with_dry_grass", { description = "Dirt with Dry Grass", tiles = {"default_dry_grass.png", "default_dirt.png", {name = "default_dirt.png^default_dry_grass_side.png", tileable_vertical = false}}, groups = {crumbly = 3, soil = 1}, drops = "", sounds = default.node_sound_dirt_defaults({ footstep = {name = "default_grass_footstep", gain = 0.4}, }), }) minetest.register_node("default:dirt_with_snow", { description = "Dirt with Snow", tiles = {"default_snow.png", "default_dirt.png", {name = "default_dirt.png^default_snow_side.png", tileable_vertical = false}}, groups = {crumbly=3,soil=1}, drops = "", sounds = default.node_sound_dirt_defaults({ footstep = {name="default_snow_footstep", gain=0.25}, }), }) minetest.register_node("default:sand", { description = "Sand", drops = "", tiles = {"default_sand.png"}, groups = {crumbly=3, falling_node=1, sand=1}, sounds = default.node_sound_sand_defaults(), }) minetest.register_node("default:desert_sand", { description = "Desert Sand", tiles = {"default_desert_sand.png"}, groups = {crumbly=3, falling_node=1, sand=1}, sounds = default.node_sound_sand_defaults(), }) minetest.register_node("default:gravel", { description = "Gravel", drops = "", tiles = {"default_gravel.png"}, groups = {crumbly=2, falling_node=1}, sounds = default.node_sound_dirt_defaults({ footstep = {name="default_gravel_footstep", gain=0.5}, dug = {name="default_gravel_footstep", gain=1.0}, }), }) minetest.register_node("default:clay", { description = "Clay", tiles = {"default_clay.png"}, groups = {crumbly=3}, drop = 'default:clay_lump 4', sounds = default.node_sound_dirt_defaults(), }) minetest.register_node("default:snow", { description = "Snow", tiles = {"default_snow.png"}, inventory_image = "default_snowball.png", wield_image = "default_snowball.png", paramtype = "light", buildable_to = true, drawtype = "nodebox", node_box = { type = "fixed", fixed = { {-0.5, -0.5, -0.5, 0.5, -0.25, 0.5}, }, }, groups = {crumbly = 3, falling_node = 1}, sounds = default.node_sound_dirt_defaults({ footstep = {name = "default_snow_footstep", gain = 0.25}, dug = {name = "default_snow_footstep", gain = 0.75}, }), on_construct = function(pos) pos.y = pos.y - 1 if minetest.get_node(pos).name == "default:dirt_with_grass" then minetest.set_node(pos, {name = "default:dirt_with_snow"}) end end, }) minetest.register_node("default:snowblock", { description = "Snow Block", tiles = {"default_snow.png"}, groups = {crumbly=3}, sounds = default.node_sound_dirt_defaults({ footstep = {name="default_snow_footstep", gain=0.25}, dug = {name="default_snow_footstep", gain=0.75}, }), drops = "", }) minetest.register_node("default:ice", { description = "Ice", tiles = {"default_ice.png"}, is_ground_content = false, drops = "", paramtype = "light", groups = {cracky=3}, sounds = default.node_sound_glass_defaults(), }) -- -- Trees -- minetest.register_node("default:tree", { description = "Tree", tiles = {"default_tree_top.png", "default_tree_top.png", "default_tree.png"}, paramtype2 = "facedir", is_ground_content = false, drops = "", groups = {tree=1,choppy=2,flammable=2}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:wood", { description = "Wooden Planks", tiles = {"default_wood.png"}, is_ground_content = false, drops = "", groups = {choppy=2,flammable=3,wood=1}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:sapling", { description = "Sapling", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_sapling.png"}, inventory_image = "default_sapling.png", wield_image = "default_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.35, 0.3} }, groups = {snappy=2,dig_immediate=3,flammable=2,attached_node=1,sapling=1}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:leaves", { description = "Leaves", drawtype = "allfaces_optional", waving = 1, visual_scale = 1.3, tiles = {"default_leaves.png"}, special_tiles = {"default_leaves_simple.png"}, paramtype = "light", drops = "", is_ground_content = false, groups = {snappy=3, leafdecay=3, flammable=2, leaves=1}, drop = { max_items = 1, items = { { -- player will get sapling with 1/20 chance items = {'default:sapling'}, rarity = 20, }, { -- player will get leaves only if he get no saplings, -- this is because max_items is 1 items = {'default:leaves'}, } } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:apple", { description = "Apple", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_apple.png"}, inventory_image = "default_apple.png", paramtype = "light", sunlight_propagates = true, walkable = false, is_ground_content = false, selection_box = { type = "fixed", fixed = {-0.2, -0.5, -0.2, 0.2, 0, 0.2} }, groups = {fleshy=3,dig_immediate=3,flammable=2,leafdecay=3,leafdecay_drop=1}, on_use = minetest.item_eat(2), sounds = default.node_sound_leaves_defaults(), after_place_node = function(pos, placer, itemstack) if placer:is_player() then minetest.set_node(pos, {name="default:apple", param2=1}) end end, }) minetest.register_node("default:jungletree", { description = "Jungle Tree", tiles = {"default_jungletree_top.png", "default_jungletree_top.png", "default_jungletree.png"}, paramtype2 = "facedir", is_ground_content = false, drops = "", groups = {tree=1,choppy=2,flammable=2}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:junglewood", { description = "Junglewood Planks", tiles = {"default_junglewood.png"}, is_ground_content = false, drops = "", groups = {choppy=2,flammable=3,wood=1}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:jungleleaves", { description = "Jungle Leaves", drawtype = "allfaces_optional", waving = 1, visual_scale = 1.3, tiles = {"default_jungleleaves.png"}, special_tiles = {"default_jungleleaves_simple.png"}, paramtype = "light", drops = "", is_ground_content = false, groups = {snappy=3, leafdecay=3, flammable=2, leaves=1}, drop = { max_items = 1, items = { { -- player will get sapling with 1/20 chance items = {'default:junglesapling'}, rarity = 20, }, } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:junglesapling", { description = "Jungle Sapling", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_junglesapling.png"}, inventory_image = "default_junglesapling.png", wield_image = "default_junglesapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.35, 0.3} }, groups = {snappy=2,dig_immediate=3,flammable=2,attached_node=1,sapling=1}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:pine_tree", { description = "Pine Tree", tiles = {"default_pine_tree_top.png", "default_pine_tree_top.png", "default_pine_tree.png"}, paramtype2 = "facedir", is_ground_content = false, drops = "", groups = {tree = 1, choppy = 2, flammable = 2}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node }) minetest.register_node("default:pine_wood", { description = "Pine Wood Planks", tiles = {"default_pine_wood.png"}, is_ground_content = false, drops = "", groups = {choppy = 2, flammable = 3, wood = 1}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:pine_needles",{ description = "Pine Needles", drawtype = "allfaces_optional", visual_scale = 1.3, tiles = {"default_pine_needles.png"}, waving = 1, paramtype = "light", is_ground_content = false, groups = {snappy = 3, leafdecay = 3, flammable = 2, leaves = 1}, drop = { max_items = 1, items = { {items = {"default:pine_sapling"}, rarity = 20}, } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:pine_sapling", { description = "Pine Sapling", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_pine_sapling.png"}, inventory_image = "default_pine_sapling.png", wield_image = "default_pine_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.35, 0.3} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), }) minetest.register_node("default:acacia_tree", { description = "Acacia Tree", tiles = {"default_acacia_tree_top.png", "default_acacia_tree_top.png", "default_acacia_tree.png"}, paramtype2 = "facedir", is_ground_content = false, groups = {tree = 1, choppy = 2, flammable = 2}, sounds = default.node_sound_wood_defaults(), drops = "", on_place = minetest.rotate_node }) minetest.register_node("default:acacia_wood", { description = "Acacia Wood Planks", tiles = {"default_acacia_wood.png"}, is_ground_content = false, groups = {choppy = 2, flammable = 3, wood = 1}, sounds = default.node_sound_wood_defaults(), drops = "", }) minetest.register_node("default:acacia_leaves", { description = "Acacia Leaves", drawtype = "allfaces_optional", visual_scale = 1.3, tiles = {"default_acacia_leaves.png"}, paramtype = "light", is_ground_content = false, groups = {snappy = 3, leafdecay = 3, flammable = 2, leaves = 1}, drop = { max_items = 1, items = { {items = {"default:acacia_sapling"}, rarity = 20}, } }, sounds = default.node_sound_leaves_defaults(), after_place_node = default.after_place_leaves, }) minetest.register_node("default:acacia_sapling", { description = "Acacia Tree Sapling", drawtype = "plantlike", visual_scale = 1.0, tiles = {"default_acacia_sapling.png"}, inventory_image = "default_acacia_sapling.png", wield_image = "default_acacia_sapling.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.35, 0.3} }, groups = {snappy = 2, dig_immediate = 3, flammable = 2, attached_node = 1, sapling = 1}, sounds = default.node_sound_leaves_defaults(), }) -- -- Ores -- minetest.register_node("default:stone_with_coal", { description = "Coal Ore", tiles = {"default_stone.png^default_mineral_coal.png"}, groups = {cracky=3}, drop = 'default:coal_lump', sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:coalblock", { description = "Coal Block", tiles = {"default_coal_block.png"}, is_ground_content = false, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stone_with_iron", { description = "Iron Ore", tiles = {"default_stone.png^default_mineral_iron.png"}, groups = {cracky=2}, drop = 'default:iron_lump', sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:steelblock", { description = "Steel Block", tiles = {"default_steel_block.png"}, is_ground_content = false, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stone_with_copper", { description = "Copper Ore", tiles = {"default_stone.png^default_mineral_copper.png"}, groups = {cracky=2}, drop = 'default:copper_lump', sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:copperblock", { description = "Copper Block", tiles = {"default_copper_block.png"}, is_ground_content = false, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:bronzeblock", { description = "Bronze Block", tiles = {"default_bronze_block.png"}, is_ground_content = false, groups = {cracky=1,level=2}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stone_with_mese", { description = "Mese Ore", tiles = {"default_stone.png^default_mineral_mese.png"}, paramtype = "light", groups = {cracky = 1}, drop = "default:mese_crystal", sounds = default.node_sound_stone_defaults(), light_source = 1, }) minetest.register_node("default:mese", { description = "Mese Block", tiles = {"default_mese_block.png"}, paramtype = "light", groups = {cracky = 1, level = 2}, sounds = default.node_sound_stone_defaults(), light_source = 3, }) minetest.register_node("default:stone_with_gold", { description = "Gold Ore", tiles = {"default_stone.png^default_mineral_gold.png"}, groups = {cracky=2}, drop = "default:gold_lump", sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:goldblock", { description = "Gold Block", tiles = {"default_gold_block.png"}, is_ground_content = false, groups = {cracky=1}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:stone_with_diamond", { description = "Diamond Ore", tiles = {"default_stone.png^default_mineral_diamond.png"}, groups = {cracky=1}, drop = "default:diamond", sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:diamondblock", { description = "Diamond Block", tiles = {"default_diamond_block.png"}, is_ground_content = false, groups = {cracky=1,level=3}, sounds = default.node_sound_stone_defaults(), }) -- -- Plantlife (non-cubic) -- minetest.register_node("default:cactus", { description = "Cactus", tiles = {"default_cactus_top.png", "default_cactus_top.png", "default_cactus_side.png"}, paramtype2 = "facedir", groups = {snappy=1,choppy=3,flammable=2}, sounds = default.node_sound_wood_defaults(), on_place = minetest.rotate_node, after_dig_node = function(pos, node, metadata, digger) default.dig_up(pos, node, digger) end, }) minetest.register_node("default:papyrus", { description = "Papyrus", drawtype = "plantlike", tiles = {"default_papyrus.png"}, inventory_image = "default_papyrus.png", wield_image = "default_papyrus.png", paramtype = "light", sunlight_propagates = true, walkable = false, selection_box = { type = "fixed", fixed = {-0.3, -0.5, -0.3, 0.3, 0.5, 0.3} }, groups = {snappy=3,flammable=2}, sounds = default.node_sound_leaves_defaults(), after_dig_node = function(pos, node, metadata, digger) default.dig_up(pos, node, digger) end, }) minetest.register_node("default:dry_shrub", { description = "Dry Shrub", drawtype = "plantlike", waving = 1, visual_scale = 1.0, tiles = {"default_dry_shrub.png"}, inventory_image = "default_dry_shrub.png", wield_image = "default_dry_shrub.png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy=3,flammable=3,attached_node=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, }) minetest.register_node("default:junglegrass", { description = "Jungle Grass", drawtype = "plantlike", waving = 1, visual_scale = 1.3, tiles = {"default_junglegrass.png"}, inventory_image = "default_junglegrass.png", wield_image = "default_junglegrass.png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy=3,flammable=2,flora=1,attached_node=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, }) minetest.register_node("default:grass_1", { description = "Grass", drawtype = "plantlike", waving = 1, tiles = {"default_grass_1.png"}, -- Use texture of a taller grass stage in inventory inventory_image = "default_grass_3.png", wield_image = "default_grass_3.png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy=3,flammable=3,flora=1,attached_node=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, on_place = function(itemstack, placer, pointed_thing) -- place a random grass node local stack = ItemStack("default:grass_"..math.random(1,5)) local ret = minetest.item_place(stack, placer, pointed_thing) return ItemStack("default:grass_1 "..itemstack:get_count()-(1-ret:get_count())) end, }) for i=2,5 do minetest.register_node("default:grass_"..i, { description = "Grass", drawtype = "plantlike", waving = 1, tiles = {"default_grass_"..i..".png"}, inventory_image = "default_grass_"..i..".png", wield_image = "default_grass_"..i..".png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, drop = "default:grass_1", groups = {snappy=3,flammable=3,flora=1,attached_node=1,not_in_creative_inventory=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, }) end minetest.register_node("default:dry_grass_1", { description = "Dry Grass", drawtype = "plantlike", waving = 1, tiles = {"default_dry_grass_1.png"}, inventory_image = "default_dry_grass_3.png", wield_image = "default_dry_grass_3.png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy=3,flammable=3,flora=1,attached_node=1}, sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, on_place = function(itemstack, placer, pointed_thing) -- place a random dry grass node local stack = ItemStack("default:dry_grass_"..math.random(1,5)) local ret = minetest.item_place(stack, placer, pointed_thing) return ItemStack("default:dry_grass_1 "..itemstack:get_count()-(1-ret:get_count())) end, }) for i=2,5 do minetest.register_node("default:dry_grass_"..i, { description = "Dry Grass", drawtype = "plantlike", waving = 1, tiles = {"default_dry_grass_"..i..".png"}, inventory_image = "default_dry_grass_"..i..".png", wield_image = "default_dry_grass_"..i..".png", paramtype = "light", sunlight_propagates = true, walkable = false, buildable_to = true, groups = {snappy=3,flammable=3,flora=1,attached_node=1,not_in_creative_inventory=1}, drop = "default:dry_grass_1", sounds = default.node_sound_leaves_defaults(), selection_box = { type = "fixed", fixed = {-0.5, -0.5, -0.5, 0.5, -5/16, 0.5}, }, }) end -- -- Liquids -- minetest.register_node("default:water_source", { description = "Water Source", inventory_image = minetest.inventorycube("default_water.png"), drawtype = "liquid", tiles = { { name = "default_water_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0, }, }, }, special_tiles = { -- New-style water source material (mostly unused) { name = "default_water_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0, }, backface_culling = false, }, }, use_texture_alpha = "blend", paramtype = "light", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:water_flowing", liquid_alternative_source = "default:water_source", liquid_viscosity = 1, post_effect_color = {a=120, r=30, g=60, b=90}, groups = {water=3, liquid=3, puts_out_fire=1}, }) minetest.register_node("default:water_flowing", { description = "Flowing Water", inventory_image = minetest.inventorycube("default_water.png"), drawtype = "flowingliquid", tiles = {"default_water.png"}, special_tiles = { { name = "default_water_flowing_animated.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, { name = "default_water_flowing_animated.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, }, use_texture_alpha = "blend", paramtype = "light", paramtype2 = "flowingliquid", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:water_flowing", liquid_alternative_source = "default:water_source", liquid_viscosity = 1, post_effect_color = {a=120, r=30, g=60, b=90}, groups = {water=3, liquid=3, puts_out_fire=1, not_in_creative_inventory=1}, }) minetest.register_node("default:river_water_source", { description = "River Water Source", inventory_image = minetest.inventorycube("default_river_water.png"), drawtype = "liquid", tiles = { { name = "default_river_water_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0, }, }, }, special_tiles = { { name = "default_river_water_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 2.0, }, backface_culling = false, }, }, use_texture_alpha = "blend", paramtype = "light", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:river_water_flowing", liquid_alternative_source = "default:river_water_source", liquid_viscosity = 1, liquid_renewable = false, liquid_range = 2, post_effect_color = {a=120, r=30, g=76, b=90}, groups = {water=3, liquid=3, puts_out_fire=1}, }) minetest.register_node("default:river_water_flowing", { description = "Flowing River Water", inventory_image = minetest.inventorycube("default_river_water.png"), drawtype = "flowingliquid", tiles = {"default_river_water.png"}, special_tiles = { { name = "default_river_water_flowing_animated.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, { name = "default_river_water_flowing_animated.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 0.8, }, }, }, use_texture_alpha = "blend", paramtype = "light", paramtype2 = "flowingliquid", walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:river_water_flowing", liquid_alternative_source = "default:river_water_source", liquid_viscosity = 1, liquid_renewable = false, liquid_range = 2, post_effect_color = {a=120, r=30, g=76, b=90}, groups = {water=3, liquid=3, puts_out_fire=1, not_in_creative_inventory=1}, }) minetest.register_node("default:lava_source", { description = "Lava Source", inventory_image = minetest.inventorycube("default_lava.png"), drawtype = "liquid", tiles = { { name = "default_lava_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, }, }, special_tiles = { -- New-style lava source material (mostly unused) { name = "default_lava_source_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0, }, backface_culling = false, }, }, paramtype = "light", light_source = default.LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "source", liquid_alternative_flowing = "default:lava_flowing", liquid_alternative_source = "default:lava_source", liquid_viscosity = 7, liquid_renewable = false, damage_per_second = 4 * 2, post_effect_color = {a=192, r=255, g=64, b=0}, groups = {lava=3, liquid=2, hot=3, igniter=1}, }) minetest.register_node("default:lava_flowing", { description = "Flowing Lava", inventory_image = minetest.inventorycube("default_lava.png"), drawtype = "flowingliquid", tiles = {"default_lava.png"}, special_tiles = { { name = "default_lava_flowing_animated.png", backface_culling = false, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3, }, }, { name = "default_lava_flowing_animated.png", backface_culling = true, animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.3, }, }, }, paramtype = "light", paramtype2 = "flowingliquid", light_source = default.LIGHT_MAX - 1, walkable = false, pointable = false, diggable = false, buildable_to = true, is_ground_content = false, drop = "", drowning = 1, liquidtype = "flowing", liquid_alternative_flowing = "default:lava_flowing", liquid_alternative_source = "default:lava_source", liquid_viscosity = 7, liquid_renewable = false, damage_per_second = 4 * 2, post_effect_color = {a=192, r=255, g=64, b=0}, groups = {lava=3, liquid=2, hot=3, igniter=1, not_in_creative_inventory=1}, }) -- -- Tools / "Advanced" crafting / Non-"natural" -- minetest.register_node("default:torch", { description = "Torch", drawtype = "torchlike", tiles = { { name = "default_torch_on_floor_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0 }, }, { name="default_torch_on_ceiling_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0 }, }, { name="default_torch_animated.png", animation = { type = "vertical_frames", aspect_w = 16, aspect_h = 16, length = 3.0 }, }, }, inventory_image = "default_torch_on_floor.png", wield_image = "default_torch_on_floor.png", paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, is_ground_content = false, walkable = false, light_source = default.LIGHT_MAX - 1, selection_box = { type = "wallmounted", wall_top = {-0.1, 0.5-0.6, -0.1, 0.1, 0.5, 0.1}, wall_bottom = {-0.1, -0.5, -0.1, 0.1, -0.5+0.6, 0.1}, wall_side = {-0.5, -0.3, -0.1, -0.5+0.3, 0.3, 0.1}, }, groups = {choppy=2,dig_immediate=3,flammable=1,attached_node=1}, legacy_wallmounted = true, sounds = default.node_sound_defaults(), }) local bookshelf_formspec = "size[8,7;]".. default.gui_bg.. default.gui_bg_img.. default.gui_slots.. "list[context;books;0,0.3;8,2;]".. "list[current_player;main;0,2.85;8,1;]".. "list[current_player;main;0,4.08;8,3;8]".. "listring[context;books]".. "listring[current_player;main]".. default.get_hotbar_bg(0,2.85) minetest.register_node("default:bookshelf", { description = "Bookshelf", tiles = {"default_wood.png", "default_wood.png", "default_bookshelf.png"}, is_ground_content = false, groups = {choppy=3,flammable=3}, sounds = default.node_sound_wood_defaults(), on_construct = function(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", bookshelf_formspec) local inv = meta:get_inventory() inv:set_size("books", 8*2) end, can_dig = function(pos,player) local meta = minetest.get_meta(pos); local inv = meta:get_inventory() return inv:is_empty("books") end, allow_metadata_inventory_put = function(pos, listname, index, stack, player) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local to_stack = inv:get_stack(listname, index) if listname == "books" then if minetest.get_item_group(stack:get_name(), "book") ~= 0 and to_stack:is_empty() then return 1 else return 0 end end end, allow_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) local meta = minetest.get_meta(pos) local inv = meta:get_inventory() local stack = inv:get_stack(from_list, from_index) local to_stack = inv:get_stack(to_list, to_index) if to_list == "books" then if minetest.get_item_group(stack:get_name(), "book") ~= 0 and to_stack:is_empty() then return 1 else return 0 end end end, on_metadata_inventory_move = function(pos, from_list, from_index, to_list, to_index, count, player) minetest.log("action", player:get_player_name().. " moves stuff in bookshelf at "..minetest.pos_to_string(pos)) end, on_metadata_inventory_put = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().. " moves stuff to bookshelf at "..minetest.pos_to_string(pos)) end, on_metadata_inventory_take = function(pos, listname, index, stack, player) minetest.log("action", player:get_player_name().. " takes stuff from bookshelf at "..minetest.pos_to_string(pos)) end, }) minetest.register_node("default:sign_wall", { description = "Sign", drawtype = "nodebox", tiles = {"default_sign.png"}, inventory_image = "default_sign_wall.png", wield_image = "default_sign_wall.png", paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, is_ground_content = false, walkable = false, node_box = { type = "wallmounted", wall_top = {-0.4375, 0.4375, -0.3125, 0.4375, 0.5, 0.3125}, wall_bottom = {-0.4375, -0.5, -0.3125, 0.4375, -0.4375, 0.3125}, wall_side = {-0.5, -0.3125, -0.4375, -0.4375, 0.3125, 0.4375}, }, groups = {choppy=2,dig_immediate=2,attached_node=1,flammable=1}, legacy_wallmounted = true, sounds = default.node_sound_defaults(), use_texture_alpha = "clip", on_construct = function(pos) --local n = minetest.get_node(pos) local meta = minetest.get_meta(pos) meta:set_string("formspec", "field[text;;${text}]") meta:set_string("infotext", "\"\"") end, on_receive_fields = function(pos, formname, fields, sender) --print("Sign at "..minetest.pos_to_string(pos).." got "..dump(fields)) if minetest.is_protected(pos, sender:get_player_name()) then minetest.record_protection_violation(pos, sender:get_player_name()) return end local meta = minetest.get_meta(pos) if not fields.text then return end minetest.log("action", (sender:get_player_name() or "").." wrote \""..fields.text.. "\" to sign at "..minetest.pos_to_string(pos)) meta:set_string("text", fields.text) meta:set_string("infotext", '"'..fields.text..'"') end, }) minetest.register_node("default:ladder", { description = "Ladder", drawtype = "signlike", tiles = {"default_ladder.png"}, inventory_image = "default_ladder.png", wield_image = "default_ladder.png", paramtype = "light", paramtype2 = "wallmounted", sunlight_propagates = true, walkable = false, climbable = true, is_ground_content = false, selection_box = { type = "wallmounted", --wall_top = = <default> --wall_bottom = = <default> --wall_side = = <default> }, groups = {choppy=2,oddly_breakable_by_hand=3,flammable=2}, legacy_wallmounted = true, sounds = default.node_sound_wood_defaults(), }) local fence_texture = "default_fence_overlay.png^default_wood.png^default_fence_overlay.png^[makealpha:255,126,126" minetest.register_node("default:fence_wood", { description = "Wooden Fence", drawtype = "fencelike", tiles = {"default_wood.png"}, inventory_image = fence_texture, wield_image = fence_texture, paramtype = "light", sunlight_propagates = true, is_ground_content = false, selection_box = { type = "fixed", fixed = {-1/7, -1/2, -1/7, 1/7, 1/2, 1/7}, }, groups = {choppy=2,oddly_breakable_by_hand=2,flammable=2}, sounds = default.node_sound_wood_defaults(), }) minetest.register_node("default:glass", { description = "Glass", drawtype = "glasslike_framed_optional", tiles = {"default_glass.png", "default_glass_detail.png"}, inventory_image = minetest.inventorycube("default_glass.png"), paramtype = "light", sunlight_propagates = true, is_ground_content = false, groups = {cracky=3,oddly_breakable_by_hand=3}, sounds = default.node_sound_glass_defaults(), }) minetest.register_node("default:obsidian_glass", { description = "Obsidian Glass", drawtype = "glasslike", tiles = {"default_obsidian_glass.png"}, paramtype = "light", is_ground_content = false, sunlight_propagates = true, sounds = default.node_sound_glass_defaults(), groups = {cracky=3,oddly_breakable_by_hand=3}, }) minetest.register_node("default:rail", { description = "Rail", drawtype = "raillike", tiles = {"default_rail.png", "default_rail_curved.png", "default_rail_t_junction.png", "default_rail_crossing.png"}, inventory_image = "default_rail.png", wield_image = "default_rail.png", paramtype = "light", sunlight_propagates = true, walkable = false, is_ground_content = false, selection_box = { type = "fixed", -- but how to specify the dimensions for curved and sideways rails? fixed = {-1/2, -1/2, -1/2, 1/2, -1/2+1/16, 1/2}, }, groups = {bendy=2,dig_immediate=2,attached_node=1,connect_to_raillike=minetest.raillike_group("rail")}, }) minetest.register_node("default:brick", { description = "Brick Block", tiles = {"default_brick.png"}, is_ground_content = false, groups = {cracky=3}, sounds = default.node_sound_stone_defaults(), }) minetest.register_node("default:meselamp", { description = "Mese Lamp", drawtype = "glasslike", tiles = {"default_meselamp.png"}, paramtype = "light", sunlight_propagates = true, is_ground_content = false, groups = {cracky = 3}, sounds = default.node_sound_glass_defaults(), light_source = default.LIGHT_MAX, }) -- -- Misc -- minetest.register_node("default:cloud", { description = "Cloud", tiles = {"default_cloud.png"}, is_ground_content = false, sounds = default.node_sound_defaults(), groups = {not_in_creative_inventory=1}, })
gpl-3.0
Lleafll/sws-lleaf
localization/zhTW.lua
1
9003
local L = LibStub("AceLocale-3.0"):NewLocale("StatWeightScore", "zhTW"); if not L then return end -- L["AlternativeStatDisplayNames_Crit"] = "" L["AlternativeStatDisplayNames_Spellpower"] = "法術能量" -- Needs review L["CharacterPane_CM_Tooltip"] = "總分不適用於降低裝備等級的挑戰模式地城中" L["CharacterPane_Tooltip_Title"] = "評量屬性分數" L["CharacterPane_Tooltip_Title_Text"] = "在%s 專精下所有現有裝備物品的總屬性權重分數" -- L["Crafting_Upgrade_Label"] = "" L["Culture"] = "enUS" L["DecimalSeparator"] = "%." -- L["Empowered_Upgrade_Label"] = "" L["Error_MultiplePrimaryStatsSelected"] = "您只能選擇一個主要屬性(敏捷、力量或智力)" L["GemsDisplayFormat"] = "%s 珠寶" -- L["Matcher_BlackhandTrinket2_ArgOrder"] = "" -- L["Matcher_BlackhandTrinket2_Pattern"] = "" -- L["Matcher_BlackhandTrinket3_ArgOrder"] = "" -- L["Matcher_BlackhandTrinket3_Pattern"] = "" L["Matcher_BlackhandTrinket_ArgOrder"] = "duration value stat tick maxstack ppm" L["Matcher_BlackhandTrinket_Pattern"] = "^Equip: Your [%a ]- have a chance to trigger [%a' ]- for (%d+) sec. While [%a' ]- is active, you gain ([%d,%. ]+) ([%a ]-) every ([%d,%. ]+) sec, stacking up to ([%d,%. ]+) times%. %(Approximately ([%d%.]+) procs per minute%)$" L["Matcher_BonusArmor_ArgOrder"] = "value" L["Matcher_BonusArmor_Pattern"] = "^%+(%d+) ?BONUS_ARMOR$" L["Matcher_ICD2_ArgOrder"] = "value stat duration chance cd" L["Matcher_ICD2_Pattern"] = "^Equip: Your attacks have a chance to grant you ([%d,%. ]+) ([%a ]-) for (%d+) sec%. %((%d+)%% chance, (%d+) sec cooldown%)$" -- L["Matcher_ICD3_ArgOrder"] = "" -- L["Matcher_ICD3_Pattern"] = "" L["Matcher_ICD_ArgOrder"] = "value stat duration chance cd" L["Matcher_ICD_Pattern"] = "^Equip: Each time your attacks hit, you have a chance to gain ([%d,%. ]+) ([%a ]-) for (%d+) sec%. %((%d+)%% chance, (%d+) sec cooldown%)$" -- L["Matcher_InsigniaOfConquest2_ArgOrder"] = "" -- L["Matcher_InsigniaOfConquest2_Pattern"] = "" L["Matcher_InsigniaOfConquest_ArgOrder"] = "value stat duration" L["Matcher_InsigniaOfConquest_Pattern"] = "^Equip: When you deal damage you have a chance to gain ([%d,%. ]+) ([%a ]-) for (%d+) sec%." L["Matcher_Partial_CdMin"] = "(%d+) Min" L["Matcher_Partial_CdSec"] = "(%d+) Sec" L["Matcher_Precheck_BonusArmor"] = "BONUS_ARMOR$" L["Matcher_Precheck_Equip"] = "^裝備:" L["Matcher_Precheck_Use"] = "^使用:" -- L["Matcher_RPPM2_ArgOrder"] = "" -- L["Matcher_RPPM2_Pattern"] = "" -- L["Matcher_RPPM3_ArgOrder"] = "" -- L["Matcher_RPPM3_Pattern"] = "" -- L["Matcher_RPPM4_ArgOrder"] = "" -- L["Matcher_RPPM4_Pattern"] = "" L["Matcher_RPPM_ArgOrder"] = "value stat duration ppm" L["Matcher_RPPM_Pattern"] = "^Equip: Your attacks have a chance to grant ([%d,%. ]+) ([%a ]-) for (%d+) sec%. %(Approximately ([%d%.]+) procs per minute%)$" L["Matcher_SoliumBand_ArgOrder"] = "type duration ppm" L["Matcher_SoliumBand_BuffType_Greater"] = "Greater" L["Matcher_SoliumBand_Pattern"] = "^Equip: Your attacks have a chance to grant Archmage's ?(%a-) Incandescence for (%d+) sec%. %(Approximately ([%d%.]+) procs per minute%)$" L["Matcher_StatTooltipParser_Armor"] = "^(%d+) (RESISTANCE0_NAME)$" -- L["Matcher_StatTooltipParser_Armor_ArgOrder"] = "" L["Matcher_StatTooltipParser_DPS"] = "^%(([%d,%. ]+) ([%a ]+)%)$" -- L["Matcher_StatTooltipParser_DPS_ArgOrder"] = "" L["Matcher_StatTooltipParser_Stat"] = "^%+([%d,%. ]+) ([%a ]+)$" -- L["Matcher_StatTooltipParser_Stat_ArgOrder"] = "" L["Matcher_StoneOfFire_ArgOrder"] = "value duration" L["Matcher_StoneOfFire_Pattern"] = "^Equip: When you heal or deal damage you have a chance to increase your Strength, Agility, or Intellect by ([%d,%. ]+) for (%d+) sec%. Your highest stat is always chosen%.$" L["Matcher_Use2_ArgOrder"] = "value stat duration cd" L["Matcher_Use2_Pattern"] = "^Use: Grants ([%d,%. ]+) ([%a ]-) for (%d+) sec%. %(([%d%a ]-) Cooldown%)$" -- L["Matcher_Use3_ArgOrder"] = "" -- L["Matcher_Use3_Pattern"] = "" -- L["Matcher_Use4_ArgOrder"] = "" -- L["Matcher_Use4_Pattern"] = "" L["Matcher_Use_ArgOrder"] = "stat value duration cd" L["Matcher_Use_Pattern"] = "^Use: Increases y?o?u?r? ?([%a ]-) by ([%d,%. ]+) for (%d+) sec%. %(([%d%a ]-) Cooldown%)$" L["Offhand_DPS"] = "副手秒傷" L["Offhand_Score"] = "副手分數" L["Options_BlankLineMainAbove_Label"] = "上方加入空行(主要)" L["Options_BlankLineMainAbove_Tooltip"] = "在主要提示中屬性評分資訊之上顯示空白行" L["Options_BlankLineMainBelow_Label"] = "下方加入空行(主要)" L["Options_BlankLineMainBelow_Tooltip"] = "在主要提示中屬性評分資訊之下顯示空白行" L["Options_BlankLineRefAbove_Label"] = "上方加入空行(比較)" L["Options_BlankLineRefAbove_Tooltip"] = "在比較提示中屬性評分資訊之上顯示空白行(例:你在一個物品上同時按下Shift鍵)" L["Options_BlankLineRefBelow_Label"] = "下方加入空行(比較)" L["Options_BlankLineRefBelow_Tooltip"] = "在比較提示中屬性評分資訊之下顯示空白行(例:你在一個物品上同時按下Shift鍵)" L["Options_Compare_Character"] = "角色分數總計" L["Options_Compare_Item"] = "裝備物品分數" L["Options_Compare_Label"] = "百分比獲取比較為" L["Options_Compare_Tooltip"] = "是否在提示中顯示與現有裝備物品或角色總分的比較百分比值。" L["Options_CreateNewSpec"] = "創建新的專精" L["Options_DeleteSpec"] = "刪除專精" L["Options_DeleteSpec_Confirm"] = "您確定想要刪除專精 '%s'?" L["Options_DuplicateSpec"] = "複製專精" L["Options_EnableCmMode_Label"] = "啟用挑戰模式" L["Options_EnableCmMode_Tooltip"] = "當在挑戰模式地城時,直接從提示讀取屬性 - 那些是挑戰模式正確的屬。只有當你按下Shift鍵,並且有啟用此選項,並且在挑戰模式地城裡比較才有效。" L["Options_Enabled"] = "啟用" L["Options_EnabledGlobal_Tooltip"] = "在提示中啟用屬性評分的顯示" L["Options_EnabledSpec_Tooltip"] = "在提示中啟用特定專精屬性評分的顯示" L["Options_EnchantLevel_Label"] = "珠寶等級" L["Options_EnchantLevel_Tooltip"] = "空插槽使用什麼等級的珠寶" L["Options_Export"] = "匯出" L["Options_Export_Label"] = "匯出輸出" L["Options_Export_Title"] = "匯出權重" L["Options_ExportType_Label"] = "匯出到" L["Options_ExportType_Tooltip"] = "選擇匯出格式" L["Options_ForceSelectedGemStat_Label"] = "強制選擇珠寶 屬性/數值" L["Options_ForceSelectedGemStat_Tooltip"] = "如果物品已經有個插槽插入了寶石,不使用那塊寶石進行計算,而是使用專精設置中基於等級與屬性的最佳寶石" L["Options_GemStat_Best"] = "最佳屬性" L["Options_GemStat_Label"] = "珠寶屬性" L["Options_GemStat_Tooltip"] = "假定空的珠寶插槽要使用什麼屬性。最佳屬性會自動選擇最佳的評定屬性。" L["Options_GetStats_Label"] = "獲取屬性來源" L["Options_GetStats_ParseTooltip"] = "物品提示" L["Options_GetStats_Tooltip"] = "是否從wow api調用獲取屬性 (GetItemStats()) 或是從提示中解析。從提示解析有一定的優勢 (例如允許您可以計算副專精灰暗的屬性),但需要所使用的語言支持。" L["Options_GetStats_WoWAPI"] = "WoW API" L["Options_Import_Label"] = "匯入" L["Options_Import_Title"] = "匯入權重" L["Options_Import_Tooltip"] = "複製&貼上來輸入匯入" L["Options_ImportType_Label"] = "匯入來源" L["Options_ImportType_Tooltip"] = "選擇匯入來源類型" L["Options_NormalizeWeights_Label"] = "標準值" L["Options_NormalizeWeights_Tooltip"] = "調整計算的值- 所以主屬性會是1.0,其他屬性會以此為標準調整" L["Options_Open"] = "開啟設置" L["Options_Order_Label"] = "排序" L["Options_Percentage_Change"] = "變動" L["Options_Percentage_Difference"] = "差異" L["Options_Percentage_Label"] = "百分比計算為" L["Options_Percentage_Tooltip"] = "是否在提示中顯示百分比變動或差異的百分比值。" L["Options_SelectStats_Label"] = "選擇屬性" L["Options_SelectStats_Tooltip"] = "選擇跟此專精相關的屬性" L["Options_ShowStatsPane_Label"] = "顯示總分" L["Options_ShowStatsPane_Tooltip"] = "是否在角色視窗顯示總分" -- L["Options_ShowUpgrades_Label"] = "" -- L["Options_ShowUpgrades_Tooltip"] = "" L["Options_Specialization_Label"] = "專精" L["Options_Specialization_Tooltip"] = "此屬性權重設置的標籤" L["Options_StatWeightsSetup"] = "屬性權重設置" L["Options_Weights_Open"] = "開啟屬性權重的設置" L["Options_Weights_Section"] = "屬性權重" L["StatPaneCategoryTitle"] = "屬性評量分數" L["ThousandSeparator"] = "," -- L["TooltipMessage_Offhand"] = "" L["TooltipMessage_StatScore"] = "屬性評分" L["TooltipMessage_WithGem"] = "包含珠寶" L["TooltipMessage_WithProcAverage"] = "包含平均觸發" L["TooltipMessage_WithUseAverage"] = "包含平均使用冷卻" L["Warning"] = "警告" L["WelcomeMessage"] = "已載入。 v%s by Necroskillz"
mit
rigeirani/sss
plugins/spammer.lua
2
65978
local function run(msg) if msg.text == "[!/]spam" then return "".. [[ kose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nv ]] end end return { description = "Spamms the group fastly", usage = "!fuck or Fuckgp or Fuck : send 1000 Spams to the group", patterns = { "^[!/]fuck$", "^fuckgp$", "^Fuck$", "^spam$", "^Fuckgp$", }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
llX8Xll/DEVKEEPER1
plugins/WLC.lua
1
1382
do local function run(msg,matches) if matches[1] == "chat_add_user" then return "🔥{ آهہلآ ؤسہهہلآ 😘 بہكہ كہبہد رؤحہيہ نہؤرتہ 👮🏽‍♀️ آلمہجہمہؤعہهہ❤️❗️ }\n".."🔥{ آسہمہ آلمہجہمہؤعہهہ }"..msg.to.title.."\n".."🔥{ آيہديہ آلمہجہمہؤعہهہ }"..msg.to.id.."\n".."🔥{ آسہمہ آلضہآفہكہ }"..(msg.from.first_name or " ").."\n".."🔥{ مہعہرفہ آلضہآفہكہ }@"..(msg.from.username or " ").."\n".."🔥{ مہعہرفہكہ }@"..(msg.action.user.username or " ") elseif matches[1] == "chat_add_user_link" then return "آهہلآ ؤسہهہلآ 😘 بہكہ كہبہد رؤحہيہ نہؤرتہ 👮🏽‍♀️ آلمہجہمہؤعہهہ❤️ \n".."🔥{آسہمہ آلمہجہمہؤعہهہ } "..msg.to.title.."\n".."🔥{آيہديہ آلمہجہمہؤعہهہ } "..msg.to.id.."\n".."🔥{آسہمہكہ آلآؤل }: "..msg.from.first_name.."\n🔥{آسہمہكہ آلثہآنہيہ }:"..(msg.from.last_name or " لآ يہؤجہد" ).."\n ".. "🔥{مہعہرفہكہ}: @"..(msg.from.username or "لآ يہؤجہد " ).."\n".."🔥{آيہديہكہ}:"..msg.from.id end end return { patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$" }, run = run, } end
gpl-2.0
RyMarq/Zero-K
LuaUI/Widgets/chili_old/Headers/autolocalizer.lua
8
3777
--------------------------------------------------------------------------- -- -- Lua Namespace Localizer -- -- author: jK (2009) -- -- License: GPLv2 -- -- Info: -- overrides VFS.Include with a function that autolocalize the used namespaces -- -- Settings local maxLocals = 50 local namespaces = { {"Spring.MoveCtrl", "mc"}, {"Spring", "sp"}, {"Script", "sc"}, {"gl", "gl"}, {"GL", "GL_"}, {"math", ""}, {"CMD", "CMD_"}, {"CMDTYPE", "CMDTYPE_"}, {"Game", "Game"}, {"table", "tb"}, } --//TODO local globalFuncs = { "pairs", "ipairs", "select", "unpack", "UnitDefs", "UnitDefNames", "FeatureDefs", "WeaponDefs", } --------------------------------------------------------------------------- -- if (Spring.GetConfigInt("AutoLocalizeLua", 1) == 0) then return end --------------------------------------------------------------------------- -- local used_funcs = {} local numLocals = 0 local function CreateLocal(prefix) local _G = getfenv() return function(fnc_prefix,fnc_name) local longname = fnc_prefix .. "." .. fnc_name local shortname = prefix..fnc_name --// if it's not in the current global namespace (perhaps it gets added later?) --// then don't localize it local gn = _G[fnc_prefix] if (type(gn)~="table")or(not gn[fnc_name]) then return longname end if (used_funcs[longname]) then return shortname else if (numLocals<maxLocals) then numLocals = numLocals + 1 used_funcs[longname] = prefix..fnc_name return shortname else return longname --// don't localize we hit locals limit end end end end local function LocalizeString(str) used_funcs = {} numLocals = 0 for i=1, #namespaces do local ns = namespaces[i] str = str:gsub( "(".. ns[1] .. ")%.([%w_]+)", CreateLocal(ns[2])) end for i=1, #globalFuncs do local gfunc = globalFuncs[i] if (str:find( "[^%w_]" .. gfunc .. "[^%w_]" )) then used_funcs[gfunc] = gfunc end end local array = {} local i = 1 for funcname, shortname in pairs(used_funcs) do array[i] = "local " .. shortname .. " = " .. funcname ..";" i = i + 1 end array[i] = str return table.concat(array, "") end --------------------------------------------------------------------------- -- local orig_load = VFS.LoadFile local orig_include = VFS.Include function LoadFileSafe(filename, mode) if (mode) then return orig_load(filename, mode) else return orig_load(filename) end end --------------------------------------------------------------------------- -- local function MyLoadString(str, filename) local chunk,err local oldMaxLocals = maxLocals local str2 if (filename:len()>40) then filename = filename:sub(-40) end repeat str2 = LocalizeString(str) chunk, err = loadstring(str2, filename) if (not chunk) then if (err:find("has more than %d+ upvalues")) then maxLocals = maxLocals - 10 end error(err) end until (chunk)or(maxLocals==0) maxLocals = oldMaxLocals return chunk,str2 end function VFS.Include(filename, enviroment, mode) local str = LoadFileSafe(filename, mode) if (not str) then return end if (not enviroment) then local status status,enviroment = pcall(getfenv,3) if (not status) then status,enviroment = pcall(getfenv,2) if (not status) then enviroment = getfenv() end end end local chunk = MyLoadString(str, filename) setfenv(chunk, enviroment) return chunk() end function VFS.LoadFile(filename, mode) local str = LoadFileSafe(filename, mode) if (str)and(filename:find(".lua", 1, true)) then _,str = MyLoadString(str, filename) end return str end
gpl-2.0
james2doyle/lit
libs/vfs.lua
5
3347
--[[ Copyright 2014-2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local gfs = require('coro-fs') local miniz = require('miniz') local pathJoin = require('luvi').path.join local function zipFs(zip, autoChroot) local zfs = {} local prefix = "./" local function locateFile(path) local index, err = zip:locate_file(path) if index then return index end if err:match("^Can't find file") then err = "ENOENT: " .. err end return nil, err end function zfs.stat(path) path = pathJoin(prefix .. path) if path == "" then return { type = "directory", mode = 493 } end local err local index = locateFile(path) if not index then index, err = locateFile(path .. "/") if not index then return nil, err end end local raw = zip:stat(index) local typ = raw.filename:sub(-1) == "/" and "directory" or "file" return { type = typ, size = raw.uncomp_size, mtime = raw.time, mode = typ == "directory" and 493 or 420 } end function zfs.scandir(path) path = pathJoin(prefix .. path) local index, err if path == "" then index = 0 else path = path .. "/" index, err = locateFile(path) if not index then return nil, err end if not zip:is_directory(index) then return nil, path .. " is not a directory" end end local i = index + 1 local num = zip:get_num_files() return function () while i <= num do local filename = zip:get_filename(i) i = i + 1 if string.sub(filename, 1, #path) ~= path then return end filename = filename:sub(#path + 1) local typ = "file" local n = string.find(filename, "/") if n == #filename then filename = string.sub(filename, 1, #filename - 1) typ = "directory" n = nil end if not n then return { name = filename, type = typ, mode = typ == "directory" and 493 or 420 } end end end end function zfs.readFile(path) path = pathJoin(prefix .. path) local index, err = locateFile(path) if not index then return nil, err end return zip:extract(index) end -- Check for zips with single folder at root if autoChroot then local entries = {} for entry in zfs.scandir("") do entries[#entries + 1] = entry if #entries > 1 then break end end if #entries == 1 and entries[1].type == "directory" then prefix = entries[1].name .. "/" end end return zfs end return function (path) local zip = miniz.new_reader(path) if zip then local fs, newPath = zipFs(zip, true), "" fs.base = path return fs, newPath else return gfs, path end end
apache-2.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Network/WorldClient.lua
1
6698
--[[ Title: WorldClient Author(s): LiXizhi Date: 2014/6/4 Desc: client side to login to the server. use the lib: ------------------------------------------------------- NPL.load("(gl)script/apps/Aries/Creator/Game/Network/WorldClient.lua"); local WorldClient = commonlib.gettable("MyCompany.Aries.Game.Network.WorldClient"); ------------------------------------------------------- ]] NPL.load("(gl)script/apps/Aries/Creator/Game/World/World.lua"); NPL.load("(gl)script/apps/Aries/Creator/Game/Network/NetClientHandler.lua"); local Packets = commonlib.gettable("MyCompany.Aries.Game.Network.Packets"); local NetClientHandler = commonlib.gettable("MyCompany.Aries.Game.Network.NetClientHandler"); local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine") local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types") local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic") local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager"); local WorldClient = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.World.World"), commonlib.gettable("MyCompany.Aries.Game.Network.WorldClient")); WorldClient.class_name = "WorldClient"; function WorldClient:ctor() end -- @param name: must be a unique name, the client side server defaults to "default" function WorldClient:Init(name) self.world_generator= "null"; self:SetName(name); self:PrepareNetWorkWorld(); WorldClient._super.Init(self); NPL.load("(gl)script/apps/Aries/Creator/Game/Network/PlayerManagerClient.lua"); local PlayerManagerClient = commonlib.gettable("MyCompany.Aries.Game.Network.PlayerManagerClient"); self.thePlayerManager = PlayerManagerClient:new():Init(self); NPL.load("(gl)script/apps/Aries/Creator/Game/World/WorldTrackerClient.lua"); WorldTrackerClient = commonlib.gettable("MyCompany.Aries.Game.World.WorldTrackerClient") self.worldTracker = WorldTrackerClient:new():Init(self); return self; end -- create empty local disk path. function WorldClient:PrepareNetWorkWorld() -- create a new empty world here, we will never save the world local worldpath = "temp/clientworld"; ParaIO.DeleteFile(worldpath.."/"); ParaIO.CreateDirectory(worldpath.."/"); ParaWorld.NewEmptyWorld("temp/clientworld", 533.3333, 64); self.worldpath = worldpath; end function WorldClient:GetWorldPath() return self.worldpath; end function WorldClient:InitBlockGenerator() -- always use a null generator for client local block_generator = self:GetChunkProvider():CreateGenerator("null"); self:GetChunkProvider():SetGenerator(block_generator); ParaTerrain.GetAttributeObject():SetField("RenderTerrain",false); GameLogic.options.has_real_terrain = ParaTerrain.GetAttributeObject():GetField("RenderTerrain",true); LOG.std(nil, "info", "WorldClient", "null generator is used"); end function WorldClient:OnPreloadWorld() GameLogic.SetIsRemoteWorld(true, false); -- initialize with null block generator that does not generate terrain. -- disable real world terrain local block = commonlib.gettable("MyCompany.Aries.Game.block") block.auto_gen_terrain_block = false; ParaTerrain.GetAttributeObject():SetField("RenderTerrain",false); GameLogic.options.has_real_terrain = false; end function WorldClient:SetName(name) self.name = name; end function WorldClient:GetName(name) return self.name; end function WorldClient:OnWeaklyDestroyWorld() WorldClient._super.OnWeaklyDestroyWorld(self); self:Disconnect(); end function WorldClient:OnExit() WorldClient._super.OnExit(self); if(self.net_handler) then self.net_handler:Cleanup(); end return self; end -- virtual function: Creates the chunk provider for this world. Called in the constructor. function WorldClient:CreateChunkProvider() NPL.load("(gl)script/apps/Aries/Creator/Game/World/ChunkProviderClient.lua"); local ChunkProviderClient = commonlib.gettable("MyCompany.Aries.Game.World.ChunkProviderClient"); return ChunkProviderClient:new():Init(self); end function WorldClient:GetPlayerManager() return self.thePlayerManager; end -- @param params: {ip, port, thread, username, password, name, tunnelClient} function WorldClient:Login(params) local ip = params.ip or "127.0.0.1"; local port = params.port or "8099"; -- a random username local username = params.username; local password = params.password; local thread = params.thread or "gl"; LOG.std(nil, "info", "WorldClient", "start login %s %s as username:%s", ip, port, username); self.username = username; self.password = password; -- prepare address -- this is a pure client, so do not listen on any port. Just start the network interface. NPL.StartNetServer("127.0.0.1", "0"); local Connections = commonlib.gettable("MyCompany.Aries.Game.Network.Connections"); Connections:Init(); self.net_handler = NetClientHandler:new():Init(ip, port, username, password, self, params.tunnelClient); self.nid = self.net_handler:GetNid(); -- TODO: it should be the server to enable world editing mode instead of client. -- For demo, we will enable it anyway for debugging. if(GameLogic.GameMode:IsEditor()) then self:EnableAdvancedWorldEditing(true); end -- whether we will edit remote world in any way we like. function WorldClient:EnableAdvancedWorldEditing(bEnabled) if(bEnabled) then self:AddWorldTracker(self.worldTracker); else self:RemoveWorldTracker(self.worldTracker); end end function WorldClient:Disconnect() if(self.net_handler) then self.net_handler:Cleanup(); end end function WorldClient:IsClient() return true; end function WorldClient:Tick() self:GetWorldInfo():SetTotalWorldTime(self:GetWorldInfo():GetWorldTotalTime() + 1); self:GetPlayerManager():SendAllChunkUpdates(); end function WorldClient:CreateClientPlayer(clientEntityId, netClientHandler) local entityMP = GameLogic.GetPlayerController():CreateNewClientPlayerMP(self, clientEntityId, netClientHandler or self.net_handler); entityMP:Attach(); GameLogic.GetPlayerController():SetMainPlayer(entityMP); return entityMP; end function WorldClient:GetPlayer() return EntityManager.GetPlayer(); end function WorldClient:RemoveEntityFromWorld(entityId) local entity = self:GetEntityByID(entityId); if (entity) then self:RemoveEntity(entity); end return entity; end function WorldClient:CreateBlockPieces(block_template, blockX, blockY, blockZ, granularity, texture_filename, cx, cy, cz) WorldClient._super.CreateBlockPieces(self, block_template, blockX, blockY, blockZ, granularity, texture_filename, cx, cy, cz); if(block_template) then self:GetPlayer():AddToSendQueue(Packets.PacketBlockPieces:new():Init(block_template.id, blockX, blockY, blockZ, granularity)); end end
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Sauromugue_Champaign/npcs/Tiger_Bones.lua
1
1652
----------------------------------- -- Area: Sauromugue Champaign -- NPC: Tiger Bones -- Involed in Quest: The Fanged One. -- @zone 120 -- @pos 666 -8 -379 ------------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ------------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getQuestStatus(WINDURST,THE_FANGED_ONE) == QUEST_ACCEPTED) then deadTiger = player:getVar("TheFangedOne_Died"); if(deadTiger == 1 and player:hasKeyItem(OLD_TIGERS_FANG) == false) then player:addKeyItem(OLD_TIGERS_FANG); player:messageSpecial(KEYITEM_OBTAINED, OLD_TIGERS_FANG); elseif(deadTiger == 0) then if(GetMobAction(17268808) == 0) then SpawnMob(17268808); player:messageSpecial(OLD_SABERTOOTH_DIALOG_I); 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
Grocel/wire-extras
lua/entities/gmod_wire_adv_hudindicator/cl_init.lua
2
32556
include('shared.lua') ENT.RenderGroup = RENDERGROUP_BOTH local advhudindicators = {} // Default HUD x/y local nextupdate = 0 // Text Height Constant local dtextheight = draw.GetFontHeight("Default") // So we don't need to calculate this every frame w/ Percent Bar style local pbarheight = dtextheight + 16 // Y Offset constants // Texture IDs for Full/Semi-Circle styles local tex_sci_fi_1 = surface.GetTextureID("adv_hud/sci_fi_style_1") // Copied from wirelib.lua (table.MakeSortedKeys() should be made shared :P) local function MakeSortedKeys(tbl) local result = {} for k,_ in pairs(tbl) do table.insert(result, k) end table.sort(result) return result end // Function to check if a registered HUD Indicator: // A) belongs to someone other than the calling LocalPlayer() // B) is not registered as pod-only function ENT:ClientCheckRegister() local ply = LocalPlayer() local plyuid = ply:UniqueID() return ply != self:GetPlayer() && !self:GetNWBool(plyuid) end // Used by STool for unregister control panel // Only allowed to unregister HUD Indicators that aren't yours // and for those that aren't pod-only registers function AdvHUDIndicator_GetCurrentRegistered() local registered = {} for eindex,_ in pairs(advhudindicators) do local ent = ents.GetByIndex(eindex) if (ent && ent:IsValid()) and (ent:CheckClientRegister()) then local entry = {} entry.EIndex = eindex entry.Description = advhudindicators[eindex].Description table.insert(registered, entry) end end return registered end local function isInsideZone( x, y, minX, minY, maxX, maxY ) return ( x > minX && x < maxX ) and ( y > minY && y < maxY ) end local function DrawAdvHUDIndicators() if (!LocalPlayer():Alive()) then return end local screenWidth = ScrW() local screenHeight = ScrH() local errors = 0 // Now draw HUD Indicators for _, index in ipairs(MakeSortedKeys(advhudindicators)) do if (advhudindicators[index]) then // Is this necessary? local ent = ents.GetByIndex(index) if (ent && ent:IsValid() ) then local indinfo = advhudindicators[index] //-- If we're hidden just skip this lot --// if( !indinfo.HideHUD ) then local xPos = indinfo.xPos local yPos = indinfo.yPos local zPos = indinfo.zPos local xEnd = indinfo.xEnd local yEnd = indinfo.yEnd local zEnd = indinfo.zEnd local positionMethod = indinfo.positionMethod //--Convert the world position to a screenspace position, this skips the input conversion step, as it makes no sense here... if( indinfo.useWorldCoords == 1 ) then //-- Start Coordinate --// local screenPos = Vector( xPos, yPos, zPos ):ToScreen() xPos = screenPos.x yPos = screenPos.y //-- End Coordinate --// local endScreenPos = Vector( xEnd, yEnd, zEnd ):ToScreen() xEnd = endScreenPos.x yEnd = endScreenPos.y else //--Convert the positions based on the position method. if( positionMethod == 1 ) then xPos = (screenWidth/100)*xPos yPos = (screenHeight/100)*yPos if( xEnd && yEnd ) then xEnd = (screenWidth/100)*xEnd yEnd = (screenHeight/100)*yEnd end elseif( positionMethod == 2 ) then xPos = screenWidth*((xPos/2)+0.5) yPos = screenHeight*((yPos/2)+0.5) if( xEnd && yEnd ) then xEnd = screenWidth*((xEnd/2)+0.5) yEnd = screenHeight*((yEnd/2)+0.5) end end end local txt = indinfo.FullText or "" if( indinfo.alpha != nil ) then alphaVal = indinfo.alpha end //-- Access the colors for this indicator, and update the local variables --// local AColor = indinfo.AColor local BColor = indinfo.BColor if( indinfo.Style == nil ) then errors = errors + 1 //-- Basic --// elseif (indinfo.Style == 0) then //--draw.WordBox(8, xPos, yPos, txt, "Default", Color(50, 50, 75, 192), Color(255, 255, 255, 255)) draw.DrawText( txt, "ScoreboardDefault", xPos, yPos, indinfo.DisplayColor, indinfo.TextColor ) //-- Boxed Text (rounded corners...) --// elseif (indinfo.Style == 1) then //draw.WordBox(8, xPos, yPos, txt, "Default", indinfo.DisplayColor, indinfo.TextColor) draw.WordBox(8, xPos, yPos, txt, "Default", Color(BColor.r, BColor.g, BColor.b, BColor.a), Color(AColor.r, AColor.g, AColor.b, AColor.a)) //--Text Box - Pretty much only useful with string gates--// elseif (indinfo.Style == 2) then local lines = string.Explode("|", indinfo.Description) local boxWidth = 0 local boxHeight = 0 surface.SetFont("ChatFont") //--Gather the total height and max width of this text--// for k,v in pairs(lines) do local lineWidth, lineHeight = surface.GetTextSize( v ) if ( lineWidth > boxWidth ) then boxWidth = lineWidth end boxHeight = boxHeight + lineHeight + 2 end //--Add a bit of a border (5px all round)--// boxWidth = boxWidth + 10 boxHeight = boxHeight + 10 //--Draw the background rectangle--// surface.SetDrawColor(50, 50, 75, 192) surface.DrawRect( xPos, yPos, boxWidth, boxHeight ) surface.SetTextColor(255, 255, 255, 255) local index = 0 for k,v in pairs(lines) do surface.SetTextPos( xPos+5, yPos+5+(index*(lineHeight+2)) ) surface.DrawText( v ); index = index + 1 end //-- Percent Bar (Style 1) --// elseif (indinfo.Style == 10) then local pbarwidth = 200 //--Reposition at the center of the point specified.--// xPos = xPos - pbarwidth/2 xPos = xPos - pbarheight/2 local w1 = pbarwidth*indinfo.Factor local w2 = pbarwidth*(1-indinfo.Factor) if (indinfo.Factor > 0) then // Draw only if we have a factor local BColor = indinfo.BColor surface.SetDrawColor(BColor.r, BColor.g, BColor.b, 160) surface.DrawRect(xPos, yPos, w1, pbarheight) end if (indinfo.Factor < 1) then //--local AColor = indinfo.AColor surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawRect(xPos+w1, yPos, w2, pbarheight) end //--Draw the border--// surface.SetDrawColor( 255, 255, 255,160) surface.DrawOutlinedRect(xPos, yPos, pbarwidth, pbarheight) if( txt != "" ) then draw.SimpleText(txt, "Default", xPos+10, yPos+8, Color(255, 255, 255, 255), 0) end //-- Percent Bar (Style 2) --// elseif( indinfo.Style == 11 ) then local pbarwidth = 200 //--Reposition at the center of the point specified.--// xPos = xPos - pbarwidth/2 xPos = xPos - pbarheight/2 local pos = pbarwidth*indinfo.Factor //--Draw the bar--// surface.SetDrawColor(BColor.r, BColor.g, BColor.b, 160) surface.DrawRect(xPos, yPos, pbarwidth, pbarheight) //--Draw the marker--// surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawRect(xPos+pos-3, yPos, 6, pbarheight) //--Draw the border--// surface.SetDrawColor( 255, 255, 255,160) surface.DrawOutlinedRect(xPos, yPos, pbarwidth, pbarheight) if( txt != "" ) then draw.SimpleText(txt, "Default", xPos+10, yPos+7, Color(255, 255, 255, 255), 0) end //-- Vertical Bar (Style 1) --// elseif (indinfo.Style == 20) then local pbarwidth = 200 //--Reposition at the center of the point specified.--// xPos = xPos - pbarwidth/2 xPos = xPos - pbarheight/2 local w1 = pbarwidth*indinfo.Factor local w2 = pbarwidth*(1-indinfo.Factor) if (indinfo.Factor > 0) then // Draw only if we have a factor local BColor = indinfo.BColor surface.SetDrawColor(BColor.r, BColor.g, BColor.b, 160) surface.DrawRect(xPos, yPos, pbarheight, w1) end if (indinfo.Factor < 1) then //--local AColor = indinfo.AColor surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawRect(xPos, yPos+w1, pbarheight, w2) end //--Draw the border--// surface.SetDrawColor( 255, 255, 255,160) surface.DrawOutlinedRect(xPos, yPos, pbarheight, pbarwidth) if( txt != "" ) then draw.SimpleText(txt, "Default", xPos+pbarheight+5, yPos, Color(255, 255, 255, 255), 0) end //-- Vertical Bar (Style 2) --// elseif(indinfo.Style == 21) then local pbarwidth = 200 //--Reposition at the center of the point specified.--// xPos = xPos - pbarwidth/2 xPos = xPos - pbarheight/2 local pos = pbarwidth*indinfo.Factor //--Draw the bar--// surface.SetDrawColor(BColor.r, BColor.g, BColor.b, 160) surface.DrawRect(xPos, yPos, pbarheight, pbarwidth) //--Draw the marker--// surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawRect(xPos, yPos+pos-3, pbarheight, 6) //--Draw the border--// surface.SetDrawColor( 255, 255, 255,160) surface.DrawOutlinedRect(xPos, yPos, pbarheight, pbarwidth) if( txt != "" ) then draw.SimpleText(txt, "Default", xPos+pbarheight+5, yPos, Color(255, 255, 255, 255), 0) end //-- Targetting Rectangle --// elseif (indinfo.Style == 30) then local size = 45 surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 90) surface.DrawRect(xPos-size, yPos-size, size*2, size*2) surface.SetDrawColor(BColor.r, BColor.g, BColor.b, 160) surface.DrawLine(xPos-size, yPos-size, xPos-size, yPos-size+15) surface.DrawLine(xPos-size, yPos-size, xPos-size+15, yPos-size) surface.DrawLine(xPos+size, yPos-size, xPos+size, yPos-size+15) surface.DrawLine(xPos+size, yPos-size, xPos+size-15, yPos-size) surface.DrawLine(xPos-size, yPos+size, xPos-size, yPos+size-15) surface.DrawLine(xPos-size, yPos+size, xPos-size+15, yPos+size) surface.DrawLine(xPos+size, yPos+size, xPos+size, yPos+size-15) surface.DrawLine(xPos+size, yPos+size, xPos+size-15, yPos+size) if( txt != "" ) then surface.DrawLine( xPos+size, yPos+size, xPos+size+20, yPos+size+20 ) draw.WordBox(8, xPos+size+20, yPos+size+12, txt, "Default", Color(50,255,50, 160), Color(0,0,0, 255) ) end //-- Target rectangle with lines to the corners of the screen --// elseif (indinfo.Style == 31) then local size = 45 local bracket_length = 15 if( isInsideZone(xPos, yPos, 0, 0, screenWidth, screenHeight) ) then //--Corner brackets--// surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawLine(xPos-size, yPos-size, xPos-size, yPos-size+bracket_length) surface.DrawLine(xPos-size, yPos-size, xPos-size+bracket_length, yPos-size) surface.DrawLine(xPos+size, yPos-size, xPos+size, yPos-size+bracket_length) surface.DrawLine(xPos+size, yPos-size, xPos+size-bracket_length, yPos-size) surface.DrawLine(xPos-size, yPos+size, xPos-size, yPos+size-bracket_length) surface.DrawLine(xPos-size, yPos+size, xPos-size+bracket_length, yPos+size) surface.DrawLine(xPos+size, yPos+size, xPos+size, yPos+size-bracket_length) surface.DrawLine(xPos+size, yPos+size, xPos+size-bracket_length, yPos+size) //--Lines from the corner of the screen--// surface.DrawLine( 0, 0, xPos-size, yPos-size ) surface.DrawLine( screenWidth, 0, xPos+size, yPos-size ) surface.DrawLine( screenWidth, screenHeight, xPos+size, yPos+size ) surface.DrawLine( 0, screenHeight, xPos-size, yPos+size ) if( txt != "" ) then draw.WordBox(8, xPos+size+20, yPos+size+20, txt, "Default", Color(50,255,50, 160), Color(0,0,0, 255) ) end end //-- Targetting Triangle --// elseif (indinfo.Style == 40) then surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawLine(xPos-20, yPos-10, xPos+20, yPos-10) surface.DrawLine(xPos-20, yPos-10, xPos, yPos+10) surface.DrawLine(xPos+20, yPos-10, xPos, yPos+10) //-- Crosshair Style 1 --// elseif (indinfo.Style == 50) then surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawLine( xPos-20, yPos, xPos+20, yPos ) surface.DrawLine( xPos, yPos-20, xPos, yPos+20 ) //-- Crosshair Style 2 --// elseif (indinfo.Style == 51) then surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawLine(xPos, yPos-25, xPos, yPos-5) surface.DrawLine(xPos, yPos+25, xPos, yPos+5) surface.DrawLine(xPos-25, yPos, xPos-5, yPos) surface.DrawLine(xPos+25, yPos, xPos+5, yPos) //-- Crosshair Style 3 --// elseif (indinfo.Style == 52) then surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawLine( xPos-20, yPos, xPos+20, yPos ) surface.DrawLine( xPos, yPos-10, xPos, yPos+10 ) //-- The braces are now controlled by wire inputs in the Extended I/O indicators. --// //-- Left Brace, This should be controlled by wire inputs! surface.SetDrawColor(BColor.r, BColor.g, BColor.b, 160) surface.DrawLine( xPos-30, yPos-10, xPos-30, yPos+10 ) surface.DrawLine( xPos-30, yPos-10, xPos-25, yPos-10 ) surface.DrawLine( xPos-30, yPos+10, xPos-25, yPos+10 ) //-- Right Brace, This should be controlled by wire inputs! surface.DrawLine( xPos+30, yPos-10, xPos+30, yPos+10 ) surface.DrawLine( xPos+30, yPos-10, xPos+25, yPos-10 ) surface.DrawLine( xPos+30, yPos+10, xPos+25, yPos+10 ) //-- Crosshair with lines to edges of screen --// elseif (indinfo.Style == 53) then surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) //-- Lines to the edge of the screen surface.DrawLine( 0, yPos, xPos-20, yPos ) surface.DrawLine( xPos+20, yPos, screenWidth, yPos ) surface.DrawLine( xPos, 0, xPos, yPos-20 ) surface.DrawLine( xPos, yPos+20, xPos, screenHeight ) //--Inner Braces surface.DrawLine( xPos-10, yPos-20, xPos+10, yPos-20 ) surface.DrawLine( xPos-10, yPos+20, xPos+10, yPos+20 ) surface.DrawLine( xPos-20, yPos-10, xPos-20, yPos+10 ) surface.DrawLine( xPos+20, yPos-10, xPos+20, yPos+10 ) if( txt != "" ) then draw.WordBox(8, xPos+20, yPos+20, txt, "Default", Color(50,255,50, 160), Color(0,0,0, 255) ) end //-- Textured crosshair in the 'Ghost In The Shell' style --// //-- Lines to edge of screen also. --// elseif (indinfo.Style == 54) then surface.SetTexture(tex_sci_fi_1) local xSize = 256 local ySize = 256 local xOffset = 128 local yOffset = 128 //-- Texture is 256x256, ergo position needs to be offset by 128. surface.DrawTexturedRect( xPos-xOffset, yPos-yOffset, xSize, ySize ) //-- Lines to the edge of the screen to match the texture... surface.SetDrawColor(187, 215, 239, 160) surface.DrawLine( 0, yPos, xPos-xOffset, yPos ) surface.DrawLine( 0, yPos-1, xPos-xOffset, yPos-1 ) surface.DrawLine( xPos+xOffset, yPos, screenWidth, yPos ) surface.DrawLine( xPos+xOffset, yPos-1, screenWidth, yPos-1 ) surface.DrawLine( xPos, 0, xPos, yPos-yOffset ) surface.DrawLine( xPos-1, 0, xPos-1, yPos-yOffset ) surface.DrawLine( xPos, yPos+yOffset, xPos, screenHeight ) surface.DrawLine( xPos-1, yPos+yOffset, xPos-1, screenHeight ) //--Animating target marker (triangular)--// //--Offsets 100 from the normal indicators, so I have room to group types--// elseif( indinfo.Style == 100 ) then local frame = RealTime()*120 local point1x = xPos+(math.sin(math.rad(frame))*20) local point1y = yPos+(math.cos(math.rad(frame))*20) local point2x = xPos+(math.sin(math.rad(frame+120))*20) local point2y = yPos+(math.cos(math.rad(frame+120))*20) local point3x = xPos+(math.sin(math.rad(frame+240))*20) local point3y = yPos+(math.cos(math.rad(frame+240))*20) surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawLine( point1x, point1y, point2x, point2y ) surface.DrawLine( point2x, point2y, point3x, point3y ) surface.DrawLine( point3x, point3y, point1x, point1y ) if( txt != "" ) then draw.WordBox(8, xPos+20, yPos+20, txt, "Default", Color(50,255,50, 160), Color(0,0,0, 255) ) end //-----------------------------------------------------------------------------------------------// //-- [Extended I/O] [Extended I/O] [Extended I/O] [Extended I/O] [Extended I/O] [Extended I/O] --// //-----------------------------------------------------------------------------------------------// //-- These inputs have other IO functions on the SENT, so can access the exio values --// //-----------------------------------------------------------------------------------------------// //-- Targetting Rectangle --// elseif (indinfo.Style == 1000) then local size = 45 if( indinfo.exio_size != nil ) then size = indinfo.exio_size end if( size < 0 ) then size = 0 end surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 90) surface.DrawRect(xPos-size, yPos-size, size*2, size*2) surface.SetDrawColor(BColor.r, BColor.g, BColor.b, 160) surface.DrawLine(xPos-size, yPos-size, xPos-size, yPos-size+15) surface.DrawLine(xPos-size, yPos-size, xPos-size+15, yPos-size) surface.DrawLine(xPos+size, yPos-size, xPos+size, yPos-size+15) surface.DrawLine(xPos+size, yPos-size, xPos+size-15, yPos-size) surface.DrawLine(xPos-size, yPos+size, xPos-size, yPos+size-15) surface.DrawLine(xPos-size, yPos+size, xPos-size+15, yPos+size) surface.DrawLine(xPos+size, yPos+size, xPos+size, yPos+size-15) surface.DrawLine(xPos+size, yPos+size, xPos+size-15, yPos+size) if( txt != "" ) then surface.DrawLine( xPos+size, yPos+size, xPos+size+20, yPos+size+20 ) draw.WordBox(8, xPos+size+20, yPos+size+12, txt, "Default", Color(50,255,50, 160), Color(0,0,0, 255) ) end //-- Crosshair Style 3 --// elseif (indinfo.Style == 1001) then surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawLine( xPos-20, yPos, xPos+20, yPos ) surface.DrawLine( xPos, yPos-10, xPos, yPos+10 ) surface.SetDrawColor(BColor.r, BColor.g, BColor.b, 160) //-- Left Brace --// if( indinfo.exio_lbrace != nil ) and ( indinfo.exio_lbrace > 0 ) then surface.DrawLine( xPos-30, yPos-10, xPos-30, yPos+10 ) surface.DrawLine( xPos-30, yPos-10, xPos-25, yPos-10 ) surface.DrawLine( xPos-30, yPos+10, xPos-25, yPos+10 ) end //-- Right Brace --// if( indinfo.exio_rbrace != nil ) and ( indinfo.exio_rbrace > 0 ) then surface.DrawLine( xPos+30, yPos-10, xPos+30, yPos+10 ) surface.DrawLine( xPos+30, yPos-10, xPos+25, yPos-10 ) surface.DrawLine( xPos+30, yPos+10, xPos+25, yPos+10 ) end //-- Divided Box --// elseif (indinfo.Style == 1002) then if( indinfo.exio_width == nil ) then indinfo.exio_width = 200 //--Msg("[WW] exio_width has not been set yet... using default value of 200\n") errors = errors + 1 end if( indinfo.exio_height == nil ) then indinfo.exio_height = 200 //--Msg("[WW] exio_height has not been set yet... using default value of 200\n") errors = errors + 1 end if( indinfo.exio_x == nil ) then indinfo.exio_x = 50 //--Msg("[WW] exio_x has not been set yet... using default value of 50\n") errors = errors + 1 end if( indinfo.exio_y == nil ) then indinfo.exio_y = 50 //--Msg("[WW] exio_y has not been set yet... using default value of 50\n") errors = errors + 1 end local x = xPos - (indinfo.exio_width/2) local y = yPos - (indinfo.exio_height/2) xRef = math.Clamp( (indinfo.exio_x/100)*indinfo.exio_width, 0, indinfo.exio_width ) yRef = math.Clamp( (indinfo.exio_y/100)*indinfo.exio_height, 0, indinfo.exio_height ) surface.SetDrawColor(BColor.r, BColor.g, BColor.b, 160) surface.DrawRect( x, y, indinfo.exio_width, indinfo.exio_height ) surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 255) surface.DrawOutlinedRect( x, y, indinfo.exio_width, indinfo.exio_height ) surface.DrawLine( x+xRef, y, x+xRef, y+indinfo.exio_height ) surface.DrawLine( x, y+yRef, x+indinfo.exio_width, y+yRef ) end //-- manual draw mode, possibly -intensely- laggy...--// if( xEnd && yEnd ) then //--XY->XY Line mode --// if( indinfo.Style == 200 ) then surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawLine( xPos, yPos, xEnd, yEnd ) //--XY->XY Box mode --// elseif( indinfo.Style == 201 ) then local boxSizeX = xEnd-xPos local boxSizeY = yEnd-yPos local drawX = xPos local drawY = yPos if( boxSizeX < 0 ) then boxSizeX = xPos-xEnd drawX = xEnd end if( boxSizeY < 0 ) then boxSizeY = yPos-yEnd drawY = yEnd end surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) surface.DrawRect( drawX, drawY, boxSizeX, boxSizeY ) //--XY->XY Rounded Box mode --// elseif( indinfo.Style == 202 ) then local boxSizeX = xEnd-xPos local boxSizeY = yEnd-yPos local drawX = xPos local drawY = yPos if( boxSizeX < 0 ) then boxSizeX = xPos-xEnd drawX = xEnd end if( boxSizeY < 0 ) then boxSizeY = yPos-yEnd drawY = yEnd end surface.SetDrawColor(AColor.r, AColor.g, AColor.b, 160) draw.RoundedBox( 3, drawX, drawY, boxSizeX, boxSizeY, Color(255,255,255, 160) ) end end end else // Clear this from the table so we don't check again advhudindicators[index] = nil end end end //--if( errors > 0 ) then //-- draw.WordBox(8, 20, 20, "[Warning] "..errors.." indicators were missing information at render time! If this message does not go away - contact a developer! ", "Default", Color(50, 50, 75, 192), Color(255, 255, 255, 255)) //--end end hook.Add("HUDPaint", "DrawAdvHUDIndicators", DrawAdvHUDIndicators) local function AdvHUDFormatDescription( eindex ) // This is placed here so we don't have to update // the description more often than is necessary local indinfo = advhudindicators[eindex] advhudindicators[eindex].FullText = indinfo.Description if( indinfo.xPos == nil ) then indinfo.xPos = 0 end if( indinfo.yPos == nil ) then indinfo.yPos = 0 end if( indinfo.zPos == nil ) then indinfo.zPos = 0 end if (indinfo.ShowValue == 1) then // Percent advhudindicators[eindex].FullText = indinfo.Description.." "..string.format("%.1f", (indinfo.Factor or 0) * 100).."%" elseif (indinfo.ShowValue == 2) then // Value // Round to up to 2 places advhudindicators[eindex].FullText = indinfo.Description.." "..string.format("%g", math.Round((indinfo.Value or 0) * 100) / 100).."" end // Do any extra processing for certain HUD styles // so we aren't calculating this every frame surface.SetFont("Default") if( advhudindicators[eindex].FullText ) then indinfo.BoxWidth = surface.GetTextSize(advhudindicators[eindex].FullText) else indinfo.BoxWidth = 0 end end // Function to ensure that the respective table index is created before any elements are added or modified // The HUDIndicatorRegister umsg is *supposed* to arrive (and be processed) before all the others, // but for some reason (probably net lag or whatever) it isn't (TheApathetic) local function AdvCheckHITableElement(eindex) if (!advhudindicators[eindex]) then advhudindicators[eindex] = {} end end // UserMessage stuff local function AdvHUDIndicatorRegister() local eindex = net.ReadInt(16) AdvCheckHITableElement(eindex) advhudindicators[eindex].Description = net.ReadString() advhudindicators[eindex].ShowValue = net.ReadInt(16) local tempstyle = net.ReadInt(16) if (!advhudindicators[eindex].Style || advhudindicators[eindex].Style != tempstyle) then advhudindicators[eindex].Ready = false // Make sure that everything's ready first before drawing end advhudindicators[eindex].Style = tempstyle if (!advhudindicators[eindex].Factor) then // First-time register advhudindicators[eindex].Factor = 0 advhudindicators[eindex].Value = 0 advhudindicators[eindex].HideHUD = false advhudindicators[eindex].BoxWidth = 100 end AdvHUDFormatDescription( eindex ) //--Position method tacked on the end of the end -Moggie100--// advhudindicators[eindex].positionMethod = net.ReadInt(16) //--Depending on which input mode we're in, we'll get differing input here...--// if( net.ReadInt(16) == 1 ) then //--Start XYZ Position--// advhudindicators[eindex].xPos = net.ReadFloat() advhudindicators[eindex].yPos = net.ReadFloat() advhudindicators[eindex].zPos = net.ReadFloat() //--Start XYZ Position--// advhudindicators[eindex].xEnd = net.ReadFloat() advhudindicators[eindex].yEnd = net.ReadFloat() advhudindicators[eindex].zEnd = net.ReadFloat() advhudindicators[eindex].useWorldCoords = 1 else //--Position data tacked on the end.--// advhudindicators[eindex].xPos = net.ReadFloat() advhudindicators[eindex].yPos = net.ReadFloat() //--End XY Position--// advhudindicators[eindex].xEnd = net.ReadFloat() advhudindicators[eindex].yEnd = net.ReadFloat() end end net.Receive("AdvHUDIndicatorRegister", AdvHUDIndicatorRegister) local function AdvHUDIndicatorUnRegister() local eindex = net.ReadInt(16) advhudindicators[eindex] = nil end net.Receive("AdvHUDIndicatorUnRegister", AdvHUDIndicatorUnRegister) local function AdvHUDIndicatorFactor() local eindex = net.ReadInt(16) AdvCheckHITableElement(eindex) advhudindicators[eindex].Factor = net.ReadFloat() advhudindicators[eindex].Value = net.ReadFloat() AdvHUDFormatDescription( eindex ) end net.Receive("AdvHUDIndicatorFactor", AdvHUDIndicatorFactor) local function AdvHUDIndicatorHideHUD() local eindex = net.ReadInt(16) AdvCheckHITableElement(eindex) advhudindicators[eindex].HideHUD = net.ReadBool() end net.Receive("AdvHUDIndicatorHideHUD", AdvHUDIndicatorHideHUD) //--Forces the HUD data to be updated -Moggie100 local function AdvHUDIndicatorUpdatePosition() //--Get the table index local eindex = net.ReadInt(16) //--Ensure it exists and is ready to use AdvCheckHITableElement(eindex) //--Update the data for this indicator advhudindicators[eindex].xPos = net.ReadFloat() advhudindicators[eindex].yPos = net.ReadFloat() advhudindicators[eindex].positionMethod = net.ReadInt(16) advhudindicators[eindex].useWorldCoords = 0 end net.Receive("AdvHUDIndicatorUpdatePosition", AdvHUDIndicatorUpdatePosition) //--Forces the HUD data to be updated -Moggie100 local function AdvHUDIndicatorUpdatePositionTwo() //--Get the table index local eindex = net.ReadInt(16) //--Ensure it exists and is ready to use AdvCheckHITableElement(eindex) //--Update the data for this indicator advhudindicators[eindex].xEnd = net.ReadFloat() advhudindicators[eindex].yEnd = net.ReadFloat() advhudindicators[eindex].positionMethod = net.ReadInt(16) advhudindicators[eindex].useWorldCoords = 0 end net.Receive("AdvHUDIndicatorUpdatePositionTwo", AdvHUDIndicatorUpdatePositionTwo) //--BETA BETA BETA BETA BETA--// //--String data to set the FullText variable to!--// //--May just explode in everyone's faces!--// local function AdvHUDIndicator_UpdateSTRING() //--Get the table index local eindex = net.ReadInt(16) //--Ensure it exists and is ready to use AdvCheckHITableElement(eindex) //--Update the data for this indicator advhudindicators[eindex].Description = net.ReadString() end net.Receive("AdvHUDIndicator_STRING", AdvHUDIndicator_UpdateSTRING) //--Forces the HUD data to be updated from 3D position data -Moggie100 local function AdvHUDIndicatorUpdate3DPosition() //--Get the table index local eindex = net.ReadInt(16) //--Ensure it exists and is ready to use AdvCheckHITableElement(eindex) //--Update the data for this indicator advhudindicators[eindex].xPos = net.ReadFloat() advhudindicators[eindex].yPos = net.ReadFloat() advhudindicators[eindex].zPos = net.ReadFloat() advhudindicators[eindex].useWorldCoords = 1 end net.Receive("AdvHUDIndicatorUpdate3DPosition", AdvHUDIndicatorUpdate3DPosition) //--Forces the HUD data to be updated from 3D position data -Moggie100 local function AdvHUDIndicatorUpdate3DPositionTwo() //--Get the table index local eindex = net.ReadInt(16) //--Ensure it exists and is ready to use AdvCheckHITableElement(eindex) //--Update the data for this indicator advhudindicators[eindex].xEnd = net.ReadFloat() advhudindicators[eindex].yEnd = net.ReadFloat() advhudindicators[eindex].zEnd = net.ReadFloat() advhudindicators[eindex].useWorldCoords = 1 end net.Receive("AdvHUDIndicatorUpdate3DPositionTwo", AdvHUDIndicatorUpdate3DPositionTwo) //-- Seeing as this is the only function to set up colours, I'm calling it on a creation/update event even if its not this //-- indicator type. -Moggie100 local function AdvHUDIndicatorStylePercent() local eindex = net.ReadInt(16) local ainfo = string.Explode("|", net.ReadString()) local binfo = string.Explode("|", net.ReadString()) AdvCheckHITableElement(eindex) advhudindicators[eindex].AColor = { r = ainfo[1], g = ainfo[2], b = ainfo[3]} advhudindicators[eindex].BColor = { r = binfo[1], g = binfo[2], b = binfo[3]} end net.Receive("AdvHUDIndicatorStylePercent", AdvHUDIndicatorStylePercent) local function AdvHUDIndicatorStyleFullCircle() local eindex = net.ReadInt(16) AdvCheckHITableElement(eindex) advhudindicators[eindex].FullCircleAngle = net.ReadFloat() AdvHUDFormatDescription( eindex ) // So the gauge updates with FullCircleAngle factored in end net.Receive("AdvHUDIndicatorStyleFullCircle", AdvHUDIndicatorStyleFullCircle) //-- EXTENDED I/O UMSG HOOKS --// local function AdvHUDIndicator_EXIO() local eindex = net.ReadInt(16) AdvCheckHITableElement(eindex) local key = net.ReadInt(16); local value = net.ReadFloat(); if( key == 1 ) then //-- SIZE update --// advhudindicators[eindex].exio_size = value elseif( key == 2 ) then //-- LBrace update --// advhudindicators[eindex].exio_lbrace = value elseif( key == 3 ) then //-- RBrace update --// advhudindicators[eindex].exio_rbrace = value elseif( key == 4 ) then //-- Width update --// advhudindicators[eindex].exio_width = value elseif( key == 5 ) then //-- Height update --// advhudindicators[eindex].exio_height = value elseif( key == 6 ) then //-- Height update --// advhudindicators[eindex].exio_x = value elseif( key == 7 ) then //-- Height update --// advhudindicators[eindex].exio_y = value end //--Msg("[II] Updated EXIO value index=" ..key.. " value=" ..value.. "\n") end net.Receive("AdvHUDIndicator_EXIO", AdvHUDIndicator_EXIO) // Check for updates every 1/50 seconds local function AdvHUDIndicatorCheck() if (CurTime() < nextupdate) then return end nextupdate = CurTime() + 0.02 // Now check readiness for eindex,indinfo in pairs(advhudindicators) do //-- Force a description update --// AdvHUDFormatDescription(eindex) //-- NOW check readiness --// if (!indinfo.Ready) then advhudindicators[eindex].Ready = true // Don't need to do any additional checks end end end hook.Add("Think", "WireAdvHUDIndicatorCVarCheck", AdvHUDIndicatorCheck)
apache-2.0
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampParentsPageDetail.lua
1
1367
--[[ Title: RedSummerCampParentsPageDetail Author(s): pbb Date: 2021/7/9 Desc: the parent's detail page for red summer camp 2021 Use Lib: ------------------------------------------------------- local RedSummerCampParentsPageDetail = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/RedSummerCampParentsPageDetail.lua"); RedSummerCampParentsPageDetail.Show(); --]] local RedSummerCampParentsPageDetail = NPL.export(); local page RedSummerCampParentsPageDetail.ItemData={{}} function RedSummerCampParentsPageDetail.OnInit() page = document:GetPageCtrl(); end local pageConfig = { ["network"] = "RedSummerCampParentsPageDetailNetWork", ["charge"] = "RedSummerCampParentsPageDetailCharge" } function RedSummerCampParentsPageDetail.Show(name) local pageName = pageConfig[name] if not pageName then return end local params = { url = string.format("script/apps/Aries/Creator/Game/Tasks/RedSummerCamp/%s.html",pageName), name = "RedSummerCampParentsPageDetail.Show", isShowTitleBar = false, DestroyOnClose = true, style = CommonCtrl.WindowFrame.ContainerStyle, allowDrag = false, enable_esc_key = false, cancelShowAnimation = true, --app_key = 0, directPosition = true, align = "_fi", x = 0, y = 0, width = 0, height = 0, }; System.App.Commands.Call("File.MCMLWindowFrame", params); end
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Port_San_dOria/npcs/Crilde.lua
1
1395
----------------------------------- -- Area: Port San d'Oria -- NPC: Crilde -- Standard Info NPC ----------------------------------- package.loaded["scripts/globals/quests"] = nil; require("scripts/globals/quests"); package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(MagicmartFlyer,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x239); 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
rudiniemeijer/NodeMCU-Lua-WS2812-matrix-displays
demo-gameoflife.lua
1
1981
-- Game of Life for WS2812 RGB Matrix Display -- Copyright (c) 2017 Rudi Niemeijer -- Requires the use of WS2812 plot functions dofile("matrixutility.lc") nextdisp = ws2812.newBuffer(leds, 3) prevGen = {} function setup(a) autoRepaint(-1) clear() if a == nil then plot(10, 10, 1) plot(10, 11, 1) plot(11, 10, 1) plot(12, 10, 1) elseif a == "acorn" then plot(15, 9, 2) line(14, 11, 15, 11, 2) plot(17, 10, 2) line(18, 11, 20, 11, 2) elseif a == "r-pentomino" then line(16, 8, 17, 8, 2) line(15, 9, 16, 9, 2) plot(16, 10, 2) end repaint() end function st(x, y) if x < 1 or x > displayWidth or y < 1 or y > displayHeight then return 0 else if prevGen[x][y] then return 1 else return 0 end end end function iterate() change = false -- Copy to temprary table first, in order to speed -- up 'isset' actions later on for i = 1, displayWidth do prevGen[i] = {} for j = 1, displayHeight do prevGen[i][j] = isset(i, j) end tmr.wdclr() end for i = 1, displayWidth do for j = 1, displayHeight do neighbors = st(i , j + 1) + st(i , j - 1) + st(i + 1, j ) + st(i + 1, j + 1) + st(i + 1, j - 1) + st(i - 1, j ) + st(i - 1, j + 1) + st(i - 1, j - 1) if prevGen[i][j] then if neighbors < 2 then nextdisp:set(toLineair(i, j), {0,0,0}) end if neighbors == 2 or neighbors == 3 then nextdisp:set(toLineair(i, j), {0,1,0}) end -- lives on if neighbors > 3 then nextdisp:set(toLineair(i, j), {0,0,0}) end else if neighbors == 3 then nextdisp:set(toLineair(i, j), {1,0,0}) change = true end -- born end tmr.wdclr() end end disp:replace(nextdisp) repaint() if change == false then tmr.stop(1) print("done.") end end setup("acorn") tmr.alarm(1, 1000, tmr.ALARM_AUTO, iterate)
mit
Laterus/Darkstar-Linux-Fork
scripts/zones/Windurst_Waters/npcs/Pursuivant.lua
5
1040
----------------------------------- -- Area: Windurst Waters -- NPC: Pursuivant -- Type: Pursuivant -- @zone: 238 -- @pos: 113.971 -3.077 51.524 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0366); 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
madpilot78/ntopng
scripts/lua/rest/v2/reset/infrastructure/config.lua
1
1218
-- -- (C) 2020 - ntop.org -- dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path package.path = dirs.installdir .. "/pro/scripts/lua/enterprise/modules/?.lua;" .. package.path package.path = dirs.installdir .. "/scripts/lua/modules/import_export/?.lua;" .. package.path require "lua_utils" local plugins_utils = require("plugins_utils") local infrastructure_import_export = require("infrastructure_import_export") local json = require "dkjson" local rest_utils = require "rest_utils" local import_export_rest_utils = require "import_export_rest_utils" local auth = require "auth" -- -- Reset infrastructure Dashboard configuration -- Example: curl -u admin:admin http://localhost:3000/lua/rest/v2/reset/infrastructure/config.lua -- -- NOTE: in case of invalid login, no error is returned but redirected to login -- if not isAdministratorOrPrintErr() then rest_utils.answer(rest_utils.consts.err.not_granted) return end if not ntop.isEnterpriseL() then rest_utils.answer(rest_utils.consts.err.not_granted) return end local instances = {} instances["infrastructure"] = infrastructure_import_export:create() import_export_rest_utils.reset(instances)
gpl-3.0
TeamHypersomnia/Hypersomnia
hypersomnia/content/gfx/orange_charge.meta.lua
2
1949
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 80, light_colors = { "238 195 154 255", "255 0 21 255", "206 104 35 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Giddeus/npcs/Uu_Zhoumo.lua
1
1934
----------------------------------- -- Area: Giddeus -- NPC: Uu Zhoumo -- Involved in Mission 2-3 ----------------------------------- require("scripts/globals/keyitems"); package.loaded["scripts/zones/Giddeus/TextIDs"] = nil; require("scripts/zones/Giddeus/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) count = trade:getItemCount(); gil = trade:getGil(); if (trade:hasItemQty(ASPIR_KNIFE,1) and count == 1 and gil == 0) then player:startEvent(0x0029); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) pNation = player:getNation(); missionActive = player:hasCurrentMission(pNation); if (missionActive) then if (player:hasKeyItem(DULL_SWORD)) then player:startEvent(0x0028); elseif (player:hasKeyItem(SHIELD_OFFERING)) then player:startEvent(0x002a); elseif (player:getCurrentMission(1) == 7 and player:getVar("MissionStatus") == 13) then player:startEvent(0x002b); else player:startEvent(0x002c); end else player:startEvent(0x002c); 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 == 0x0028) then player:setVar("MissionStatus",13); player:delKeyItem(DULL_SWORD); elseif (csid == 0x0029) then player:tradeComplete(); player:setVar("MissionStatus",14); elseif (csid == 0x002a) then player:setVar("MissionStatus",12); player:delKeyItem(SHIELD_OFFERING); end end;
gpl-3.0
gleachkr/luakit
lib/editor.lua
3
2524
--- Text editor launching functionality. -- -- This module is primarily for use by other Lua modules that wish to -- allow the user to edit a particular text file. The default is to guess at the -- shell command to open a text editor from environment variables. To override -- the guess, replace `editor.cmd_string`. This can be done manually, as follows: -- -- local editor = require "editor" -- editor.editor_cmd = "urxvt -e nvim {file} +{line}" -- -- Before running the command, `{file}` will be replaced by the name of the file -- to be edited, and `{line}` will be replaced by the number of the line at -- which to begin editing. This module also supplies several builtin command -- strings, which can be used like this: -- -- local editor = require "editor" -- editor.editor_cmd = editor.builtin.urxvt -- -- @module editor -- @copyright 2017 Graham Leach-Krouse -- @copyright 2017 Aidan Holm <aidanholm@gmail.com> local _M = {} -- substitute in common values from the environment. local env_sub = function (s) local subs = { term = os.getenv("TERMINAL") or "xterm", editor = os.getenv("EDITOR") or "vim" } return string.gsub(s,"{(%w+)}", subs) end --- Built in substitution strings. Includes -- -- * `autodetect` (attempts to extract a terminal and editor from environment -- variables, and otherwise falls back to xterm and vim) -- * `xterm` -- * `urxvt` -- * `xdg_open` -- -- @type table -- @readonly _M.builtin = { autodetect = env_sub("{term} -e '{editor} {file} +{line}'"), xterm = env_sub("xterm -e {editor} {file} +{line}"), urxvt = env_sub("urxvt -e {editor} {file} +{line}"), xdg_open = env_sub("xdg-open {file}"), } --- The shell command used to open the editor. The default setting is to -- use `editor.builtin.xdg_open`. -- -- @type string -- @readwrite _M.editor_cmd = _M.builtin.xdg_open --- Edit a file in a terminal editor in a new window. -- -- * Can't yet handle files with special characters in their name. -- -- @tparam string file The path of the file to edit. -- @tparam[opt] number line The line number at which to begin editing. -- @tparam[opt] function callback A callback that fires when the process spawned -- by the editor command exits, of type @ref{process_exit_cb}. _M.edit = function (file, line, callback) local subs = { file = file, line = line or 1, } local cmd = string.gsub(_M.editor_cmd, "{(%w+)}", subs) luakit.spawn(cmd, callback) end return _M -- vim: et:sw=4:ts=8:sts=4:tw=80
gpl-3.0
hfjgjfg/PERSIANGUARD10
plugins/vote.lua
83
2129
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
pakoito/ToME---t-engine4
game/engines/default/engine/generator/map/Forest.lua
3
15084
-- TE4 - T-Engine 4 -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org require "engine.class" local Map = require "engine.Map" require "engine.Generator" local RoomsLoader = require "engine.generator.map.RoomsLoader" local Astar = require"engine.Astar" local DirectPath = require"engine.DirectPath" module(..., package.seeall, class.inherit(engine.Generator, RoomsLoader)) function _M:init(zone, map, level, data) engine.Generator.init(self, zone, map, level) self.data = data self.grid_list = self.zone.grid_list self.noise = data.noise or "fbm_perlin" self.zoom = data.zoom or 5 self.max_percent = data.max_percent or 80 self.sqrt_percent = data.sqrt_percent or 30 self.sqrt_percent2 = data.sqrt_percent2 self.hurst = data.hurst or nil self.lacunarity = data.lacunarity or nil self.octave = data.octave or 4 self.nb_spots = data.nb_spots or 10 self.do_ponds = data.do_ponds self.add_road = data.add_road or false self.end_road = data.end_road or false self.end_road_room = data.end_road_room if self.do_ponds then self.do_ponds.zoom = self.do_ponds.zoom or 5 self.do_ponds.octave = self.do_ponds.octave or 5 self.do_ponds.hurst = self.do_ponds.hurst or nil self.do_ponds.lacunarity = self.do_ponds.lacunarity or nil end RoomsLoader.init(self, data) end function _M:addPond(x, y, spots) local noise = core.noise.new(2, self.do_ponds.size.w, self.do_ponds.size.h) local nmap = {} local pmap = {} local lowest = {v=100, x=nil, y=nil} for i = 1, self.do_ponds.size.w do nmap[i] = {} pmap[i] = {} for j = 1, self.do_ponds.size.h do nmap[i][j] = noise:fbm_simplex(self.do_ponds.zoom * i / self.do_ponds.size.w, self.do_ponds.zoom * j / self.do_ponds.size.h, self.do_ponds.octave) if nmap[i][j] < lowest.v then lowest.v = nmap[i][j]; lowest.x = i; lowest.y = j end end end -- print("Lowest pond point", lowest.x, lowest.y," ::", lowest.v) local quadrant = function(i, j) local highest = {v=-100, x=nil, y=nil} local l = line.new(lowest.x, lowest.y, i, j) local lx, ly = l() while lx do -- print(lx, ly, nmap[lx][ly]) if nmap[lx] and nmap[lx][ly] and nmap[lx][ly] > highest.v then highest.v = nmap[lx][ly]; highest.x = lx; highest.y = ly end lx, ly = l() end -- print("Highest pond point", highest.x, highest.y," ::", highest.v) local split = (highest.v + lowest.v) local l = line.new(lowest.x, lowest.y, i, j) local lx, ly = l() while lx do local stop = true for _ = 1, #self.do_ponds.pond do if nmap[lx] and nmap[lx][ly] and nmap[lx][ly] < split * self.do_ponds.pond[_][1] then pmap[lx][ly] = self.do_ponds.pond[_][2] stop = false break end end if stop then break end lx, ly = l() end end for i = 1, self.do_ponds.size.w do quadrant(i, 1) quadrant(i, self.do_ponds.size.h) end for i = 1, self.do_ponds.size.h do quadrant(1, i) quadrant(self.do_ponds.size.w, i) end -- Smooth the pond for i = 1, self.do_ponds.size.w do for j = 1, self.do_ponds.size.h do local g1 = pmap[i-1] and pmap[i-1][j+1] local g2 = pmap[i] and pmap[i][j+1] local g3 = pmap[i+1] and pmap[i+1][j+1] local g4 = pmap[i-1] and pmap[i-1][j] local g6 = pmap[i+1] and pmap[i+1][j] local g7 = pmap[i-1] and pmap[i-1][j-1] local g8 = pmap[i] and pmap[i][j-1] local g9 = pmap[i+1] and pmap[i+1][j-1] local nb = (g1 and 1 or 0) + (g2 and 1 or 0) + (g3 and 1 or 0) + (g4 and 1 or 0) + (g6 and 1 or 0) + (g7 and 1 or 0) + (g8 and 1 or 0) + (g9 and 1 or 0) if nb < 4 then pmap[i][j] = nil end end end -- Draw the pond for i = 1, self.do_ponds.size.w do for j = 1, self.do_ponds.size.h do if pmap[i][j] then self.map(i-1+x, j-1+y, Map.TERRAIN, self:resolve(pmap[i][j], self.grid_list, true)) if self.map.room_map[i-1+x] and self.map.room_map[i-1+x][j-1+y] then self.map.room_map[i-1+x][j-1+y].special = "pond" end end end end spots[#spots+1] = {x=x, y=y, type="pond", subtype="pond"} end function _M:generate(lev, old_lev) for i = 0, self.map.w - 1 do for j = 0, self.map.h - 1 do self.map(i, j, Map.TERRAIN, self:resolve("floor")) end end -- make the noise local possible_spots = {} local noise = core.noise.new(2, self.hurst, self.lacunarity) for i = 1, self.map.w do for j = 1, self.map.h do local v = math.floor((noise[self.noise](noise, self.zoom * i / self.map.w, self.zoom * j / self.map.h, self.octave) / 2 + 0.5) * self.max_percent) if (v >= self.sqrt_percent and rng.percent(v)) or (v < self.sqrt_percent and rng.percent(math.sqrt(v))) then self.map(i-1, j-1, Map.TERRAIN, self:resolve("wall")) else if not self.sqrt_percent2 then self.map(i-1, j-1, Map.TERRAIN, self:resolve("floor")) else if (v >= self.sqrt_percent2) then self.map(i-1, j-1, Map.TERRAIN, self:resolve("floor2")) else self.map(i-1, j-1, Map.TERRAIN, self:resolve("floor")) end end if v >= self.sqrt_percent then possible_spots[#possible_spots+1] = {x=i-1, y=j-1, type="clearing", subtype="clearing"} end end end end local spots = {} local waypoints = {} self.spots = spots -- Add some spots for i = 1, self.nb_spots do local s = rng.tableRemove(possible_spots) if s then self.spots[#self.spots+1] = s end end if self.do_ponds then for i = 1, rng.range(self.do_ponds.nb[1], self.do_ponds.nb[2]) do self:addPond(rng.range(self.do_ponds.size.w, self.map.w - self.do_ponds.size.w), rng.range(self.do_ponds.size.h, self.map.h - self.do_ponds.size.h), spots) end end local nb_room = util.getval(self.data.nb_rooms or 0) local rooms = {} local end_room local axis = "x" local direction = 1 local ending -- get the axis and direction if self.data.edge_entrances then if self.data.edge_entrances[1] == 2 or self.data.edge_entrances[1] == 8 then axis = "y" else axis = "x" end if self.data.edge_entrances[1] == 2 or self.data.edge_entrances[1] == 4 then direction = 1 else direction = -1 end end -- Add the "requested" end room first (must be at least 66% into the level) print("End Room:",self.end_road_room) if self.end_road_room then print("Trying to load",self.end_road_room) local rroom, end_room_load end_room_load = self:loadRoom(self.end_road_room) local r = self:roomAlloc(end_room_load, #rooms+1, lev, old_lev, function(room, x, y) local far_enough = false if axis == "x" and direction == 1 then far_enough = x >= self.map.w*0.66 elseif axis == "x" and direction == -1 then far_enough = x <= self.map.w*0.33 elseif axis == "y" and direction == 1 then far_enough = y >= self.map.h*0.66 elseif axis == "y" and direction == -1 then far_enough = y <= self.map.h*0.33 end return far_enough end) if r then rooms[#rooms+1] = r end_room = r print("Successfully loaded the end room") end end while nb_room > 0 do local rroom while true do rroom = self.rooms[rng.range(1, #self.rooms)] if type(rroom) == "table" and rroom.chance_room then if rng.percent(rroom.chance_room) then rroom = rroom[1] break end else break end end local r = self:roomAlloc(rroom, #rooms+1, lev, old_lev) if r then rooms[#rooms+1] = r end nb_room = nb_room - 1 end local ux, uy, dx, dy if self.data.edge_entrances then ux, uy, dx, dy, spots = self:makeStairsSides(lev, old_lev, self.data.edge_entrances, spots) else ux, uy, dx, dy, spots = self:makeStairsInside(lev, old_lev, spots) end -- Create a road between the stairs via "waypoints" on the map -- The rule is that no waypoint may further away (in terms of the directional axis) than the previous point if self.add_road then if self.end_road then ending = true else ending = false end -- Add the up stairs as waypoint 1 if #waypoints > 0 then table.insert(waypoints,1,{x=ux,y=uy}) else waypoints[#waypoints+1] = {x=ux,y=uy} end -- Get 30 random locations local possible_waypoints = {} for i = 1, 30 do local x = rng.range(0,self.map.w-1) local y = rng.range(0,self.map.h-1) possible_waypoints[i] = {x=x,y=y} --print("Possible waypoint",i,x,y) end -- sort all the spots in order of upstairs to downstairs local start, finish if self.data.edge_entrances[1] == 2 then start = 0 finish = self.map.h table.sort(possible_waypoints,function(a, b) return b.y > a.y end) elseif self.data.edge_entrances[1] == 4 then start = 0 finish = self.map.w table.sort(possible_waypoints,function(a, b) return b.x > a.x end) elseif self.data.edge_entrances[1] == 6 then start = self.map.w finish = 0 table.sort(possible_waypoints,function(a, b) return b.x < a.x end) elseif self.data.edge_entrances[1] == 8 then start = self.map.h finish = 0 table.sort(possible_waypoints,function(a, b) return b.y < a.y end) end -- for i = 1, #possible_waypoints do -- spot = possible_waypoints[i] -- print("Possible waypoint",i,spot.x,spot.y) -- end print("Axis : ", axis, " from ", start," to ", finish) if ending and end_room then if axis == "x" then finish = end_room.x else finish = end_room.y end end for i = 1, #possible_waypoints do local s = possible_waypoints[i] print ("Possible waypoint",i,s.x,s.y) reason = self:checkValid(s,waypoints[#waypoints],axis,start,finish) if not self.map.room_map[s.x][s.y].special and reason == true then waypoints[#waypoints+1] = {x=s.x,y=s.y} print("Waypoint",i,s.x,s.y,"accepted") else print("Waypoint",i,s.x,s.y,"rejected: ",reason) end end -- if the downstairs exist, and the road's not ending here, add the downstairs if dx and not ending then waypoints[#waypoints+1] = {x=dx,y=dy} end if ending and self.end_road_room then waypoints[#waypoints+1] = {x=end_room.x,y=end_room.y} end --print("Amount of waypoints in road are: ", #waypoints) local i = 2 while i <= #waypoints do print("tunnel waypoint ",i-1," from ", waypoints[i-1].x, waypoints[i-1].y, " to ", waypoints[i].x,waypoints[i].y) self:makeRoad(waypoints[i-1].x,waypoints[i-1].y,waypoints[i].x,waypoints[i].y,id,"road") i = i + 1 end end return ux, uy, dx, dy, spots end function _M:makeRoad(x1,y1,x2,y2,id,terrain) local a = Astar.new(self.map, game:getPlayer()) local recheck = false path = a:calc(x1, y1, x2, y2, true, nil, function(x, y) if game.level.map:checkEntity(x, y, Map.TERRAIN, "air_level") then return false else return true end end, true) --No Astar path ? just be dumb and try direct line if not path then local d = DirectPath.new(game.level.map, game:getPlayer()) path = d:calc(x1, y1, x2, y2, false) print("A* couldn't find road to ",x2,y2,"from",x1,x2) end -- convert path to tunnel for i, pathnode in ipairs(path) do if not self.map.room_map[pathnode.x][pathnode.y].special then self.map(pathnode.x, pathnode.y, Map.TERRAIN, self:resolve(terrain)) end end end function _M:checkValid(spot, lastspot, axis, start, finish) -- Get the axis local mindistance = 2 --math.floor((start+finish)*0.07) local progress, measure, invert_measure,invert_progress, measure = 0,0,0,0 if axis == "x" then progress = lastspot.x measure = spot.x invert_measure = spot.y invert_progress = lastspot.y else progress = lastspot.y measure = spot.y invert_measure = spot.x invert_progress = lastspot.x end -- Get the direction if finish < start then progess = progress * -1 measure = measure * -1 finish = finish * -1 mindistance = mindistance * -1 end -- every next one must be at least X squares closer to the end, and not closer than 2*X to the end, -- and on the other axis may not be further than 20% of the distance of the map away if not (measure > progress+mindistance) then return "not enough progress from previous waypoint" end if not (measure < finish-mindistance*2) then return "measure too close to finish" end if not (math.abs(invert_progress - invert_measure) < math.abs(start-finish)*0.2) then return "on non-progress axis, the measure was more than 20% different from previous" end return measure > progress+mindistance and measure < finish-mindistance*2 and math.abs(invert_progress - invert_measure) < math.abs(start-finish)*0.2 end --- Create the stairs inside the level function _M:makeStairsInside(lev, old_lev, spots) -- Put down stairs local dx, dy if lev < self.zone.max_level or self.data.force_last_stair then while true do dx, dy = rng.range(1, self.map.w - 1), rng.range(1, self.map.h - 1) if not self.map:checkEntity(dx, dy, Map.TERRAIN, "block_move") and not self.map.room_map[dx][dy].special then self.map(dx, dy, Map.TERRAIN, self:resolve("down")) self.map.room_map[dx][dy].special = "exit" break end end end -- Put up stairs local ux, uy while true do ux, uy = rng.range(1, self.map.w - 1), rng.range(1, self.map.h - 1) if not self.map:checkEntity(ux, uy, Map.TERRAIN, "block_move") and not self.map.room_map[ux][uy].special then self.map(ux, uy, Map.TERRAIN, self:resolve("up")) self.map.room_map[ux][uy].special = "exit" break end end return ux, uy, dx, dy, spots end --- Create the stairs on the sides function _M:makeStairsSides(lev, old_lev, sides, spots) -- Put down stairs local dx, dy if lev < self.zone.max_level or self.data.force_last_stair then while true do if sides[2] == 4 then dx, dy = 0, rng.range(0, self.map.h - 1) elseif sides[2] == 6 then dx, dy = self.map.w - 1, rng.range(0, self.map.h - 1) elseif sides[2] == 8 then dx, dy = rng.range(0, self.map.w - 1), 0 elseif sides[2] == 2 then dx, dy = rng.range(0, self.map.w - 1), self.map.h - 1 end if not self.map.room_map[dx][dy].special then self.map(dx, dy, Map.TERRAIN, self:resolve("down")) self.map.room_map[dx][dy].special = "exit" break end end end -- Put up stairs local ux, uy while true do if sides[1] == 4 then ux, uy = 0, rng.range(0, self.map.h - 1) elseif sides[1] == 6 then ux, uy = self.map.w - 1, rng.range(0, self.map.h - 1) elseif sides[1] == 8 then ux, uy = rng.range(0, self.map.w - 1), 0 elseif sides[1] == 2 then ux, uy = rng.range(0, self.map.w - 1), self.map.h - 1 end if not self.map.room_map[ux][uy].special then self.map(ux, uy, Map.TERRAIN, self:resolve("up")) self.map.room_map[ux][uy].special = "exit" break end end return ux, uy, dx, dy, spots end
gpl-3.0
purebn/ShadowBot
plugins/pokedex.lua
626
1668
do local images_enabled = true; local function get_sprite(path) local url = "http://pokeapi.co/"..path print(url) local b,c = http.request(url) local data = json:decode(b) local image = data.image return image end local function callback(extra) send_msg(extra.receiver, extra.text, ok_cb, false) end local function send_pokemon(query, receiver) local url = "http://pokeapi.co/api/v1/pokemon/" .. query .. "/" local b,c = http.request(url) local pokemon = json:decode(b) if pokemon == nil then return 'No pokémon found.' end -- api returns height and weight x10 local height = tonumber(pokemon.height)/10 local weight = tonumber(pokemon.weight)/10 local text = 'Pokédex ID: ' .. pokemon.pkdx_id ..'\nName: ' .. pokemon.name ..'\nWeight: ' .. weight.." kg" ..'\nHeight: ' .. height.." m" ..'\nSpeed: ' .. pokemon.speed local image = nil if images_enabled and pokemon.sprites and pokemon.sprites[1] then local sprite = pokemon.sprites[1].resource_uri image = get_sprite(sprite) end if image then image = "http://pokeapi.co"..image local extra = { receiver = receiver, text = text } send_photo_from_url(receiver, image, callback, extra) else return text end end local function run(msg, matches) local receiver = get_receiver(msg) local query = URL.escape(matches[1]) return send_pokemon(query, receiver) end return { description = "Pokedex searcher for Telegram", usage = "!pokedex [Name/ID]: Search the pokédex for Name/ID and get info of the pokémon!", patterns = { "^!pokedex (.*)$", "^!pokemon (.+)$" }, run = run } end
gpl-2.0
TeamHypersomnia/Hypersomnia
hypersomnia/content/gfx/metropolis_torso_rifle_walk_1.meta.lua
2
2801
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.43000000715255737, amplification = 140, light_colors = { "89 31 168 255", "48 42 88 255", "61 16 123 0" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = -14, y = -13 }, rotation = 41 }, head = { pos = { x = -2, y = 2 }, rotation = 0 }, legs = { pos = { x = -2, y = 2 }, rotation = 0 }, primary_hand = { pos = { x = 5, y = 18 }, rotation = 0 }, secondary_hand = { pos = { x = 48, y = 13 }, rotation = 0 }, secondary_shoulder = { pos = { x = -10, y = 19 }, rotation = -138.81407165527344 }, shoulder = { pos = { x = 13, y = -13 }, rotation = -139 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Kazham/npcs/Mamerie.lua
37
1372
----------------------------------- -- Area: Kazham -- NPC: Mamerie -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MAMERIE_SHOP_DIALOG); stock = {0x11C1,62, -- Gysahl Greens 0x0348,7, -- Chocobo Feather 0x4278,11, -- Pet Food Alpha Biscuit 0x4279,82, -- Pet Food Beta Biscuit 0x45C4,82, -- Carrot Broth 0x45C6,695, -- Bug Broth 0x45C8,126, -- Herbal Broth 0x45CA,695, -- Carrion Broth 0x13D1,50784} -- Scroll of Chocobo Mazurka 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
Laterus/Darkstar-Linux-Fork
scripts/zones/Windurst_Waters/npcs/Panna-Donna.lua
5
1039
----------------------------------- -- Area: Windurst Waters -- NPC: Panna-Donna -- Type: Mission NPC -- @zone: 238 -- @pos: -57.502 -6 229.571 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0069); 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
pakoito/ToME---t-engine4
game/modules/tome/data/gfx/particles/necrotic-aura.lua
3
1474
-- ToME - Tales of Maj'Eyal -- Copyright (C) 2009 - 2014 Nicolas Casalini -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- Nicolas Casalini "DarkGod" -- darkgod@te4.org base_size = 32 radius = radius or 3 local toggle = false return { generator = function() local ad = rng.range(0, 360) local a = math.rad(ad) local dir = -math.rad(ad) local r = rng.range(10, 32 * radius) local dirchance = rng.chance(2) return { trail = 1, life = 30, size = 12, sizev = -0.3, sizea = 0, x = r * math.cos(a), xv = 0, xa = 0, y = r * math.sin(a), yv = 0, ya = 0, dir = dir, dirv = 0, dira = 0, vel = dirchance and 0.32 or -0.2, velv = 0, vela = dirchance and -0.01 or 0.01, r = 0, rv = 0, ra = 0, g = 0, gv = 0, ga = 0, b = 0, bv = 0, ba = 0, a = rng.range(40, 70) / 255, av = 0, aa = 0, } end, }, function(self) self.ps:emit(1) end, 7 * radius
gpl-3.0
tarantool/luarocks
src/luarocks/cmd/lint.lua
2
1460
--- Module implementing the LuaRocks "lint" command. -- Utility function that checks syntax of the rockspec. local lint = {} local util = require("luarocks.util") local download = require("luarocks.download") local fetch = require("luarocks.fetch") lint.help_summary = "Check syntax of a rockspec." lint.help_arguments = "<rockspec>" lint.help = [[ This is a utility function that checks the syntax of a rockspec. It returns success or failure if the text of a rockspec is syntactically correct. ]] function lint.command(flags, input) if not input then return nil, "Argument missing. "..util.see_help("lint") end local filename = input if not input:match(".rockspec$") then local err filename, err = download.download("rockspec", input:lower()) if not filename then return nil, err end end local rs, err = fetch.load_local_rockspec(filename) if not rs then return nil, "Failed loading rockspec: "..err end local ok = true -- This should have been done in the type checker, -- but it would break compatibility of other commands. -- Making 'lint' alone be stricter shouldn't be a problem, -- because extra-strict checks is what lint-type commands -- are all about. if not rs.description.license then util.printerr("Rockspec has no license field.") ok = false end return ok, ok or filename.." failed consistency checks." end return lint
mit
tarantool/luarocks
src/luarocks/util.lua
1
23445
--- Assorted utilities for managing tables, plus a scheduler for rollback functions. -- Does not requires modules directly (only as locals -- inside specific functions) to avoid interdependencies, -- as this is used in the bootstrapping stage of luarocks.core.cfg. local util = {} local core = require("luarocks.core.util") util.cleanup_path = core.cleanup_path util.split_string = core.split_string util.sortedpairs = core.sortedpairs util.deep_merge = core.deep_merge util.deep_merge_under = core.deep_merge_under util.popen_read = core.popen_read util.show_table = core.show_table util.printerr = core.printerr util.warning = core.warning util.keys = core.keys local unpack = unpack or table.unpack local scheduled_functions = {} local debug = require("debug") --- Schedule a function to be executed upon program termination. -- This is useful for actions such as deleting temporary directories -- or failure rollbacks. -- @param f function: Function to be executed. -- @param ... arguments to be passed to function. -- @return table: A token representing the scheduled execution, -- which can be used to remove the item later from the list. function util.schedule_function(f, ...) assert(type(f) == "function") local item = { fn = f, args = {...} } table.insert(scheduled_functions, item) return item end --- Unschedule a function. -- This is useful for cancelling a rollback of a completed operation. -- @param item table: The token representing the scheduled function that was -- returned from the schedule_function call. function util.remove_scheduled_function(item) for k, v in pairs(scheduled_functions) do if v == item then table.remove(scheduled_functions, k) return end end end --- Execute scheduled functions. -- Some calls create temporary files and/or directories and register -- corresponding cleanup functions. Calling this function will run -- these function, erasing temporaries. -- Functions are executed in the inverse order they were scheduled. function util.run_scheduled_functions() local fs = require("luarocks.fs") if fs.change_dir_to_root then fs.change_dir_to_root() end for i = #scheduled_functions, 1, -1 do local item = scheduled_functions[i] item.fn(unpack(item.args)) end end --- Produce a Lua pattern that matches precisely the given string -- (this is suitable to be concatenating to other patterns, -- so it does not include beginning- and end-of-string markers (^$) -- @param s string: The input string -- @return string: The equivalent pattern function util.matchquote(s) return (s:gsub("[?%-+*%[%].%%()$^]","%%%1")) end --- List of supported arguments. -- Arguments that take no parameters are marked with the boolean true. -- Arguments that take a parameter are marked with a descriptive string. -- Arguments that may take an empty string are described in quotes, -- (as in the value for --detailed="<text>"). -- For all other string values, it means the parameter is mandatory. local supported_flags = { ["all"] = true, ["api-key"] = "<key>", ["append"] = true, ["arch"] = "<arch>", ["bin"] = true, ["binary"] = true, ["branch"] = "<branch-name>", ["build-deps"] = true, ["chdir"] = "<path>", ["debug"] = true, ["deps"] = true, ["deps-mode"] = "<mode>", ["detailed"] = "\"<text>\"", ["dev"] = true, ["force"] = true, ["force-fast"] = true, ["from"] = "<server>", ["global"] = true, ["help"] = true, ["home"] = true, ["homepage"] = "\"<url>\"", ["index"] = true, ["issues"] = true, ["json"] = true, ["keep"] = true, ["labels"] = true, ["lib"] = "<library>", ["license"] = "\"<text>\"", ["list"] = true, ["local"] = true, ["local-tree"] = true, ["lr-bin"] = true, ["lr-cpath"] = true, ["lr-path"] = true, ["lua-dir"] = "<path>", ["lua-version"] = "<vers>", ["lua-versions"] = "<versions>", ["lua-ver"] = true, ["lua-incdir"] = true, ["lua-libdir"] = true, ["modules"] = true, ["mversion"] = true, ["namespace"] = "<namespace>", ["no-bin"] = true, ["no-doc"] = true, ["no-refresh"] = true, ["nodeps"] = true, ["old-versions"] = true, ["only-deps"] = true, ["only-from"] = "<server>", ["only-server"] = "<server>", ["only-sources"] = "<url>", ["only-sources-from"] = "<url>", ["outdated"] = true, ["output"] = "<file>", ["pack-binary-rock"] = true, ["porcelain"] = true, ["project-tree"] = "<tree>", ["quick"] = true, ["reset"] = true, ["rock-dir"] = true, ["rock-license"] = true, ["rock-namespace"] = true, ["rock-tree"] = true, ["rock-trees"] = true, ["rockspec"] = true, ["rockspec-format"] = "<ver>", ["scope"] = "<system|user|project>", ["server"] = "<server>", ["sign"] = true, ["skip-pack"] = true, ["source"] = true, ["summary"] = "\"<text>\"", ["system-config"] = true, ["tag"] = "<tag>", ["test-type"] = "<type>", ["temp-key"] = "<key>", ["timeout"] = "<seconds>", ["to"] = "<path>", ["tree"] = "<path>", ["unset"] = true, ["user-config"] = true, ["verbose"] = true, ["verify"] = true, ["version"] = true, } --- Extract flags from an arguments list. -- Given string arguments, extract flag arguments into a flags set. -- For example, given "foo", "--tux=beep", "--bla", "bar", "--baz", -- it would return the following: -- {["bla"] = true, ["tux"] = "beep", ["baz"] = true}, "foo", "bar". function util.parse_flags(...) local args = {...} local flags = {} local i = 1 local out = {} local state = "initial" while i <= #args do local flag = args[i]:match("^%-%-(.*)") if state == "initial" and flag == "" then state = "ignore_flags" elseif state == "initial" and flag then local var,val = flag:match("([a-z_%-]*)=(.*)") if val then local vartype = supported_flags[var] if type(vartype) == "string" then if val == "" and vartype:sub(1,1) ~= '"' then return { ERROR = "Invalid argument: parameter to flag --"..var.."="..vartype.." cannot be empty." } end flags[var] = val else if vartype then return { ERROR = "Invalid argument: flag --"..var.." does not take an parameter." } else return { ERROR = "Invalid argument: unknown flag --"..var.."." } end end else local var = flag local vartype = supported_flags[var] if type(vartype) == "string" then i = i + 1 local val = args[i] if not val then return { ERROR = "Invalid argument: flag --"..var.."="..vartype.." expects a parameter." } end if val:match("^%-%-.*") then return { ERROR = "Invalid argument: flag --"..var.."="..vartype.." expects a parameter (if you really want to pass "..val.." as an argument to --"..var..", use --"..var.."="..val..")." } else if val == "" and vartype:sub(1,1) ~= '"' then return { ERROR = "Invalid argument: parameter to flag --"..var.."="..vartype.." cannot be empty." } end flags[var] = val end elseif vartype == true then flags[var] = true else return { ERROR = "Invalid argument: unknown flag --"..var.."." } end end elseif state == "ignore_flags" or (state == "initial" and not flag) then table.insert(out, args[i]) end i = i + 1 end return flags, unpack(out) end local var_format_pattern = "%$%((%a[%a%d_]+)%)" -- Check if a set of needed variables are referenced -- somewhere in a list of definitions, warning the user -- about any unused ones. Each key in needed_set should -- appear as a $(XYZ) variable at least once as a -- substring of some value of var_defs. -- @param var_defs: a table with string keys and string -- values, containing variable definitions. -- @param needed_set: a set where keys are the names of -- needed variables. -- @param msg string: the warning message to display. function util.warn_if_not_used(var_defs, needed_set, msg) needed_set = core.make_shallow_copy(needed_set) for _, val in pairs(var_defs) do for used in val:gmatch(var_format_pattern) do needed_set[used] = nil end end for var, _ in pairs(needed_set) do util.warning(msg:format(var)) end end -- Output any entries that might remain in $(XYZ) format, -- warning the user that substitutions have failed. -- @param line string: the input string local function warn_failed_matches(line) local any_failed = false if line:match(var_format_pattern) then for unmatched in line:gmatch(var_format_pattern) do util.warning("unmatched variable " .. unmatched) any_failed = true end end return any_failed end --- Perform make-style variable substitutions on string values of a table. -- For every string value tbl.x which contains a substring of the format -- "$(XYZ)" will have this substring replaced by vars["XYZ"], if that field -- exists in vars. Only string values are processed; this function -- does not scan subtables recursively. -- @param tbl table: Table to have its string values modified. -- @param vars table: Table containing string-string key-value pairs -- representing variables to replace in the strings values of tbl. function util.variable_substitutions(tbl, vars) assert(type(tbl) == "table") assert(type(vars) == "table") local updated = {} for k, v in pairs(tbl) do if type(v) == "string" then updated[k] = v:gsub(var_format_pattern, vars) if warn_failed_matches(updated[k]) then updated[k] = updated[k]:gsub(var_format_pattern, "") end end end for k, v in pairs(updated) do tbl[k] = v end end function util.lua_versions(sort) local versions = { "5.1", "5.2", "5.3", "5.4" } local i = 0 if sort == "descending" then i = #versions + 1 return function() i = i - 1 return versions[i] end else return function() i = i + 1 return versions[i] end end end function util.lua_path_variables() local cfg = require("luarocks.core.cfg") local lpath_var = "LUA_PATH" local lcpath_var = "LUA_CPATH" local lv = cfg.lua_version:gsub("%.", "_") if lv ~= "5_1" then if os.getenv("LUA_PATH_" .. lv) then lpath_var = "LUA_PATH_" .. lv end if os.getenv("LUA_CPATH_" .. lv) then lcpath_var = "LUA_CPATH_" .. lv end end return lpath_var, lcpath_var end function util.starts_with(s, prefix) return s:sub(1,#prefix) == prefix end --- Print a line to standard output function util.printout(...) io.stdout:write(table.concat({...},"\t")) io.stdout:write("\n") end function util.title(msg, porcelain, underline) if porcelain then return end util.printout() util.printout(msg) util.printout((underline or "-"):rep(#msg)) util.printout() end function util.this_program(default) local i = 1 local last, cur = default, default while i do local dbg = debug.getinfo(i,"S") if not dbg then break end last = cur cur = dbg.source i=i+1 end local prog = last:sub(1,1) == "@" and last:sub(2) or last -- Check if we found the true path of a script that has a wrapper local lrdir, binpath = prog:match("^(.*)/lib/luarocks/rocks%-[0-9.]*/[^/]+/[^/]+(/bin/[^/]+)$") if lrdir then -- Return the wrapper instead return lrdir .. binpath end return prog end function util.deps_mode_help(program) local cfg = require("luarocks.core.cfg") return [[ --deps-mode=<mode> How to handle dependencies. Four modes are supported: * all - use all trees from the rocks_trees list for finding dependencies * one - use only the current tree (possibly set with --tree) * order - use trees based on order (use the current tree and all trees below it on the rocks_trees list) * none - ignore dependencies altogether. The default mode may be set with the deps_mode entry in the configuration file. The current default is "]]..cfg.deps_mode..[[". Type ']]..util.this_program(program or "luarocks")..[[' with no arguments to see your list of rocks trees. ]] end function util.see_help(command, program) return "See '"..util.this_program(program or "luarocks")..' help'..(command and " "..command or "").."'." end function util.announce_install(rockspec) local cfg = require("luarocks.core.cfg") local path = require("luarocks.path") local suffix = "" if rockspec.description and rockspec.description.license then suffix = " (license: "..rockspec.description.license..")" end util.printout(rockspec.name.." "..rockspec.version.." is now installed in "..path.root_dir(cfg.root_dir)..suffix) util.printout() end --- Collect rockspecs located in a subdirectory. -- @param versions table: A table mapping rock names to newest rockspec versions. -- @param paths table: A table mapping rock names to newest rockspec paths. -- @param unnamed_paths table: An array of rockspec paths that don't contain rock -- name and version in regular format. -- @param subdir string: path to subdirectory. local function collect_rockspecs(versions, paths, unnamed_paths, subdir) local fs = require("luarocks.fs") local dir = require("luarocks.dir") local path = require("luarocks.path") local vers = require("luarocks.core.vers") if fs.is_dir(subdir) then for file in fs.dir(subdir) do file = dir.path(subdir, file) if file:match("rockspec$") and fs.is_file(file) then local rock, version = path.parse_name(file) if rock then if not versions[rock] or vers.compare_versions(version, versions[rock]) then versions[rock] = version paths[rock] = file end else table.insert(unnamed_paths, file) end end end end end --- Get default rockspec name for commands that take optional rockspec name. -- @return string or (nil, string): path to the rockspec or nil and error message. function util.get_default_rockspec() local versions, paths, unnamed_paths = {}, {}, {} -- Look for rockspecs in some common locations. collect_rockspecs(versions, paths, unnamed_paths, ".") collect_rockspecs(versions, paths, unnamed_paths, "rockspec") collect_rockspecs(versions, paths, unnamed_paths, "rockspecs") if #unnamed_paths > 0 then -- There are rockspecs not following "name-version.rockspec" format. -- More than one are ambiguous. if #unnamed_paths > 1 then return nil, "Please specify which rockspec file to use." else return unnamed_paths[1] end else local fs = require("luarocks.fs") local dir = require("luarocks.dir") local basename = dir.base_name(fs.current_dir()) if paths[basename] then return paths[basename] end local rock = next(versions) if rock then -- If there are rockspecs for multiple rocks it's ambiguous. if next(versions, rock) then return nil, "Please specify which rockspec file to use." else return paths[rock] end else return nil, "Argument missing: please specify a rockspec to use on current directory." end end end -- Quote Lua string, analogous to fs.Q. -- @param s A string, such as "hello" -- @return string: A quoted string, such as '"hello"' function util.LQ(s) return ("%q"):format(s) end --- Normalize the --namespace flag and the user/rock syntax for namespaces. -- If a namespace is given in user/rock syntax, update the --namespace flag; -- If a namespace is given in --namespace flag, update the user/rock syntax. -- In case of conflicts, the user/rock syntax takes precedence. function util.adjust_name_and_namespace(ns_name, flags) assert(type(ns_name) == "string" or not ns_name) assert(type(flags) == "table") if not ns_name then return elseif ns_name:match("%.rockspec$") or ns_name:match("%.rock$") then return ns_name end local name, namespace = util.split_namespace(ns_name) if namespace then flags["namespace"] = namespace end if flags["namespace"] then name = flags["namespace"] .. "/" .. name end return name:lower() end -- Split name and namespace of a package name. -- @param ns_name a name that may be in "namespace/name" format -- @return string, string? - name and optionally a namespace function util.split_namespace(ns_name) local p1, p2 = ns_name:match("^([^/]+)/([^/]+)$") if p1 then return p2, p1 end return ns_name end function util.deep_copy(tbl) local copy = {} for k, v in pairs(tbl) do if type(v) == "table" then copy[k] = util.deep_copy(v) else copy[k] = v end end return copy end -- An ode to the multitude of JSON libraries out there... function util.require_json() local list = { "cjson", "dkjson", "json" } for _, lib in ipairs(list) do local json_ok, json = pcall(require, lib) if json_ok then pcall(json.use_lpeg) -- optional feature in dkjson return json_ok, json end end local errmsg = "Failed loading " for i, name in ipairs(list) do if i == #list then errmsg = errmsg .."and '"..name.."'. Use 'luarocks search <partial-name>' to search for a library and 'luarocks install <name>' to install one." else errmsg = errmsg .."'"..name.."', " end end return nil, errmsg end -- A portable version of fs.exists that can be used at early startup, -- before the platform has been determined and luarocks.fs has been -- initialized. function util.exists(file) local fd, _, code = io.open(file, "r") if code == 13 then -- code 13 means "Permission denied" on both Unix and Windows -- io.open on folders always fails with code 13 on Windows return true end if fd then fd:close() return true end return false end do local function Q(pathname) if pathname:match("^.:") then return pathname:sub(1, 2) .. '"' .. pathname:sub(3) .. '"' end return '"' .. pathname .. '"' end function util.check_lua_version(lua_exe, luaver) if not util.exists(lua_exe) then return nil end local cmd = 'io.write(_VERSION:sub(5))' -- Tarantool falls into the interactive mode if no script is -- given even when -e option is passed. if lua_exe:find('tarantool') then cmd = cmd .. ' os.exit()' end local lv, err = util.popen_read(Q(lua_exe) .. (' -e "%s"'):format(cmd)) if luaver and luaver ~= lv then return nil end local ljv if lv == "5.1" then local cmd = 'io.write(tostring(jit and jit.version:sub(8)))' -- Exit from the iteractive mode. See the comment above. if lua_exe:find('tarantool') then cmd = cmd .. ' os.exit()' end ljv = util.popen_read(Q(lua_exe) .. (' -e "%s"'):format(cmd)) if ljv == "nil" then ljv = nil end end return lv, ljv end local find_lua_bindir do local exe_suffix = (package.config:sub(1, 1) == "\\" and ".exe" or "") local function insert_lua_variants(names, luaver) local variants = { "lua" .. luaver .. exe_suffix, "lua" .. luaver:gsub("%.", "") .. exe_suffix, "lua-" .. luaver .. exe_suffix, "lua-" .. luaver:gsub("%.", "") .. exe_suffix, } for _, name in ipairs(variants) do names[name] = luaver table.insert(names, name) end end find_lua_bindir = function(prefix, luaver) local names = {} if luaver then insert_lua_variants(names, luaver) else for v in util.lua_versions("descending") do insert_lua_variants(names, v) end end if luaver == "5.1" or not luaver then table.insert(names, "luajit" .. exe_suffix) table.insert(names, "tarantool") end table.insert(names, "lua" .. exe_suffix) local bindirs = { prefix .. "/bin", prefix } local tried = {} for _, d in ipairs(bindirs) do for _, name in ipairs(names) do local lua_exe = d .. "/" .. name local is_wrapper, err = util.lua_is_wrapper(lua_exe) if is_wrapper == false then local lv, ljv = util.check_lua_version(lua_exe, luaver) if lv then return name, d, lv, ljv end elseif is_wrapper == true or err == nil then table.insert(tried, lua_exe) else table.insert(tried, string.format("%-13s (%s)", lua_exe, err)) end end end local interp = luaver and ("Lua " .. luaver .. " interpreter") or "Lua interpreter" return nil, interp .. " not found at " .. prefix .. "\n" .. "Tried:\t" .. table.concat(tried, "\n\t") end end function util.find_lua(prefix, luaver) local lua_interpreter, bindir, luajitver lua_interpreter, bindir, luaver, luajitver = find_lua_bindir(prefix, luaver) if not lua_interpreter then return nil, bindir end return { lua_version = luaver, luajit_version = luajitver, lua_interpreter = lua_interpreter, lua_dir = prefix, lua_bindir = bindir, } end end function util.lua_is_wrapper(interp) local fd, err = io.open(interp, "r") if not fd then return nil, err end local data, err = fd:read(1000) fd:close() if not data then return nil, err end return not not data:match("LUAROCKS_SYSCONFDIR") end function util.opts_table(type_name, valid_opts) local opts_mt = {} opts_mt.__index = opts_mt function opts_mt.type() return type_name end return function(opts) for k, v in pairs(opts) do local tv = type(v) if not valid_opts[k] then error("invalid option: "..k) end local vo, optional = valid_opts[k]:match("^(.-)(%??)$") if not (tv == vo or (optional == "?" and tv == nil)) then error("invalid type option: "..k.." - got "..tv..", expected "..vo) end end for k, v in pairs(valid_opts) do if (not v:find("?", 1, true)) and opts[k] == nil then error("missing option: "..k) end end return setmetatable(opts, opts_mt) end end return util
mit
tarantool/luarocks
src/luarocks/tools/patch.lua
1
21921
--- Patch utility to apply unified diffs. -- -- http://lua-users.org/wiki/LuaPatch -- -- (c) 2008 David Manura, Licensed under the same terms as Lua (MIT license). -- Code is heavily based on the Python-based patch.py version 8.06-1 -- Copyright (c) 2008 rainforce.org, MIT License -- Project home: http://code.google.com/p/python-patch/ . -- Version 0.1 local patch = {} local fs = require("luarocks.fs") local fun = require("luarocks.fun") local io = io local os = os local string = string local table = table local format = string.format -- logging local debugmode = false local function debug(_) end local function info(_) end local function warning(s) io.stderr:write(s .. '\n') end -- Returns boolean whether string s2 starts with string s. local function startswith(s, s2) return s:sub(1, #s2) == s2 end -- Returns boolean whether string s2 ends with string s. local function endswith(s, s2) return #s >= #s2 and s:sub(#s-#s2+1) == s2 end -- Returns string s after filtering out any new-line characters from end. local function endlstrip(s) return s:gsub('[\r\n]+$', '') end -- Returns shallow copy of table t. local function table_copy(t) local t2 = {} for k,v in pairs(t) do t2[k] = v end return t2 end local function exists(filename) local fh = io.open(filename) local result = fh ~= nil if fh then fh:close() end return result end local function isfile() return true end --FIX? local function string_as_file(s) return { at = 0, str = s, len = #s, eof = false, read = function(self, n) if self.eof then return nil end local chunk = self.str:sub(self.at, self.at + n - 1) self.at = self.at + n if self.at > self.len then self.eof = true end return chunk end, close = function(self) self.eof = true end, } end -- -- file_lines(f) is similar to f:lines() for file f. -- The main difference is that read_lines includes -- new-line character sequences ("\n", "\r\n", "\r"), -- if any, at the end of each line. Embedded "\0" are also handled. -- Caution: The newline behavior can depend on whether f is opened -- in binary or ASCII mode. -- (file_lines - version 20080913) -- local function file_lines(f) local CHUNK_SIZE = 1024 local buffer = "" local pos_beg = 1 return function() local pos, chars while 1 do pos, chars = buffer:match('()([\r\n].)', pos_beg) if pos or not f then break elseif f then local chunk = f:read(CHUNK_SIZE) if chunk then buffer = buffer:sub(pos_beg) .. chunk pos_beg = 1 else f = nil end end end if not pos then pos = #buffer elseif chars == '\r\n' then pos = pos + 1 end local line = buffer:sub(pos_beg, pos) pos_beg = pos + 1 if #line > 0 then return line end end end local function match_linerange(line) local m1, m2, m3, m4 = line:match("^@@ %-(%d+),(%d+) %+(%d+),(%d+)") if not m1 then m1, m3, m4 = line:match("^@@ %-(%d+) %+(%d+),(%d+)") end if not m1 then m1, m2, m3 = line:match("^@@ %-(%d+),(%d+) %+(%d+)") end if not m1 then m1, m3 = line:match("^@@ %-(%d+) %+(%d+)") end return m1, m2, m3, m4 end local function match_epoch(str) return str:match("[^0-9]1969[^0-9]") or str:match("[^0-9]1970[^0-9]") end function patch.read_patch(filename, data) -- define possible file regions that will direct the parser flow local state = 'header' -- 'header' - comments before the patch body -- 'filenames' - lines starting with --- and +++ -- 'hunkhead' - @@ -R +R @@ sequence -- 'hunkbody' -- 'hunkskip' - skipping invalid hunk mode local all_ok = true local lineends = {lf=0, crlf=0, cr=0} local files = {source={}, target={}, epoch={}, hunks={}, fileends={}, hunkends={}} local nextfileno = 0 local nexthunkno = 0 --: even if index starts with 0 user messages -- number hunks from 1 -- hunkinfo holds parsed values, hunkactual - calculated local hunkinfo = { startsrc=nil, linessrc=nil, starttgt=nil, linestgt=nil, invalid=false, text={} } local hunkactual = {linessrc=nil, linestgt=nil} info(format("reading patch %s", filename)) local fp if data then fp = string_as_file(data) else fp = filename == '-' and io.stdin or assert(io.open(filename, "rb")) end local lineno = 0 for line in file_lines(fp) do lineno = lineno + 1 if state == 'header' then if startswith(line, "--- ") then state = 'filenames' end -- state is 'header' or 'filenames' end if state == 'hunkbody' then -- skip hunkskip and hunkbody code until definition of hunkhead read if line:match"^[\r\n]*$" then -- prepend space to empty lines to interpret them as context properly line = " " .. line end -- process line first if line:match"^[- +\\]" then -- gather stats about line endings local he = files.hunkends[nextfileno] if endswith(line, "\r\n") then he.crlf = he.crlf + 1 elseif endswith(line, "\n") then he.lf = he.lf + 1 elseif endswith(line, "\r") then he.cr = he.cr + 1 end if startswith(line, "-") then hunkactual.linessrc = hunkactual.linessrc + 1 elseif startswith(line, "+") then hunkactual.linestgt = hunkactual.linestgt + 1 elseif startswith(line, "\\") then -- nothing else hunkactual.linessrc = hunkactual.linessrc + 1 hunkactual.linestgt = hunkactual.linestgt + 1 end table.insert(hunkinfo.text, line) -- todo: handle \ No newline cases else warning(format("invalid hunk no.%d at %d for target file %s", nexthunkno, lineno, files.target[nextfileno])) -- add hunk status node table.insert(files.hunks[nextfileno], table_copy(hunkinfo)) files.hunks[nextfileno][nexthunkno].invalid = true all_ok = false state = 'hunkskip' end -- check exit conditions if hunkactual.linessrc > hunkinfo.linessrc or hunkactual.linestgt > hunkinfo.linestgt then warning(format("extra hunk no.%d lines at %d for target %s", nexthunkno, lineno, files.target[nextfileno])) -- add hunk status node table.insert(files.hunks[nextfileno], table_copy(hunkinfo)) files.hunks[nextfileno][nexthunkno].invalid = true state = 'hunkskip' elseif hunkinfo.linessrc == hunkactual.linessrc and hunkinfo.linestgt == hunkactual.linestgt then table.insert(files.hunks[nextfileno], table_copy(hunkinfo)) state = 'hunkskip' -- detect mixed window/unix line ends local ends = files.hunkends[nextfileno] if (ends.cr~=0 and 1 or 0) + (ends.crlf~=0 and 1 or 0) + (ends.lf~=0 and 1 or 0) > 1 then warning(format("inconsistent line ends in patch hunks for %s", files.source[nextfileno])) end end -- state is 'hunkbody' or 'hunkskip' end if state == 'hunkskip' then if match_linerange(line) then state = 'hunkhead' elseif startswith(line, "--- ") then state = 'filenames' if debugmode and #files.source > 0 then debug(format("- %2d hunks for %s", #files.hunks[nextfileno], files.source[nextfileno])) end end -- state is 'hunkskip', 'hunkhead', or 'filenames' end local advance if state == 'filenames' then if startswith(line, "--- ") then if fun.contains(files.source, nextfileno) then all_ok = false warning(format("skipping invalid patch for %s", files.source[nextfileno+1])) table.remove(files.source, nextfileno+1) -- double source filename line is encountered -- attempt to restart from this second line end -- Accept a space as a terminator, like GNU patch does. -- Breaks patches containing filenames with spaces... -- FIXME Figure out what does GNU patch do in those cases. local match, rest = line:match("^%-%-%- ([^ \t\r\n]+)(.*)") if not match then all_ok = false warning(format("skipping invalid filename at line %d", lineno+1)) state = 'header' else if match_epoch(rest) then files.epoch[nextfileno + 1] = true end table.insert(files.source, match) end elseif not startswith(line, "+++ ") then if fun.contains(files.source, nextfileno) then all_ok = false warning(format("skipping invalid patch with no target for %s", files.source[nextfileno+1])) table.remove(files.source, nextfileno+1) else -- this should be unreachable warning("skipping invalid target patch") end state = 'header' else if fun.contains(files.target, nextfileno) then all_ok = false warning(format("skipping invalid patch - double target at line %d", lineno+1)) table.remove(files.source, nextfileno+1) table.remove(files.target, nextfileno+1) nextfileno = nextfileno - 1 -- double target filename line is encountered -- switch back to header state state = 'header' else -- Accept a space as a terminator, like GNU patch does. -- Breaks patches containing filenames with spaces... -- FIXME Figure out what does GNU patch do in those cases. local re_filename = "^%+%+%+ ([^ \t\r\n]+)(.*)$" local match, rest = line:match(re_filename) if not match then all_ok = false warning(format( "skipping invalid patch - no target filename at line %d", lineno+1)) state = 'header' else table.insert(files.target, match) nextfileno = nextfileno + 1 if match_epoch(rest) then files.epoch[nextfileno] = true end nexthunkno = 0 table.insert(files.hunks, {}) table.insert(files.hunkends, table_copy(lineends)) table.insert(files.fileends, table_copy(lineends)) state = 'hunkhead' advance = true end end end -- state is 'filenames', 'header', or ('hunkhead' with advance) end if not advance and state == 'hunkhead' then local m1, m2, m3, m4 = match_linerange(line) if not m1 then if not fun.contains(files.hunks, nextfileno-1) then all_ok = false warning(format("skipping invalid patch with no hunks for file %s", files.target[nextfileno])) end state = 'header' else hunkinfo.startsrc = tonumber(m1) hunkinfo.linessrc = tonumber(m2 or 1) hunkinfo.starttgt = tonumber(m3) hunkinfo.linestgt = tonumber(m4 or 1) hunkinfo.invalid = false hunkinfo.text = {} hunkactual.linessrc = 0 hunkactual.linestgt = 0 state = 'hunkbody' nexthunkno = nexthunkno + 1 end -- state is 'header' or 'hunkbody' end end if state ~= 'hunkskip' then warning(format("patch file incomplete - %s", filename)) all_ok = false -- os.exit(?) else -- duplicated message when an eof is reached if debugmode and #files.source > 0 then debug(format("- %2d hunks for %s", #files.hunks[nextfileno], files.source[nextfileno])) end end local sum = 0; for _,hset in ipairs(files.hunks) do sum = sum + #hset end info(format("total files: %d total hunks: %d", #files.source, sum)) fp:close() return files, all_ok end local function find_hunk(file, h, hno) for fuzz=0,2 do local lineno = h.startsrc for i=0,#file do local found = true local location = lineno for l, hline in ipairs(h.text) do if l > fuzz then -- todo: \ No newline at the end of file if startswith(hline, " ") or startswith(hline, "-") then local line = file[lineno] lineno = lineno + 1 if not line or #line == 0 then found = false break end if endlstrip(line) ~= endlstrip(hline:sub(2)) then found = false break end end end end if found then local offset = location - h.startsrc - fuzz if offset ~= 0 then warning(format("Hunk %d found at offset %d%s...", hno, offset, fuzz == 0 and "" or format(" (fuzz %d)", fuzz))) end h.startsrc = location h.starttgt = h.starttgt + offset for _=1,fuzz do table.remove(h.text, 1) table.remove(h.text, #h.text) end return true end lineno = i end end return false end local function load_file(filename) local fp = assert(io.open(filename)) local file = {} local readline = file_lines(fp) while true do local line = readline() if not line then break end table.insert(file, line) end fp:close() return file end local function find_hunks(file, hunks) for hno, h in ipairs(hunks) do find_hunk(file, h, hno) end end local function check_patched(file, hunks) local lineno = 1 local ok, err = pcall(function() if #file == 0 then error('nomatch', 0) end for hno, h in ipairs(hunks) do -- skip to line just before hunk starts if #file < h.starttgt then error('nomatch', 0) end lineno = h.starttgt for _, hline in ipairs(h.text) do -- todo: \ No newline at the end of file if not startswith(hline, "-") and not startswith(hline, "\\") then local line = file[lineno] lineno = lineno + 1 if #line == 0 then error('nomatch', 0) end if endlstrip(line) ~= endlstrip(hline:sub(2)) then warning(format("file is not patched - failed hunk: %d", hno)) error('nomatch', 0) end end end end end) -- todo: display failed hunk, i.e. expected/found return err ~= 'nomatch' end local function patch_hunks(srcname, tgtname, hunks) local src = assert(io.open(srcname, "rb")) local tgt = assert(io.open(tgtname, "wb")) local src_readline = file_lines(src) -- todo: detect linefeeds early - in apply_files routine -- to handle cases when patch starts right from the first -- line and no lines are processed. At the moment substituted -- lineends may not be the same at the start and at the end -- of patching. Also issue a warning about mixed lineends local srclineno = 1 local lineends = {['\n']=0, ['\r\n']=0, ['\r']=0} for hno, h in ipairs(hunks) do debug(format("processing hunk %d for file %s", hno, tgtname)) -- skip to line just before hunk starts while srclineno < h.startsrc do local line = src_readline() -- Python 'U' mode works only with text files if endswith(line, "\r\n") then lineends["\r\n"] = lineends["\r\n"] + 1 elseif endswith(line, "\n") then lineends["\n"] = lineends["\n"] + 1 elseif endswith(line, "\r") then lineends["\r"] = lineends["\r"] + 1 end tgt:write(line) srclineno = srclineno + 1 end for _,hline in ipairs(h.text) do -- todo: check \ No newline at the end of file if startswith(hline, "-") or startswith(hline, "\\") then src_readline() srclineno = srclineno + 1 else if not startswith(hline, "+") then src_readline() srclineno = srclineno + 1 end local line2write = hline:sub(2) -- detect if line ends are consistent in source file local sum = 0 for _,v in pairs(lineends) do if v > 0 then sum=sum+1 end end if sum == 1 then local newline for k,v in pairs(lineends) do if v ~= 0 then newline = k end end tgt:write(endlstrip(line2write) .. newline) else -- newlines are mixed or unknown tgt:write(line2write) end end end end for line in src_readline do tgt:write(line) end tgt:close() src:close() return true end local function strip_dirs(filename, strip) if strip == nil then return filename end for _=1,strip do filename=filename:gsub("^[^/]*/", "") end return filename end local function write_new_file(filename, hunk) local fh = io.open(filename, "wb") if not fh then return false end for _, hline in ipairs(hunk.text) do if not hline:sub(1,1) == "+" then return false, "malformed patch" end fh:write(hline:sub(2)) end fh:close() return true end local function patch_file(source, target, epoch, hunks, strip, create_delete) local create_file = false if create_delete then local is_src_epoch = epoch and #hunks == 1 and hunks[1].startsrc == 0 and hunks[1].linessrc == 0 if is_src_epoch or source == "/dev/null" then info(format("will create %s", target)) create_file = true end end if create_file then return write_new_file(fs.absolute_name(strip_dirs(target, strip)), hunks[1]) end source = strip_dirs(source, strip) local f2patch = source if not exists(f2patch) then f2patch = strip_dirs(target, strip) f2patch = fs.absolute_name(f2patch) if not exists(f2patch) then --FIX:if f2patch nil warning(format("source/target file does not exist\n--- %s\n+++ %s", source, f2patch)) return false end end if not isfile(f2patch) then warning(format("not a file - %s", f2patch)) return false end source = f2patch -- validate before patching local file = load_file(source) local hunkno = 1 local hunk = hunks[hunkno] local hunkfind = {} local validhunks = 0 local canpatch = false local hunklineno if not file then return nil, "failed reading file " .. source end if create_delete then if epoch and #hunks == 1 and hunks[1].starttgt == 0 and hunks[1].linestgt == 0 then local ok = os.remove(source) if not ok then return false end info(format("successfully removed %s", source)) return true end end find_hunks(file, hunks) local function process_line(line, lineno) if not hunk or lineno < hunk.startsrc then return false end if lineno == hunk.startsrc then hunkfind = {} for _,x in ipairs(hunk.text) do if x:sub(1,1) == ' ' or x:sub(1,1) == '-' then hunkfind[#hunkfind+1] = endlstrip(x:sub(2)) end end hunklineno = 1 -- todo \ No newline at end of file end -- check hunks in source file if lineno < hunk.startsrc + #hunkfind - 1 then if endlstrip(line) == hunkfind[hunklineno] then hunklineno = hunklineno + 1 else debug(format("hunk no.%d doesn't match source file %s", hunkno, source)) -- file may be already patched, but check other hunks anyway hunkno = hunkno + 1 if hunkno <= #hunks then hunk = hunks[hunkno] return false else return true end end end -- check if processed line is the last line if lineno == hunk.startsrc + #hunkfind - 1 then debug(format("file %s hunk no.%d -- is ready to be patched", source, hunkno)) hunkno = hunkno + 1 validhunks = validhunks + 1 if hunkno <= #hunks then hunk = hunks[hunkno] else if validhunks == #hunks then -- patch file canpatch = true return true end end end return false end local done = false for lineno, line in ipairs(file) do done = process_line(line, lineno) if done then break end end if not done then if hunkno <= #hunks and not create_file then warning(format("premature end of source file %s at hunk %d", source, hunkno)) return false end end if validhunks < #hunks then if check_patched(file, hunks) then warning(format("already patched %s", source)) elseif not create_file then warning(format("source file is different - %s", source)) return false end end if not canpatch then return true end local backupname = source .. ".orig" if exists(backupname) then warning(format("can't backup original file to %s - aborting", backupname)) return false end local ok = os.rename(source, backupname) if not ok then warning(format("failed backing up %s when patching", source)) return false end patch_hunks(backupname, source, hunks) info(format("successfully patched %s", source)) os.remove(backupname) return true end function patch.apply_patch(the_patch, strip, create_delete) local all_ok = true local total = #the_patch.source for fileno, source in ipairs(the_patch.source) do local target = the_patch.target[fileno] local hunks = the_patch.hunks[fileno] local epoch = the_patch.epoch[fileno] info(format("processing %d/%d:\t %s", fileno, total, source)) local ok = patch_file(source, target, epoch, hunks, strip, create_delete) all_ok = all_ok and ok end -- todo: check for premature eof return all_ok end return patch
mit
NPLPackages/paracraft
script/apps/Aries/Creator/Game/Neuron/Templates/example_blocks.lua
1
1399
-- 示例文件: NPL script file -- 立方体模型:{x,y,z,block_id} cube_models = { {1,1,1, 4}, {-1,1,1, 4}, {-1,1,-1, 4}, {1,1,-1, 4}, }; -- 在x,y,z的位置创建一个模型 -- @param model_data: 数据源 -- @param x,y,z: 原点 function CreateModel(model_data, x,y,z) for i, b in ipairs(model_data) do blocks.set(x+b[1], y+b[2], z+b[3], b[4]); end end -- entry function: function main(msg) -- 在当前积木的上面: 创建ID=4的3个积木 for i=3, 5 do -- 判断一下ID是否为0(空) if(blocks.get(this.x, this.y + i, this.z) == 0 ) then -- 使用Set方法在当前位置的上方一格创建 blocks.set(this.x, this.y + i, this.z, 4); end end -- 在当前位置创建 CreateModel(cube_models, this.x, this.y+4, this.z); -- 获取指定位置的脚本模块. 这里获取自己的. local my_script = blocks.getscript(this.x, this.y, this.z); -- 更改一下cube_models中的块ID for i, b in ipairs(my_script.cube_models) do b[4] = b[4] % 100 + 1; end -- 选择block_id==4的积木(拿在右手中) select(cube_models[1][4]); -- 运行一条指令: 设置当前时间为中午 [-1,1] cmd("/time 0"); -- 显示字幕 movie.text("方块功能演示:每触发一次会改变周围的积木") -- 休眠5秒, 本方块不再接受任何请求,5秒后如果再次激活,每次创建的模型会不一样 this:Sleep(5); end
gpl-2.0
RyMarq/Zero-K
scripts/assaultcruiser.lua
8
4064
include 'constants.lua' -------------------------------------------------------------------- --pieces -------------------------------------------------------------------- local base, lowerhull, upperhull, antenna, radarbase, radardish = piece('base', 'lowerhull', 'upperhull', 'antenna', 'radarbase', 'radardish') local wake1, wake2 = piece('wake1', 'wake2') local turretPrefixes = {"fl", "fr", "sl", "sr", "ml", "mr"} local turretPieces = {} local gunStates = {} -- generate turretPieces table for i=2,7 do turretPieces[i] = {} local array = turretPieces[i] array.turret = piece(turretPrefixes[i-1].."turret") array.pivot = piece(turretPrefixes[i-1].."pivot") array.barrel = {} array.barrel[0] = piece(turretPrefixes[i-1].."barrel1") array.barrel[1] = piece(turretPrefixes[i-1].."barrel2") array.flare = {} array.flare[0] = piece(turretPrefixes[i-1].."flare1") array.flare[1] = piece(turretPrefixes[i-1].."flare2") gunStates[i] = 0 end -------------------------------------------------------------------- --constants -------------------------------------------------------------------- local smokePiece = {lowerhull, radarbase, upperhull} local SIG_RESTORE = 1 local SIG_MOVE = 2 local RESTORE_DELAY = 5000 local TURRET_PITCH_SPEED = math.rad(90) local TURRET_YAW_SPEED = math.rad(180) local RECOIL_DISTANCE = -3 local RECOIL_RESTORE_SPEED = 2.5 -------------------------------------------------------------------- --variables -------------------------------------------------------------------- local gun = {1, 1, 1} local gunHeading = {0, 0, 0} local dead = false function script.Create() Turn(turretPieces[4].turret, y_axis, math.rad(180)) Turn(turretPieces[5].turret, y_axis, math.rad(180)) Spin(radardish, y_axis, math.rad(100)) StartThread(GG.Script.SmokeUnit, unitID, smokePiece) end local function RestoreAfterDelay() Signal(SIG_RESTORE) SetSignalMask(SIG_RESTORE) Sleep(RESTORE_DELAY) if dead then return false end for i=2,7 do if i == 4 or i == 5 then Turn(turretPieces[i].turret, y_axis, math.pi, math.rad(35)) else Turn(turretPieces[i].turret, y_axis, 0, math.rad(35)) end Turn(turretPieces[i].pivot, x_axis, 0, math.rad(15)) end end local function Wake() Signal(SIG_MOVE) SetSignalMask(SIG_MOVE) while true do EmitSfx(wake1, 2) EmitSfx(wake2, 2) Sleep(200) end end function script.StartMoving() StartThread(Wake) end function script.StopMoving() Signal(SIG_MOVE) end function script.AimWeapon(num, heading, pitch) if dead or (num == 1) then return false end local SIG_Aim = 2^num Signal(SIG_Aim) SetSignalMask(SIG_Aim) Turn(turretPieces[num].turret, y_axis, heading, TURRET_YAW_SPEED) Turn(turretPieces[num].pivot, x_axis, -pitch, TURRET_PITCH_SPEED) WaitForTurn(turretPieces[num].turret, y_axis) WaitForTurn(turretPieces[num].pivot, x_axis) StartThread(RestoreAfterDelay) return true end function script.FireWeapon(num) end function script.Shot(num) local gun_num = gunStates[num] local barrel = turretPieces[num].barrel[gun_num] local flare = turretPieces[num].flare[gun_num] local toEmit = (num <= 5) and 1024 or 1025 EmitSfx(flare, toEmit) if (num <= 5) then Move(barrel, z_axis, RECOIL_DISTANCE) Move(barrel, z_axis, 0, RECOIL_RESTORE_SPEED) end gunStates[num] = 1 - gunStates[num] end function script.AimFromWeapon(num) if num == 1 then return base end return turretPieces[num].turret end function script.QueryWeapon(num) if num == 1 then return base end return turretPieces[num].flare[gunStates[num]] end local function ExplodeTurret(num, severity) end --not actually called; copypasta into Killed() local function DeathAnim() dead = true end function script.Killed(recentDamage, maxHealth) local severity = recentDamage/maxHealth if severity < 0.25 then DeathAnim() Explode(lowerhull, SFX.NONE) Explode(upperhull, SFX.NONE) return 1 elseif severity < 0.5 then DeathAnim() Explode(lowerhull, SFX.NONE) Explode(upperhull, SFX.NONE) return 1 else Explode(lowerhull, SFX.SHATTER) Explode(upperhull, SFX.SHATTER) return 2 end end
gpl-2.0
RyMarq/Zero-K
LuaUI/Widgets/gui_savegame.lua
2
16703
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Save Game Menu", desc = "bla", author = "KingRaptor", date = "2016.11.24", license = "GNU GPL, v2 or later", layer = -9999, enabled = true -- loaded by default? } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local SAVEGAME_BUTTON_HEIGHT = 128 local SAVE_DIR = "Saves" local SAVE_DIR_LENGTH = string.len(SAVE_DIR) + 2 local AUTOSAVE_DIR = SAVE_DIR .. "/auto" local MAX_SAVES = 999 local LOAD_GAME_STRING = "loadFilename " local SAVE_TYPE = (Spring.Utilities.IsCurrentVersionNewerThan(104, 1322) and "save ") or "luasave " -- https://springrts.com/mantis/view.php?id=6219 -- https://springrts.com/mantis/view.php?id=6222 -------------------------------------------------------------------------------- -- Chili elements -------------------------------------------------------------------------------- local Chili local Window local Control local Panel local Grid local StackPanel local ScrollPanel local TextBox local Label local Button local mainWindow -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- options_path = 'Settings/Misc/Autosave' options = { enableautosave = { name = 'Enable Autosave', type = 'bool', value = false, simpleMode = true, everyMode = true, }, autosaveFrequency = { name = 'Autosave Frequency (minutes)', type = 'number', min = 1, max = 60, step = 1, value = 10, simpleMode = true, everyMode = true, }, } -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- Makes a control grey for disabled, or whitish for enabled local function SetControlGreyout(control, state) if state then control.backgroundColor = {0.4, 0.4, 0.4, 1} control.font.color = {0.4, 0.4, 0.4, 1} control:Invalidate() else control.backgroundColor = {.8,.8,.8,1} control.font.color = nil control:Invalidate() end end local function WriteDate(dateTable) return string.format("%02d/%02d/%04d", dateTable.day, dateTable.month, dateTable.year) .. " " .. string.format("%02d:%02d:%02d", dateTable.hour, dateTable.min, dateTable.sec) end local function SecondsToClock(seconds) local seconds = tonumber(seconds) if seconds <= 0 then return "00:00"; else hours = string.format("%02d", math.floor(seconds/3600)); mins = string.format("%02d", math.floor(seconds/60 - (hours*60))); secs = string.format("%02d", math.floor(seconds - hours*3600 - mins *60)); if seconds >= 3600 then return hours..":"..mins..":"..secs else return mins..":"..secs end end end local function DisposeWindow() if mainWindow then mainWindow:Dispose() mainWindow = nil end end local function trim(str) return str:match'^()%s*$' and '' or str:match'^%s*(.*%S)' end -------------------------------------------------------------------------------- -- Savegame utlity functions -------------------------------------------------------------------------------- -- FIXME: currently unused as it doesn't seem to give the correct order local function SortSavesByDate(a, b) if a == nil or b == nil then return false end --Spring.Echo(a.id, b.id, a.date.hour, b.date.hour, a.date.hour>b.date.hour) if a.date.year > b.date.year then return true end if a.date.yday > b.date.yday then return true end if a.date.hour > b.date.hour then return true end if a.date.min > b.date.min then return true end if a.date.sec > b.date.sec then return true end return false end local function SortSavesByFilename(a, b) if a == nil or b == nil then return false end if a.filename and b.filename then return a.filename < b.filename end return false end local function GetSaveExtension(path) if VFS.FileExists(path .. ".ssf") then return ".ssf" end return VFS.FileExists(path .. ".slsf") and ".slsf" end local function GetSaveWithExtension(path) local ext = GetSaveExtension(path) return ext and path .. ext end -- Returns the data stored in a save file local function GetSave(path) local ret = nil local success, err = pcall(function() local saveData = VFS.Include(path) saveData.filename = string.sub(path, SAVE_DIR_LENGTH, -5) -- pure filename without directory or extension saveData.path = path ret = saveData end) if (not success) then Spring.Log(widget:GetInfo().name, LOG.ERROR, "Error getting save " .. path .. ": " .. err) else local engineSaveFilename = GetSaveWithExtension(string.sub(path, 1, -5)) if not engineSaveFilename then --Spring.Log(widget:GetInfo().name, LOG.ERROR, "Save " .. engineSaveFilename .. " does not exist") return nil else return ret end end end -- Loads the list of save files and their contents local function GetSaves() Spring.CreateDir(SAVE_DIR) local saves = {} local savefiles = VFS.DirList(SAVE_DIR, "*.lua") for i = 1, #savefiles do local path = savefiles[i] local saveData = GetSave(path) if saveData then saves[#saves + 1] = saveData end end table.sort(saves, SortSavesByFilename) return saves end -- e.g. if save slots 1, 2, 5, and 7 are used, return 3 -- only use for save name fallback local function FindFirstEmptySaveSlot() for i = 0, MAX_SAVES do local num = string.format("%03d", i) if not VFS.FileExists(SAVE_DIR .. "/save" .. num .. ".lua") then return i end end return MAX_SAVES end local function GetSaveDescText(saveFile) if not saveFile then return "" end return (saveFile.description or "no description") .. "\n" .. saveFile.gameName .. " " .. saveFile.gameVersion .. "\n" .. saveFile.map .. "\n" .. (WG.Translate("interface", "time_ingame") or "Ingame time").. ": " .. SecondsToClock((saveFile.totalGameframe or saveFile.gameframe or 0)/30) .. "\n" .. WriteDate(saveFile.date) end local function RemoveAllSaveControls() for i=1,#saveControls do saveControls[i].container:Dispose() end saveControls = {} end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local function SaveGame(filename, description, requireOverwrite) local success, err = pcall( function() Spring.CreateDir(SAVE_DIR) filename = (filename and trim(filename)) or ("save" .. string.format("%03d", FindFirstEmptySaveSlot())) path = SAVE_DIR .. "/" .. filename .. ".lua" local saveData = {} --saveData.filename = filename saveData.date = os.date('*t') saveData.description = description or "No description" saveData.gameName = Game.gameName saveData.gameVersion = Game.gameVersion saveData.engineVersion = Spring.Utilities.GetEngineVersion() saveData.map = Game.mapName saveData.gameID = (Spring.GetGameRulesParam("save_gameID") or Game.gameID) saveData.gameframe = Spring.GetGameFrame() saveData.totalGameframe = Spring.GetGameFrame() + (Spring.GetGameRulesParam("totalSaveGameFrame") or 0) saveData.playerName = Spring.GetPlayerInfo(Spring.GetMyPlayerID(), false) table.save(saveData, path) -- TODO: back up existing save? --if VFS.FileExists(SAVE_DIR .. "/" .. filename) then --end if requireOverwrite then Spring.SendCommands(SAVE_TYPE .. filename .. " -y") else Spring.SendCommands(SAVE_TYPE .. filename) end Spring.Log(widget:GetInfo().name, LOG.INFO, "Saved game to " .. path) DisposeWindow() end ) if (not success) then Spring.Log(widget:GetInfo().name, LOG.ERROR, "Error saving game: " .. err) end end local function LoadGameByFilename(filename) local saveData = GetSave(SAVE_DIR .. '/' .. filename .. ".lua") if saveData then if Spring.GetMenuName and Spring.SendLuaMenuMsg and Spring.GetMenuName() then Spring.SendLuaMenuMsg(LOAD_GAME_STRING .. filename) else local ext = GetSaveExtension(SAVE_DIR .. '/' .. filename) if not ext then Spring.Log(widget:GetInfo().name, LOG.ERROR, "Error loading game: cannot find save file.") return end local success, err = pcall( function() -- This should perhaps be handled in chobby first? --Spring.Log(widget:GetInfo().name, LOG.INFO, "Save file " .. path .. " loaded") local script = [[ [GAME] { SaveFile=__FILE__; IsHost=1; OnlyLocal=1; MyPlayerName=__PLAYERNAME__; } ]] script = script:gsub("__FILE__", filename .. ext) script = script:gsub("__PLAYERNAME__", saveData.playerName) Spring.Reload(script) end ) if (not success) then Spring.Log(widget:GetInfo().name, LOG.ERROR, "Error loading game: " .. err) end end else Spring.Log(widget:GetInfo().name, LOG.ERROR, "Save game " .. filename .. " not found") end if saveFilenameEdit then saveFilenameEdit:SetText(filename) end end local function DeleteSave(filename) if not filename then Spring.Log(widget:GetInfo().name, LOG.ERROR, "No filename specified for save deletion") end local success, err = pcall(function() local pathNoExtension = SAVE_DIR .. "/" .. filename os.remove(pathNoExtension .. ".lua") local saveFilePath = GetSaveWithExtension(pathNoExtension) if saveFilePath then os.remove(saveFilePath) end end) if (not success) then Spring.Log(widget:GetInfo().name, LOG.ERROR, "Error deleting save " .. filename .. ": " .. err) end end -------------------------------------------------------------------------------- -- Save/Load UI -------------------------------------------------------------------------------- local function SaveLoadConfirmationDialogPopup(filename, saveMode, description) local text if saveMode then text = WG.Translate("interface", "save_overwrite_confirm") or ("Save \"" .. filename .. "\" already exists. Overwrite?") else text = WG.Translate("interface", "load_confirm") or ("Loading will lose any unsaved progress.\nDo you wish to continue?") end local yesFunc = function() if (saveMode) then DeleteSave(filename) SaveGame(filename, description, true) -- TODO refresh UI else LoadGameByFilename(filename) end end WG.crude.MakeExitConfirmWindow(text, yesFunc, 78, true, false) end local function PromptSave(filename, description) filename = filename or saveFilenameEdit.text filename = trim(filename) filename = string.gsub(filename, " ", "_") local saveExists = filename and VFS.FileExists(SAVE_DIR .. "/" .. filename .. ".lua") or false if saveExists then SaveLoadConfirmationDialogPopup(filename, true) else SaveGame(filename, description) WG.crude.KillSubWindow(false) end end local function GetButtonYPos(index) return (index - 1)*SAVEGAME_BUTTON_HEIGHT + 4 end local function UpdateSaveButtonPositions(container) for i = 1, #container.children do local child = container.children[i] child:SetPos(child.x, GetButtonYPos(#container.children - i + 1)) -- assume reverse order, to match the ordering of the original save buttons end end -- Makes a button for a save game on the save/load screen local function AddSaveEntryButton(parent, saveFile, position, saveMode) local controlsEntry = {filename = saveFile and saveFile.filename} local holder = Control:New { name = "save_" .. saveFile.filename, height = SAVEGAME_BUTTON_HEIGHT, width = "100%", y = GetButtonYPos(position), x = 0, parent = parent, } local button = Button:New { parent = holder, x = 0, right = (saveFile and 96 + 8 or 0) + 0, y = 0, bottom = 0, caption = "", OnClick = { function(self) if saveMode then PromptSave(saveFile.filename, saveFile.description) else SaveLoadConfirmationDialogPopup(saveFile.filename, false) end end } } --controlsEntry.stack = StackPanel:New { -- parent = controlsEntry.button, -- height = "100%", -- width = "100%", -- orientation = "vertical", -- resizeItems = false, -- autoArrangeV = false, --} local titleLabel = Label:New { parent = button, caption = saveFile and saveFile.filename, valign = "center", x = 8, y = 2, font = { size = 16 }, } local descTextbox = TextBox:New { parent = button, x = 8, y = 24, right = 8, bottom = 8, text = GetSaveDescText(saveFile), font = { size = 14 }, } local deleteButton = Button:New { parent = holder, width = 96, right = 0, y = 4, bottom = 4, caption = WG.Translate("interface", "delete") or "Delete", --backgroundColor = {0.4,0.4,0.4,1}, OnClick = { function(self) WG.crude.MakeExitConfirmWindow("Are you sure you want to delete this save?", function() DeleteSave(saveFile.filename) holder:Dispose() UpdateSaveButtonPositions(parent) end, 78, false, false) end } } return controlsEntry end -- Generates the buttons for the savegames on the save/load screen local function FillSaveStackWithSaves(parent, saves, saveMode) for i = #saves, 1, -1 do AddSaveEntryButton(parent, saves[i], i, saveMode) end end -------------------------------------------------------------------------------- -- Make Chili controls -------------------------------------------------------------------------------- local function GetSavesList(parent, saveMode) local saves = GetSaves() FillSaveStackWithSaves(parent, saves, saveMode) end local function CreateWindow(saveMode) DisposeWindow() if WG.crude and WG.crude.AllowPauseOnMenuChange(true) then Spring.SendCommands("pause 1") end mainWindow = Window:New { name = 'zk_saveUI_saveWindow', x = Chili.Screen0.width / 2 - 320, y = "20%", width = 640, height = "60%", classname = "main_window", backgroundColor = {0, 0, 0, 0}, caption = saveMode and "Save Game" or "Load Game", resizable = false, tweakResizable = false, parent = Chili.Screen0, } local saveScroll = ScrollPanel:New { name = 'zk_saveUI_saveScroll', orientation = "vertical", x = 5, y = 18, right = 5, bottom = 80, parent = mainWindow, } GetSavesList(saveScroll, saveMode) if saveMode then local saveFilenameEdit = Chili.EditBox:New { name = 'zk_saveUI_saveFilename', x = 5, right = (saveMode and 174) or 94, bottom = 42, height = 28, width = "100%", hint = "Save Filename", font = {size = 16}, parent = mainWindow, } local saveDescEdit = Chili.EditBox:New { name = 'zk_saveUI_saveDesc', x = 5, right = (saveMode and 174) or 94, bottom = 8, height = 28, width = "100%", hint = "Save Description", font = {size = 16}, parent = mainWindow, } local saveButton = Button:New { name = 'saveButton', width = 80, height = 66, bottom = 6, right = 90, caption = WG.Translate("interface", "save") or "Save", OnClick = { function () if saveFilenameEdit.text and string.len(saveFilenameEdit.text) ~= 0 then PromptSave(saveFilenameEdit.text, saveDescEdit.text) end end }, font = {size = 18}, parent = mainWindow, } end local closeButton = Button:New { name = 'closeButton', width = 80, height = 66, bottom = 6, right = 5, caption = WG.Translate("interface", "close") or "Close", OnClick = {DisposeWindow}, font = {size = 18}, parent = mainWindow, } end -------------------------------------------------------------------------------- -- External Functions -------------------------------------------------------------------------------- local externalFunctions = {} function externalFunctions.CreateSaveWindow() CreateWindow(true) end function externalFunctions.CreateLoadWindow() CreateWindow(false) end -------------------------------------------------------------------------------- -- callins -------------------------------------------------------------------------------- function widget:Initialize() Chili = WG.Chili Control = Chili.Control Window = Chili.Window Panel = Chili.Panel StackPanel = Chili.StackPanel ScrollPanel = Chili.ScrollPanel Label = Chili.Label TextBox = Chili.TextBox Button = Chili.Button WG.SaveGame = externalFunctions end function widget:Shutdown() end function widget:GameFrame(n) if not options.enableautosave.value then return end if options.autosaveFrequency.value == 0 then return end if n % (options.autosaveFrequency.value * 1800) == 0 and n ~= 0 then if Spring.GetSpectatingState() or Spring.IsReplay() or (not WG.crude.IsSinglePlayer()) then return end Spring.Log(widget:GetInfo().name, LOG.INFO, "Autosaving") SaveGame("autosave", "", true) end end
gpl-2.0
ZACTELEGRAM1/IRAN
plugins/inrealm.lua
287
25005
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^[!/](creategroup) (.*)$", "^[!/](createrealm) (.*)$", "^[!/](setabout) (%d+) (.*)$", "^[!/](setrules) (%d+) (.*)$", "^[!/](setname) (.*)$", "^[!/](setgpname) (%d+) (.*)$", "^[!/](setname) (%d+) (.*)$", "^[!/](lock) (%d+) (.*)$", "^[!/](unlock) (%d+) (.*)$", "^[!/](setting) (%d+)$", "^[!/](wholist)$", "^[!/](who)$", "^[!/](type)$", "^[!/](kill) (chat) (%d+)$", "^[!/](kill) (realm) (%d+)$", "^[!/](addadmin) (.*)$", -- sudoers only "^[!/](removeadmin) (.*)$", -- sudoers only "^[!/](list) (.*)$", "^[!/](log)$", "^[!/](help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
Laterus/Darkstar-Linux-Fork
scripts/zones/Metalworks/npcs/Lucius.lua
1
1038
----------------------------------- -- Area: Metalworks -- NPC: Lucius -- Type: Mission NPC -- @zone: 237 -- @pos: 59.959 -17.39 -42.321 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0140); 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
TerraME/publish
data.lua
1
11471
data{ file = "caragua.shp", summary = "Caragua municipality, in Sao Paulo State, Brazil.", source = "IBGE (http://www.ibge.gov.br)", attributes = { population = "Population of Caraguatatuba.", pib = "Gross Domestic Product (GDP) of Caraguatatuba.", name = "Data name.", idh = "HDI indicators of Caraguatatuba." } } data{ file = "regions.shp", summary = "Caragua municipality divided into three regions.", source = "H. Guerra and P. Andrade", image = "urbis_regions.png", attributes = { name = "Regions of Caraguatatuba, North (1), Central (2) and South (3).", } } data{ file = "caragua_classes2010_regioes.shp", summary = "Social Classe 2010 Real.", source = "Feitosa et. al (2014) URBIS-Caraguá: Um Modelo de Simulação Computacional para a Investigação de Dinâmicas de Ocupação Urbana em Caraguatatuba, SP.", image = "urbis_2010_real.PNG", attributes = { classe = "Categorizes the social conditions of households in Caraguatatuba using classes A (3), B (2) or C (1).", } } data{ file = "occupational2010.shp", summary = "Occupational Classes (IBGE, 2010).", source = "Feitosa et. al (2014) URBIS-Caraguá: Um Modelo de Simulação Computacional para a Investigação de Dinâmicas de Ocupação Urbana em Caraguatatuba, SP.", image = "urbis_uso_2010.PNG", attributes = { uso = "The percentage of houses and apartments inside such areas that is typically used in summer vacations and holidays.", } } data{ file = "simulation2025_baseline.shp", summary = "Baseline simulation for 2025.", source = "Feitosa et. al (2014) URBIS-Caraguá: Um Modelo de Simulação Computacional para a Investigação de Dinâmicas de Ocupação Urbana em Caraguatatuba, SP.", image = "urbis_simulation_2025_baseline.PNG", attributes = { classe = "Categorizes the social conditions of households in Caraguatatuba using classes A (3), B (2) or C (1).", } } data{ file = "simulation2025_lessgrowth.shp", summary = "Less growth simulation in 2025.", source = "Feitosa et. al (2014) URBIS-Caraguá: Um Modelo de Simulação Computacional para a Investigação de Dinâmicas de Ocupação Urbana em Caraguatatuba, SP.", image = "urbis_simulation_2025_lessgrowth.PNG", attributes = { classe = "Categorizes the social conditions of households in Caraguatatuba using classes A (3), B (2) or C (1).", } } data{ file = "simulation2025_plusgrowth.shp", summary = "Plus growth simulation in 2025.", source = "Feitosa et. al (2014) URBIS-Caraguá: Um Modelo de Simulação Computacional para a Investigação de Dinâmicas de Ocupação Urbana em Caraguatatuba, SP.", image = "urbis_simulation_2025_plusgrowth.PNG", attributes = { classe = "Categorizes the social conditions of households in Caraguatatuba using classes A (3), B (2) or C (1).", } } data{ file = "simulation2025_poorer.shp", summary = "Poorer people in Caragua in 2025.", source = "Feitosa et. al (2014) URBIS-Caraguá: Um Modelo de Simulação Computacional para a Investigação de Dinâmicas de Ocupação Urbana em Caraguatatuba, SP.", image = "urbis_simulation_2025_poorer.PNG", attributes = { classe = "Categorizes the social conditions of households in Caraguatatuba using classes A (3), B (2) or C (1).", } } data{ file = "simulation2025_richer_final.shp", summary = "Richer people in Caragua in 2025.", source = "Feitosa et. al (2014) URBIS-Caraguá: Um Modelo de Simulação Computacional para a Investigação de Dinâmicas de Ocupação Urbana em Caraguatatuba, SP.", image = "urbis_simulation_2025_richer.PNG", attributes = { classe = "Categorizes the social conditions of households in Caraguatatuba using classes A (3), B (2) or C (1).", } } data{ file = "arapiuns_traj.shp", summary = "Route on the Arapiuns River.", source = "Escada et. al (2013) Infraestrutura, Serviços e Conectividade das Comunidades Ribeirinhas do Arapiuns, PA. Technical report, INPE." } data{ file = "AllCmmTab_210316OK.shp", summary = "The riverine communities at Arapiuns (PA).", source = "Escada et. al (2013) Infraestrutura, Serviços e Conectividade das Comunidades Ribeirinhas do Arapiuns, PA. Technical report, INPE.", attributes = { Nome = "Name of riverine community.", CMM2 = "Name of riverine community.", UC = "Conservation Unit.", IDDCM = "Age of the community.", NPES = "Population of the community.", BFAM = "Bolsa Familia.", SALE = "Saude e Alegria NGO.", INST = "Governmental institutions.", NASSOC = "Local institutions.", ENERGIA = "Energy.", AGUA = "Water.", LIXO = "Garbage collection.", ORELHAO = "Telephone.", CFUT = "Soccer field.", IGREJAS = "Church.", PSAU = "Health center of riverine settlements at Arapiuns.", ENSINF = "The schools of riverine settlements at Arapiuns.", ENSFUND2 = "The schools of riverine settlements at Arapiuns.", MERENDA = "Lunch at schools.", EJA = "The schools of riverine settlements at Arapiuns.", ARROZ = "Rice.", MAND = "Manioc.", FRUTAS = "Fruits.", CASTANHA = "Chestnut.", ACAI = "Acai.", PESCA = "Fischery.", CACA = "Hunting.", GADO = "Cattle.", MINERACAO = "Mining.", MANT = "Where people usually buy food.", ICON = "The name of marker icon." } } data{ file = "br_biomes.shp", summary = "Brazilian biomes.", source = "IBGE", attributes = { name = "Name of the biome.", link = "Link to a Wikipedia page with the description of the biome.", cover = "Percentage of Brazil's area covered by the biome." } } data{ file = "br_states.shp", summary = "Brazilian states.", source = "IBGE", attributes = { NOMEUF2 = "Name of the state.", SIGLAUF3 = "An acronym for the state.", } } data{ file = "sp_municipalities.shp", summary = "Sao Paulo municipalities.", source = "IBGE", attributes = { id = "Unique identifier.", nome = "Name of the city.", uf = "States of Brazil.", pib = "Gross Domestic Product (GDP).", populacao = "Population size.", } } directory{ name = "arapiuns", summary = "Photos of several riverine settlements.", source = "Escada et. al (2013) Infraestrutura, Serviços e Conectividade das Comunidades Ribeirinhas do Arapiuns, PA. Technical report, INPE.", } directory{ name = "biomes", summary = "A set of images related to Brazilian biomes collected from the Internet.", source = "Google and Wikipedia", } data{ file = "caragua_classes2010_regioes.tif", summary = "Social Classe 2010 Real.", source = "Feitosa et. al (2014) URBIS-Caraguá: Um Modelo de Simulação Computacional para a Investigação de Dinâmicas de Ocupação Urbana em Caraguatatuba, SP.", image = "urbis_2010_real.PNG", attributes = { ["0"] = "Categorizes the social conditions of households in Caraguatatuba using classes A (3), B (2) or C (1)." } } data{ file = "vegtype_2000_5880.tif", summary = "Vegetation Type 2000.", source = "Inland, INPE.", attributes = { ["0"] = "Vegetation classes." } } data{ file = "uc_federais_2001.shp", summary = "Conservation units of Brazil.", source = "INCT.", attributes = { codigoCnuc = "Unique identifier.", nome = "Name of the unit.", geometriaA = "Geometry.", anoCriacao = "Creation year.", sigla = "Initials.", areaHa = "Area.", perimetroM = "Perimeter.", atoLegal = "Legal.", administra = "Administration.", SiglaGrupo = "Group initials.", UF = "States of Brazil.", municipios = "Municipalities.", biomaIBGE = "Biome IBGE.", biomaCRL = "Biome CRL.", CoordRegio = "Region coordinates.", codCat = "Code.", codUso = "Code.", categoria = "Category.", IdUnidade = "Unit id.", tipo = "Type.", } } data{ file = "uc_federais_2009.shp", summary = "Conservation units of Brazil.", source = "INCT.", attributes = { codigoCnuc = "Unique identifier.", nome = "Name of the unit.", geometriaA = "Geometry.", anoCriacao = "Creation year.", sigla = "Initials.", areaHa = "Area.", perimetroM = "Perimeter.", atoLegal = "Legal.", administra = "Administration.", SiglaGrupo = "Group initials.", UF = "States of Brazil.", municipios = "Municipalities.", biomaIBGE = "Biome IBGE.", biomaCRL = "Biome CRL.", CoordRegio = "Region coordinates.", codCat = "Code.", codUso = "Code.", categoria = "Category.", IdUnidade = "Unit id.", tipo = "Type.", } } data{ file = "uc_federais_2016.shp", summary = "Conservation units of Brazil.", source = "INCT.", attributes = { codigoCnuc = "Unique identifier.", nome = "Name of the unit.", geometriaA = "Geometry.", anoCriacao = "Creation year.", sigla = "Initials.", areaHa = "Area.", perimetroM = "Perimeter.", atoLegal = "Legal.", administra = "Administration.", SiglaGrupo = "Group initials.", UF = "States of Brazil.", municipios = "Municipalities.", biomaIBGE = "Biome IBGE.", biomaCRL = "Biome CRL.", CoordRegio = "Region coordinates.", codCat = "Code.", codUso = "Code.", categoria = "Category.", IdUnidade = "Unit id.", tipo = "Type.", } } data{ file = "temporal-data.shp", summary = "Test of temporal data to create graphic and table.", source = "CCST.", attributes = { id = "Identifying of label.", col = "Column.", row = "Row.", f = "Identifier f.", d = "Identifier d.", outros = "outhers.", [{"f16", "d16", "ag_slope_1", "e_roads", "e_proads", "e_railway", "e_connmkt", "e_hidro", "e_beef", "e_wood", "e_soysug", "e_min", "e_urban100", "as_pland_s", "as_pland_m", "as_pland_b", "c_sett11" ,"c_nsett11" ,"c_hidreopc" ,"c_ucpi12" ,"c_ussapa12"}] = "Temporal data test bloc 1.", deterCR = "Deter.", [{"p19class27", "d_recente", "CAR_vazio", "f_recente", "e_urban10", "drec","frec", "OBJECTID", "Join_Cou_1", "TARGET_F_1"}] = "Test data bloc 1.", id_1 = "Identifier id 1.", col_1 = "Identifier col 1.", row_1 = "Identifier row_1.", [{"d_inita", "d_area02", "d_area03","d_area04", "d_area05", "d_area06", "d_area07", "d_area08", "d_area09", "d_area10", "d_area11", "d_area12", "d_area13", "d_area14", "d_area15"}] = "Temporal data test bloc 2.", [{"dg_darea06", "dg_darea07", "dg_darea08", "dg_darea09", "dg_darea10", "dg_darea11", "dg_darea12"}] = "Temporal data test bloc 3.", [{"B2nd", "b2_agb", "AGB3rd", "BGB3rd", "DW3rd", "Litter3rd", "soma_dg"}] = "Test data bloc 2.", [{"dg_darea13", "dg_darea14"}] = "Temporal data test bloc 4.", [{"b3_agb","B2ndM100"}] = "Test data bloc 3.", [{"b3_perc1", "b3_perc2", "b3_perc3"}] = "Temporal data test bloc 5.", [{"d_area16", "d_inita01", "d_forest"}] = "Temporal data test bloc 6.", forest02 = "Forest 02.", b12 = "Test data b12.", forest06 = "Forest 06.", [{"d_inita05", "b4_agb", "O", "soma_d"}] = "Test data bloc 4.", [{"AGB3rdM70", "BGB3rdM70"}] = "Temporal data test bloc 7.", [{"Lit3rdM70", "DW3rdM70", "AGB3M70cor"}] = "Test data bloc 5.", [{"for06_test", "for06_area"}] = "Temporal data test bloc 8.", [{"averAGBDeg", "b12_3rdInv"}] = "Test data bloc 6.", [{"dg_darea15", "dg_darea16", "dg_darea17", "dg_darea18", "dg_darea19"}] = "Temporal data test bloc 9.", [{"Shape_Leng", "Shape_Area"}] = "Temporal data test bloc 10.", [{"mcwd06", "mcwd07", "mcwd08", "mcwd09", "mcwd10", "mcwd11", "mcwd12", "mcwd13", "mcwd14", "mcwd15", "mcwd16"}] = "Temporal data test bloc 11.", [{"log_pDG06", "dAcc_ant", "pDG06", "TIndigena", "area_disp"}] = "Test data bloc 7.", [{"pTrjCrRaso", "pTrjDegrad", "pTrjRegen"}] = "Temporal data test bloc 12.", [{"log_CrRaso", "log_Degrad", "log_Regen"}] = "Temporal data test bloc 13.", min_mcwd = "Identifier MCWD.", } }
gpl-3.0
shubhamg31/columbus_julia
lib/julia/test/perf/micro/perf.lua
2
5365
local ffi = require 'ffi' local bit = require 'bit' local gsl = require 'gsl' local min, max, abs, sqrt, random, floor = math.min, math.max, math.abs, math.sqrt, math.random, math.floor local cabs = complex.abs local rshift = bit.rshift local format = string.format local gettime do ffi.cdef[[ struct timeval { long tv_sec; long tv_usec; }; int gettimeofday(struct timeval * tp, void *tzp); ]] local tv = ffi.new('struct timeval[1]') gettime = function() ffi.C.gettimeofday(tv, nil) return tv[0].tv_sec, tv[0].tv_usec end end -- return the elapsed time in ms local function elapsed(f) local s0, us0 = gettime() f() local s1, us1 = gettime() return tonumber(s1 - s0) * 1000 + tonumber(us1 - us0) / 1000 end local function timeit(f, name) local t = nil for k = 1, 5 do local tx = elapsed(f) t = t and min(t, tx) or tx end print(format("lua,%s,%g", name, t)) end local function fib(n) if n < 2 then return n else return fib(n-1) + fib(n-2) end end assert(fib(20) == 6765) timeit(|| fib(20), "fib") local function parseint() local r = rng.new('rand') local lmt = 2^32 - 1 local n, m for i = 1, 1000 do n = r:getint(lmt) local s = format('0x%x', tonumber(n)) m = tonumber(s) end assert(m == n) return n end timeit(parseint, "parse_int") local function mandel(z) local c = z local maxiter = 80 for n = 1, maxiter do if cabs(z) > 2 then return n-1 end z = z*z + c end return maxiter end function mandelperf() local a, re, im, z a = ffi.new("double[?]", 546) r = 0 for r = -20, 5 do re = r*0.1 for i=-10, 10 do im = i*0.1 a[r*21+i+430] = mandel(re + 1i * im) end end return a end do local a = mandelperf() local sum = 0 for i = 0, 545 do sum = sum + a[i] end assert(sum == 14791) end timeit(mandelperf, "mandel") local function qsort(a, lo, hi) local i, j = lo, hi while i < hi do local pivot = a[rshift(lo+hi, 1)] while i <= j do while a[i] < pivot do i = i+1 end while a[j] > pivot do j = j-1 end if i <= j then a[i], a[j] = a[j], a[i] i, j = i+1, j-1 end end if lo < j then qsort(a, lo, j) end lo, j = i, hi end return a end local function sortperf() local n = 5000 local r = rng.new('rand') local v = iter.ilist(|| r:get(), n) qsort(v, 1, n) end local function pisum() local sum for j = 1, 500 do sum = 0 for k = 1, 10000 do sum = sum + 1 / (k*k) end end return sum end local function stat(v) local p, q = 0, 0 local n = #v for k = 1, n do local x = v[k] p = p + x q = q + x*x end return sqrt((n*(n*q-p*p))/((n-1)*p*p)) end local function randmatstat(t) local n = 5 local A = iter.ilist(|| matrix.alloc(n, n), 4) local P = matrix.alloc(n, 4*n) local Q = matrix.alloc(2*n, 2*n) local PtP1 = matrix.alloc(4*n, 4*n) local PtP2 = matrix.alloc(4*n, 4*n) local QtQ1 = matrix.alloc(2*n, 2*n) local QtQ2 = matrix.alloc(2*n, 2*n) local get, set = A[1].get, A[1].set local r = rng.new('rand') local randn = || rnd.gaussian(r, 1) local function hstackf(i, j) local k, r = math.divmod(j - 1, n) return get(A[k + 1], i, r + 1) end local function vstackf(i, j) local ik, ir = math.divmod(i - 1, n) local jk, jr = math.divmod(j - 1, n) return get(A[2*ik + jk + 1], ir + 1, jr + 1) end local Tr, NT = gsl.CblasTrans, gsl.CblasNoTrans local v, w = {}, {} for i = 1, t do matrix.fset(A[1], randn) matrix.fset(A[2], randn) matrix.fset(A[3], randn) matrix.fset(A[4], randn) matrix.fset(P, hstackf) matrix.fset(Q, vstackf) gsl.gsl_blas_dgemm(Tr, NT, 1.0, P, P, 0.0, PtP1) gsl.gsl_blas_dgemm(NT, NT, 1.0, PtP1, PtP1, 0.0, PtP2) gsl.gsl_blas_dgemm(NT, NT, 1.0, PtP2, PtP2, 0.0, PtP1) local vi = 0 for j = 1, n do vi = vi + get(PtP1, j, j) end v[i] = vi gsl.gsl_blas_dgemm(Tr, NT, 1.0, Q, Q, 0.0, QtQ1) gsl.gsl_blas_dgemm(NT, NT, 1.0, QtQ1, QtQ1, 0.0, QtQ2) gsl.gsl_blas_dgemm(NT, NT, 1.0, QtQ2, QtQ2, 0.0, QtQ1) local wi = 0 for j = 1, 2*n do wi = wi + get(QtQ1, j, j) end w[i] = wi end return stat(v), stat(w) end do local s1, s2 = randmatstat(1000) assert( 0.5 < s1 and s1 < 1.0 and 0.5 < s2 and s2 < 1.0 ) end local function randmatmult(n) local r = rng.new('rand') --local rand = || r:get() local rand = random local a = matrix.new(n, n, rand) local b = matrix.new(n, n, rand) return a*b end local function printfd(n) local f = io.open("/dev/null","w") for i = 1, n do f:write(format("%d %d\n", i, i+1)) end f:close() end timeit(sortperf, "quicksort") timeit(pisum, "pi_sum") timeit(|| randmatstat(1000), "rand_mat_stat") timeit(|| randmatmult(1000), "rand_mat_mul") -- timeit(|| printfd(100000), "printfd")
apache-2.0