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
AresTao/darkstar
scripts/zones/Riverne-Site_A01/npcs/_0u4.lua
17
1341
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Unstable Displacement ----------------------------------- package.loaded["scripts/zones/Riverne-Site_A01/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Riverne-Site_A01/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1691,1) and trade:getItemCount() == 1) then -- Trade Giant Scale player:tradeComplete(); npc:openDoor(RIVERNE_PORTERS); player:messageSpecial(SD_HAS_GROWN); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 8) then player:startEvent(0x20); else player:messageSpecial(SD_VERY_SMALL); end; return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AresTao/darkstar
scripts/zones/Ruhotz_Silvermines/Zone.lua
36
1131
----------------------------------- -- -- Zone: Ruhotz_Silvermines -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Ruhotz_Silvermines/TextIDs"] = nil; require("scripts/zones/Ruhotz_Silvermines/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
AresTao/darkstar
scripts/zones/Sauromugue_Champaign/TextIDs.lua
7
1425
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6393; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6397; -- Obtained: <item>. GIL_OBTAINED = 6398; -- Obtained <number> gil. KEYITEM_OBTAINED = 6400; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7221; -- You can't fish here. -- Quest Dialogs MANY_TIGER_BONES = 7213; -- There are many tiger bones here... OLD_SABERTOOTH_DIALOG_I = 7219; -- You hear the distant roar of a tiger. It sounds as if the beast is approaching slowly... OLD_SABERTOOTH_DIALOG_II = 7220; -- The sound of the tiger's footsteps is growing louder. THF_AF_MOB = 7393; -- Something has come down from the tower! THF_AF_WALL_OFFSET = 7412; -- It is impossible to climb this wall with your bare hands. -- Other Dialog NOTHING_HAPPENS = 133; -- Nothing happens... NOTHING_OUT_OF_ORDINARY = 6411; -- There is nothing out of the ordinary here. -- conquest Base CONQUEST_BASE = 7054; -- Tallying conquest results... -- chocobo digging DIG_THROW_AWAY = 7234; -- You dig up ?Possible Special Code: 01??Possible Special Code: 01??Possible Special Code: 01? ?Possible Special Code: 01??Possible Special Code: 05?$?BAD CHAR: 8280??BAD CHAR: 80??BAD CHAR: 80?, but your inventory is full. FIND_NOTHING = 7236; -- You dig and you dig, but find nothing.
gpl-3.0
kidaa/luvit
tests/test-net-connect-handle-econnrefused.lua
11
1147
--[[ Copyright 2012-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 Tcp = require('uv').Tcp local net = require('net') local PORT = process.env.PORT or 10088 require('tap')(function(test) test('net-connect-handle-econnerefuesed', function(expected) local c, err = net.createConnection(PORT) c:on('connect', function () print("error: connnected, please shutdown whatever is running on " .. PORT) assert(false) end) c:on('error', function (err) assert('ECONNREFUSED' == err or 'EADDRNOTAVAIL' == err) expected = {gotError = true} c:destroy() end) end) end)
apache-2.0
AresTao/darkstar
scripts/zones/Promyvion-Mea/Zone.lua
25
7397
----------------------------------- -- -- Zone: Promyvion-Mea (20) -- ----------------------------------- package.loaded["scripts/zones/Promyvion-Mea/TextIDs"] = nil; ---------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/missions"); require("scripts/zones/Promyvion-Mea/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) -- -96,0,174,155 -- Level One Start zone:registerRegion(11,-122,-4,197,-117,4,202); -- Level One Return zone:registerRegion(12,-283,-4,237,-276,4,242); -- Level One MR -- -70,0,-233,105 -- Level Two Start zone:registerRegion(21,-1,-4,-121,2,4,-118); -- Level Two Return zone:registerRegion(22,-82,-4,-42,-78,4,-38); -- Level Two MR1 zone:registerRegion(23,-322,-4,-361,-318,4,-357); -- Level Two MR2 zone:registerRegion(24,-42,-4,-321,-37,4,-317); -- Level Two MR3 zone:registerRegion(25,77,-4,-241,81,4,-238); -- Level Two MR4 -- -167,0,172,38 -- Level Three West Start zone:registerRegion(31,-161,-4,158,-157,4,161); -- Level Three West Return zone:registerRegion(32,-42,-4,-2,-38,4,2); -- Level Three West MR1 no receptacle zone:registerRegion(33,-241,-4,-42,-238,4,-37); -- Level Three West MR2 zone:registerRegion(34,-321,-4,-42,-318,4,-38); -- Level Three West MR3 -- 68,0,-76,254 -- Level THREE East Start zone:registerRegion(35,158,-4,-281,161,4,-278); -- Level Three East Return zone:registerRegion(36,240,-4,-322,244,4,-317); -- Level Three East MR1 OKK zone:registerRegion(37,198,-4,-2,201,4,2); -- Level Three East MR2 no receptacle zone:registerRegion(38,358,-4,-41,362,4,-38); -- Level Three East MR3 -- -106,0,384,38 -- Level FOUR Start zone:registerRegion(41,-82,-4,358,-78,4,361); -- Level Four Return end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(-93.268, 0, 170.749, 162); -- Floor 1 {R} end if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 2) then player:completeMission(COP,BELOW_THE_ARKS); player:addMission(COP,THE_MOTHERCRYSTALS); -- start mission 1.3 player:setVar("PromathiaStatus",0); elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then if (player:hasKeyItem(LIGHT_OF_HOLLA) and player:hasKeyItem(LIGHT_OF_DEM)) then if (player:getVar("cslastpromy") == 1) then player:setVar("cslastpromy",0) cs = 0x0034; end elseif (player:hasKeyItem(LIGHT_OF_HOLLA) or player:hasKeyItem(LIGHT_OF_DEM)) then if (player:getVar("cs2ndpromy") == 1) then player:setVar("cs2ndpromy",0) cs = 0x0033; end end end if (player:getVar("FirstPromyvionMea") == 1) then cs = 0x0032; elseif (ENABLE_COP_ZONE_CAP == 1) then player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,30,0,0);-- ZONE LEVEL RESTRICTION end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) if (player:getAnimation() == 0) then switch (region:GetRegionID()): caseof { [11] = function (x) player:startEvent(0x002e); end, [12] = function (x) if (GetNPCByID(16859453):getAnimation() == 8) then player:startEvent(30); end end, -- player:setPos(-70,0,-233,105); [21] = function (x) player:startEvent(41); -- player:setPos(-96,0,174,155); end, [22] = function (x) if (GetNPCByID(16859456):getAnimation() == 8) then if (player:getVar("MemoryReceptacle") == 2) then player:startEvent(37); -- player:setPos(-167,0,172,38); else player:startEvent(33); -- player:setPos(68,0,-76,254); end end end, [23] = function (x) if (GetNPCByID(16859460):getAnimation() == 8) then if (player:getVar("MemoryReceptacle") == 2) then player:startEvent(37); -- player:setPos(-167,0,172,38); else player:startEvent(33); -- player:setPos(68,0,-76,254); end end end, [24] = function (x) if (GetNPCByID(16859461):getAnimation() == 8) then if (player:getVar("MemoryReceptacle") == 2) then player:startEvent(37); -- player:setPos(-167,0,172,38); else player:startEvent(33); -- player:setPos(68,0,-76,254); end end end, [25] = function (x) if (GetNPCByID(16859462):getAnimation() == 8) then if (player:getVar("MemoryReceptacle") == 2) then player:startEvent(37); -- player:setPos(-167,0,172,38); else player:startEvent(33); -- player:setPos(68,0,-76,254); end end end, [31] = function (x) player:startEvent(30); -- player:setPos(-70,0,-233,105); end, [32] = function (x) player:startEvent(31); -- player:setPos(-106,0,384,38); end, [33] = function (x) if (GetNPCByID(16859455):getAnimation() == 8) then player:startEvent(31); -- player:setPos(-106,0,384,38); end end, [34] = function (x) if (GetNPCByID(16859454):getAnimation() == 8) then player:startEvent(31); -- player:setPos(-106,0,384,38); end end, [35] = function (x) player:startEvent(30); -- player:setPos(-70,0,-233,105); end, [36] = function (x) if (GetNPCByID(16859463):getAnimation() == 8) then player:startEvent(31); -- player:setPos(-106,0,384,38); end end, [37] = function (x) if (GetNPCByID(16859458):getAnimation() == 8) then player:startEvent(31); -- player:setPos(-106,0,384,38); end end, [38] = function (x) if (GetNPCByID(16859459):getAnimation() == 8) then player:startEvent(31); -- player:setPos(-106,0,384,38); end end, [41] = function (x) if (player:getVar("MemoryReceptacle") == 2) then player:startEvent(37); -- player:setPos(-167,0,172,38); else player:startEvent(33); -- player:setPos(68,0,-76,254); end end, } end end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,region) -- 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 == 0x002e and option == 1) then player:setPos(279.988, -86.459, -25.994, 63, 14); -- To Hall of Transferance {R} elseif (csid == 0x0032) then player:setVar("FirstPromyvionMea",0); if (ENABLE_COP_ZONE_CAP == 1) then player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,30,0,0); -- ZONE LEVEL RESTRICTION end end if (option == 1) then player:setVar("MemoryReceptacle",0); end end;
gpl-3.0
prosody-modules/import
mod_auth_ccert/mod_auth_ccert.lua
32
2651
-- Copyright (C) 2013 Kim Alvefur -- -- This file is MIT/X11 licensed. local jid_compare = require "util.jid".compare; local jid_split = require "util.jid".prepped_split; local new_sasl = require "util.sasl".new; local now = os.time; local log = module._log; local subject_alternative_name = "2.5.29.17"; local id_on_xmppAddr = "1.3.6.1.5.5.7.8.5"; local oid_emailAddress = "1.2.840.113549.1.9.1"; local cert_match = module:get_option("certificate_match", "xmppaddr"); local username_extractor = {}; function username_extractor.xmppaddr(cert, authz, session) local extensions = cert:extensions(); local SANs = extensions[subject_alternative_name]; local xmppAddrs = SANs and SANs[id_on_xmppAddr]; if not xmppAddrs then (session.log or log)("warn", "Client certificate contains no xmppAddrs"); return nil, false; end for i=1,#xmppAddrs do if authz == "" or jid_compare(authz, xmppAddrs[i]) then (session.log or log)("debug", "xmppAddrs[%d] %q matches authz %q", i, xmppAddrs[i], authz) local username, host = jid_split(xmppAddrs[i]); if host == module.host then return username, true end end end end function username_extractor.email(cert) local subject = cert:subject(); for i=1,#subject do local ava = subject[i]; if ava.oid == oid_emailAddress then local username, host = jid_split(ava.value); if host == module.host then return username, true end end end end local find_username = username_extractor[cert_match]; if not find_username then module:log("error", "certificate_match = %q is not supported"); return end function get_sasl_handler(session) return new_sasl(module.host, { external = session.secure and function(authz) if not session.secure then -- getpeercertificate() on a TCP connection would be bad, abort! (session.log or log)("error", "How did you manage to select EXTERNAL without TLS?"); return nil, false; end local sock = session.conn:socket(); local cert = sock:getpeercertificate(); if not cert then (session.log or log)("warn", "No certificate provided"); return nil, false; end if not cert:validat(now()) then (session.log or log)("warn", "Client certificate expired") return nil, "expired"; end local chain_valid, chain_errors = sock:getpeerverification(); if not chain_valid then (session.log or log)("warn", "Invalid client certificate chain"); for i, error in ipairs(chain_errors) do (session.log or log)("warn", "%d: %s", i, table.concat(error, ", ")); end return nil, false; end return find_username(cert, authz, session); end }); end module:provides "auth";
mit
mehulsbhatt/ntopng
scripts/lua/hosts_flows_matrix.lua
2
4832
-- -- (C) 2013-15 - ntop.org -- dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path require "lua_utils" if(mode ~= "embed") then sendHTTPHeader('text/html; charset=iso-8859-1') ntop.dumpFile(dirs.installdir .. "/httpdocs/inc/header.inc") active_page = "hosts" dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua") end print("<h2>Top Hosts Traffic</H2>") print [[ <style> svg { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } sup, sub { line-height: 0; } .background { fill: #eee; } line { stroke: #fff; } text.active { font-size: 12px; fill: red; } article, aside { display:inline-block; vertical-align:top;} #tooltip{ display: none; position: absolute; color : #fff; /*background-color: #333;*/ border-radius: 4px; z-index: 1000; } tr { background-color: #333; } </style> ]] print("<section>") print("<header><h3></h3></header>") print('<div id="tooltip">') print [[ <table class="table table-bordered"> <thead> <th style="text-align: center;">Host</th> <th style="text-align: center;">Sent</th> <th style="text-align: center;">Rcvd</th> </thead> <tbody> </tbody> </table> ]] print('</div>') print("<article class=\"gr\"></article>") print [[ <aside style="margin-top: 90px; margin-left: 10px;>" <p><h4>Sort by: </h4><select id="order"> <option value="name">Name</option> <option value="count">Frequency</option> <option value="group">Cluster</option> <option value="flow_sent">Traffic Sent</option> <option value="flow_rcvd">Traffic Rcvd</option> <option value="flow_tot">Total Traffic</option> </select> </p> <div id="legend" style=""> <h4>Legend:</h4> <svg width="100" height="198"> <defs> <linearGradient id="local" x1="0%" y1="0%" x2="100%" y2="100%" spreadMethod="pad"> <stop offset="0%" stop-color="#1f77b4" stop-opacity="1"/> <stop offset="100%" stop-color="#1f77b4" stop-opacity=".25"/> </linearGradient> <linearGradient id="remote" x1="0%" y1="0%" x2="100%" y2="100%" spreadMethod="pad"> <stop offset="0%" stop-color="#ff7f0e" stop-opacity="1"/> <stop offset="100%" stop-color="#ff7f0e" stop-opacity=".25"/> </linearGradient> <linearGradient id="none" x1="0%" y1="0%" x2="100%" y2="100%" spreadMethod="pad"> <stop offset="0%" stop-color="#333" stop-opacity="1"/> <stop offset="100%" stop-color="#333" stop-opacity=".25"/> </linearGradient> </defs> <g transform="translate(0,0)"> <rect rx="3" ry="3" width="100" height="30" style="fill: url(#local);"></rect> <text x="50" y="15" dy="0.35em" text-anchor="middle">local</text> </g> <g transform="translate(0,33)"> <rect rx="3" ry="3" width="100" height="30" style="fill: url(#remote);"></rect> <text x="50" y="15" dy="0.35em" text-anchor="middle">remote</text> </g> <g transform="translate(0,66)"> <rect rx="3" ry="3" width="100" height="30" style="fill: url(#none);"></rect> <text x="50" y="15" dy="0.35em" text-anchor="middle">local &lt;-&gt; remote</text> </g> </svg> </div> </aside> ]] print("</section>") print ('<script>') print [[ var margin = {top: 140, right: 0, bottom: 10, left: 140}, width = 620, height = 500; var h = d3.scale.ordinal().rangeBands([0, width]), z = d3.scale.linear().domain([0, 4]).clamp(true), c = d3.scale.category10().domain(d3.range(10)); var svg = d3.select(".gr").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .style("margin-left", margin.left/7 + "px") .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); d3.json("]] print (ntop.getHttpPrefix()) print [[/lua/get_host_traffic_matrix.lua]] if(_GET["host"] ~= nil) then print("?host=".._GET["host"]) end print('",function(dati) {\n') ntop.dumpFile(dirs.installdir .. "/httpdocs/js/matrix_volume.js") print ('</script>') --[[print ('<script src="/js/matrix_volume.js"></script>')]]-- if(mode ~= "embed") then dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua") end
gpl-3.0
AresTao/darkstar
scripts/zones/Mhaura/npcs/Take.lua
17
4380
----------------------------------- -- Area: Mhaura -- NPC: Take -- Involved In Quest: RYCHARDE_THE_CHEF -- Starts and finishes quest: Expertice ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Mhaura/TextIDs"); -- player:startEvent(0x3b); -- standar dialog -- player:startEvent(0x3c); -- tell to look for ricarde --player:startEvent(0x44); -- not talked to rycharde yet --player:startEvent(0x3d);-- accept expertice quest --player:startEvent(0x3e);-- expertice completed --player:startEvent(0x3f);-- expertice not done yet --player:startEvent(0x40); -- after expertice quest --player:startEvent(0x41); -- good luck --player:startEvent(0x42);-- Valgeir cook was delicious --player:startEvent(0x43);-- after back to basics i think ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(OTHER_AREAS,RYCHARDE_THE_CHEF)==QUEST_AVAILABLE) then -- if available and allready talked to mayor assistant if (player:getVar("QuestRychardetheChef_var") == 1) then player:startEvent(0x3c); -- tell to look for ricarde elseif (player:getVar("QuestRychardetheChef_var") == 2) then player:startEvent(0x44); -- not talked to rycharde yet else player:startEvent(0x3b); -- talk abaout something else end elseif (player:getQuestStatus(OTHER_AREAS,EXPERTISE)==QUEST_AVAILABLE and player:getQuestStatus(OTHER_AREAS,HIS_NAME_IS_VALGEIR )==QUEST_COMPLETED) then -- player:startEvent(0x3d);-- accept expertice quest elseif (player:getQuestStatus(OTHER_AREAS,EXPERTISE)==QUEST_ACCEPTED) then -- if (player:hasKeyItem(LAND_CRAB_BISQUE)) then -- if have the Land Crab Bisque from Valgeir player:startEvent(0x3e,132);-- expertice completed else player:startEvent(0x3f);-- expertice not done yet end elseif (player:getQuestStatus(OTHER_AREAS,EXPERTISE)==QUEST_COMPLETED and player:getQuestStatus(OTHER_AREAS,THE_CLUE)==QUEST_AVAILABLE) then -- player:startEvent(0x40); -- after expertice quest elseif (player:getQuestStatus(OTHER_AREAS,THE_CLUE)==QUEST_ACCEPTED) then-- player:startEvent(0x41); -- good luck elseif (player:getQuestStatus(OTHER_AREAS,THE_CLUE)==QUEST_COMPLETED and player:getQuestStatus(OTHER_AREAS,THE_BASICS)==QUEST_AVAILABLE) then -- player:startEvent(0x42);-- Valgeir cook was delicious elseif (player:getQuestStatus(OTHER_AREAS,THE_BASICS)==QUEST_COMPLETED) then-- player:startEvent(0x43);-- after back to basics i think else player:startEvent(0x3b); -- talk abaout something else 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 == 0x3c) then player:setVar("QuestRychardetheChef_var",2); -- second stage on quest elseif (csid == 0x3d) then -- accept quest EXPERTICE player:addQuest(OTHER_AREAS,EXPERTISE); elseif (csid == 0x3e) then -- end quest expertice player:addFame(WINDURST,WIN_FAME*120); if (player:getFreeSlotsCount() < 1) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,132); else player:addItem(132); player:messageSpecial(ITEM_OBTAINED,132); player:addTitle(THREESTAR_PURVEYOR); player:setVar("QUEST_EXPERTISE_STATE_var",0); --done cooking player:setVar("QuestHNIVCCompDay_var",0); -- completition day of unending chase player:setVar("QuestHNIVCCompYear_var",0); player:setVar("QuestExpertiseCompDay_var",VanadielDayOfTheYear()); -- completition day of expertise quest player:setVar("QuestExpertiseCompYear_var",VanadielYear()); player:delKeyItem(LAND_CRAB_BISQUE); --give Land Crab Bisque from Valgeir player:completeQuest(OTHER_AREAS,EXPERTISE); end end end;
gpl-3.0
omidas77/speedbot
plugins/security.lua
2
39929
--Begin security.lua --Prerequisite: local function lock_group_media(msg, data, target) if not is_momod(msg) then return end local group_media_lock = data[tostring(target)]['settings']['lock_media'] if group_media_lock == 'yes' then return 'قفل رسانه از قبل فعال است .' else data[tostring(target)]['settings']['lock_media'] = 'yes' save_data(_config.moderation.data, data) return 'قفل رسانه فعال شد .' end end local function unlock_group_media(msg, data, target) if not is_momod(msg) then return end local group_media_lock = data[tostring(target)]['settings']['lock_media'] if group_media_lock == 'no' then return 'قفل رسانه فعال نیست .' else data[tostring(target)]['settings']['lock_media'] = 'no' save_data(_config.moderation.data, data) return 'قفل رسانه فعال شد .' end end local function lock_group_fwd(msg, data, target) if not is_momod(msg) then return end local group_fwd_lock = data[tostring(target)]['settings']['lock_fwd'] if group_fwd_lock == 'yes' then return 'قفل فروارد از قبل فعال است' else data[tostring(target)]['settings']['lock_fwd'] = 'yes' save_data(_config.moderation.data, data) local hash = 'fwd:'..msg.to.id redis:set(hash, true) return 'قفل فروارد فعال شد .' end end local function unlock_group_fwd(msg, data, target) if not is_momod(msg) then return end local group_fwd_lock = data[tostring(target)]['settings']['lock_fwd'] if group_fwd_lock == 'no' then return 'قفل فروارد فعال نیست .' else data[tostring(target)]['settings']['lock_fwd'] = 'no' save_data(_config.moderation.data, data) local hash = 'fwd:'..msg.to.id redis:del(hash) return 'قفل فروارد غیرفعال شد .' end end local function lock_group_reply(msg, data, target) if not is_momod(msg) then return end local group_reply_lock = data[tostring(target)]['settings']['lock_reply'] if group_reply_lock == 'yes' then return 'قفل ریپلی از قبل فعال است .' else data[tostring(target)]['settings']['lock_reply'] = 'yes' save_data(_config.moderation.data, data) local hash2 = 'reply:'..msg.to.id redis:set(hash2, true) return 'قفل ریپلی فعال شد .' end end local function unlock_group_reply(msg, data, target) if not is_momod(msg) then return end local group_reply_lock = data[tostring(target)]['settings']['lock_reply'] if group_reply_lock == 'no' then return 'قفل ریپلی فعال نیست .' else data[tostring(target)]['settings']['lock_reply'] = 'no' save_data(_config.moderation.data, data) local hash2 = 'reply:'..msg.to.id redis:del(hash2) return 'قفل ریپلی غیرفعال شد .' end end local function lock_group_share(msg, data, target) if not is_momod(msg) then return end local group_share_lock = data[tostring(target)]['settings']['lock_share'] if group_share_lock == 'yes' then return 'قفل ارسال مخاطب از قفل فعال است .' else data[tostring(target)]['settings']['lock_share'] = 'yes' save_data(_config.moderation.data, data) return 'قفل ارسال مخاطب فعال شد .' end end local function unlock_group_share(msg, data, target) if not is_momod(msg) then return end local group_share_lock = data[tostring(target)]['settings']['lock_share'] if group_share_lock == 'no' then return 'قفل ارسال مخاطب فعال نیست .' else data[tostring(target)]['settings']['lock_share'] = 'no' save_data(_config.moderation.data, data) return 'قفل ارسال مخاطب غیرفعال شد .' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return end local group_tag_lock = data[tostring(target)]['settings']['lock_tag'] if group_tag_lock == 'yes' then return 'قفل تگ از قبل فعال است .' else data[tostring(target)]['settings']['lock_tag'] = 'yes' save_data(_config.moderation.data, data) return 'قفل تگ فعال شد .' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return end local group_tag_lock = data[tostring(target)]['settings']['lock_tag'] if group_tag_lock == 'no' then return 'قفل تگ فعال نیست .' else data[tostring(target)]['settings']['lock_tag'] = 'no' save_data(_config.moderation.data, data) return 'قفل تگ غیرفعال شد .' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'قفل ربات از قبل فعال است .' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'قفل ربات فعال شد .' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'قفل ربات فعال نیست .' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'قفل ربات غیرفعال شد .' end end local function lock_group_number(msg, data, target) if not is_momod(msg) then return end local group_number_lock = data[tostring(target)]['settings']['lock_number'] if group_number_lock == 'yes' then return 'قفل عدد از قبل فعال است .' else data[tostring(target)]['settings']['lock_number'] = 'yes' save_data(_config.moderation.data, data) return 'قفل عدد فعال شد .' end end local function unlock_group_number(msg, data, target) if not is_momod(msg) then return end local group_number_lock = data[tostring(target)]['settings']['lock_number'] if group_number_lock == 'no' then return 'قفل عدد فعال نیست .' else data[tostring(target)]['settings']['lock_number'] = 'no' save_data(_config.moderation.data, data) return 'قفل عدد غیرفعال شد .' end end local function lock_group_poker(msg, data, target) if not is_momod(msg) then return end local group_poker_lock = data[tostring(target)]['settings']['lock_poker'] if group_poker_lock == 'yes' then return 'قفل پوکر از قبل فعال است ' else data[tostring(target)]['settings']['lock_poker'] = 'yes' save_data(_config.moderation.data, data) return 'قفل پوکر فعال شد .' end end local function unlock_group_poker(msg, data, target) if not is_momod(msg) then return end local group_poker_lock = data[tostring(target)]['settings']['lock_poker'] if group_poker_lock == 'no' then return 'قفل پوکر فعال نیست .' else data[tostring(target)]['settings']['lock_poker'] = 'no' save_data(_config.moderation.data, data) return 'قفل پوکر غیرفعال شد .' end end local function lock_group_audio(msg, data, target) local msg_type = 'Audio' local chat_id = msg.to.id if not is_momod(msg) then return end local group_audio_lock = data[tostring(target)]['settings']['lock_audio'] if group_audio_lock == 'yes' and is_muted(chat_id, msg_type..': yes') then return 'قفل صدا از قبل فعال است .' else if not is_muted(chat_id, msg_type..': yes') then mute(chat_id, msg_type) data[tostring(target)]['settings']['lock_audio'] = 'yes' save_data(_config.moderation.data, data) return 'قفل صدا فعال شد .' end end end local function unlock_group_audio(msg, data, target) local chat_id = msg.to.id local msg_type = 'Audio' if not is_momod(msg) then return end local group_audio_lock = data[tostring(target)]['settings']['lock_audio'] if group_audio_lock == 'no' and not is_muted(chat_id, msg_type..': yes') then return 'قفل صدا فعال نیست .' else if is_muted(chat_id, msg_type..': yes') then unmute(chat_id, msg_type) data[tostring(target)]['settings']['lock_audio'] = 'no' save_data(_config.moderation.data, data) return 'قفل صدا غیرفعال شد .' end end end local function lock_group_photo(msg, data, target) local msg_type = 'Photo' local chat_id = msg.to.id if not is_momod(msg) then return end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' and is_muted(chat_id, msg_type..': yes') then return 'قفل عکس از قبل فعال است .' else if not is_muted(chat_id, msg_type..': yes') then mute(chat_id, msg_type) data[tostring(target)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) return 'قفل عکس فعال شد .' end end end local function unlock_group_photo(msg, data, target) local chat_id = msg.to.id local msg_type = 'Photo' if not is_momod(msg) then return end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' and not is_muted(chat_id, msg_type..': yes') then return 'قفل عکس فعال نیست .' else if is_muted(chat_id, msg_type..': yes') then unmute(chat_id, msg_type) data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'قفل عکس غیرفعال شد .' end end end local function lock_group_video(msg, data, target) local msg_type = 'Video' local chat_id = msg.to.id if not is_momod(msg) then return end local group_video_lock = data[tostring(target)]['settings']['lock_video'] if group_video_lock == 'yes' and is_muted(chat_id, msg_type..': yes') then return 'قفل فیلم از قبل فعال است .' else if not is_muted(chat_id, msg_type..': yes') then mute(chat_id, msg_type) data[tostring(target)]['settings']['lock_video'] = 'yes' save_data(_config.moderation.data, data) return 'قفل فیلم فعال شد .' end end end local function unlock_group_video(msg, data, target) local chat_id = msg.to.id local msg_type = 'Video' if not is_momod(msg) then return end local group_video_lock = data[tostring(target)]['settings']['lock_video'] if group_video_lock == 'no' and not is_muted(chat_id, msg_type..': yes') then return 'قفل فیلم فعال نیست .' else if is_muted(chat_id, msg_type..': yes') then unmute(chat_id, msg_type) data[tostring(target)]['settings']['lock_video'] = 'no' save_data(_config.moderation.data, data) return 'قفل فیلم غیرفعال شد .' end end end local function lock_group_documents(msg, data, target) local msg_type = 'Documents' local chat_id = msg.to.id if not is_momod(msg) then return end local group_documents_lock = data[tostring(target)]['settings']['lock_documents'] if group_documents_lock == 'yes' and is_muted(chat_id, msg_type..': yes') then return 'قفل فایل از قبل فعال است .' else if not is_muted(chat_id, msg_type..': yes') then mute(chat_id, msg_type) data[tostring(target)]['settings']['lock_documents'] = 'yes' save_data(_config.moderation.data, data) return 'قفل فایل فعال شد .' end end end local function unlock_group_documents(msg, data, target) local chat_id = msg.to.id local msg_type = 'Documents' if not is_momod(msg) then return end local group_documents_lock = data[tostring(target)]['settings']['lock_documents'] if group_documents_lock == 'no' and not is_muted(chat_id, msg_type..': yes') then return 'قفل فایل فعال نیست .' else if is_muted(chat_id, msg_type..': yes') then unmute(chat_id, msg_type) data[tostring(target)]['settings']['lock_documents'] = 'no' save_data(_config.moderation.data, data) return 'قفل فایل غیرفعال شد .' end end end local function lock_group_text(msg, data, target) local msg_type = 'Text' local chat_id = msg.to.id if not is_momod(msg) then return end local group_text_lock = data[tostring(target)]['settings']['lock_text'] if group_text_lock == 'yes' and is_muted(chat_id, msg_type..': yes') then return 'قفل متن از قبل فعال است .' else if not is_muted(chat_id, msg_type..': yes') then mute(chat_id, msg_type) data[tostring(target)]['settings']['lock_text'] = 'yes' save_data(_config.moderation.data, data) return 'قفل متن فعال شد .' end end end local function unlock_group_text(msg, data, target) local chat_id = msg.to.id local msg_type = 'Text' if not is_momod(msg) then return end local group_text_lock = data[tostring(target)]['settings']['lock_text'] if group_text_lock == 'no' and not is_muted(chat_id, msg_type..': yes') then return 'قفل متن فعال نیست .' else if is_muted(chat_id, msg_type..': yes') then unmute(chat_id, msg_type) data[tostring(target)]['settings']['lock_text'] = 'no' save_data(_config.moderation.data, data) return 'قفل متن غیرفعال شد .' end end end local function lock_group_all(msg, data, target) local msg_type = 'All' local chat_id = msg.to.id if not is_momod(msg) then return end local group_all_lock = data[tostring(target)]['settings']['lock_all'] if group_all_lock == 'yes' and is_muted(chat_id, msg_type..': yes') then return 'قفل همه از قبل فعال است .' else if not is_muted(chat_id, msg_type..': yes') then mute(chat_id, msg_type) data[tostring(target)]['settings']['lock_all'] = 'yes' save_data(_config.moderation.data, data) return 'قفل همه فعال شد .' end end end local function unlock_group_all(msg, data, target) local chat_id = msg.to.id local msg_type = 'All' if not is_momod(msg) then return end local group_all_lock = data[tostring(target)]['settings']['lock_all'] if group_all_lock == 'no' and not is_muted(chat_id, msg_type..': yes') then return 'قفل همه فعال نیست .' else if is_muted(chat_id, msg_type..': yes') then unmute(chat_id, msg_type) data[tostring(target)]['settings']['lock_all'] = 'no' save_data(_config.moderation.data, data) return 'قفل همه غیرفعال شد .' end end end local function lock_group_gifs(msg, data, target) local msg_type = 'Gifs' local chat_id = msg.to.id if not is_momod(msg) then return end local group_gifs_lock = data[tostring(target)]['settings']['lock_gifs'] if group_gifs_lock == 'yes' and is_muted(chat_id, msg_type..': yes') then return 'قفل گیف از قبل فعال است .' else if not is_muted(chat_id, msg_type..': yes') then mute(chat_id, msg_type) data[tostring(target)]['settings']['lock_gifs'] = 'yes' save_data(_config.moderation.data, data) return 'قفل گیف فعال شد .' end end end local function unlock_group_gifs(msg, data, target) local chat_id = msg.to.id local msg_type = 'Gifs' if not is_momod(msg) then return end local group_gifs_lock = data[tostring(target)]['settings']['lock_gifs'] if group_gifs_lock == 'no' and not is_muted(chat_id, msg_type..': yes') then return 'قفل گیف فعال نیست .' else if is_muted(chat_id, msg_type..': yes') then unmute(chat_id, msg_type) data[tostring(target)]['settings']['lock_gifs'] = 'no' save_data(_config.moderation.data, data) return 'قفل گیف غیرفعال شد .' end end end local function lock_group_inline(msg, data, target) local msg_type = 'Inline' local chat_id = msg.to.id if not is_momod(msg) then return end local group_inline_lock = data[tostring(target)]['settings']['lock_inline'] if group_inline_lock == 'yes' and is_muted(chat_id, msg_type..': yes') then return 'قفل اینلاین از قبل فعال است .' else if not is_muted(chat_id, msg_type..': yes') then mute(chat_id, msg_type) data[tostring(target)]['settings']['lock_inline'] = 'yes' save_data(_config.moderation.data, data) return 'قفل اینلاین فعال شد .' end end end local function unlock_group_inline(msg, data, target) local chat_id = msg.to.id local msg_type = 'Inline' if not is_momod(msg) then return end local group_inline_lock = data[tostring(target)]['settings']['lock_inline'] if group_inline_lock == 'no' and not is_muted(chat_id, msg_type..': yes') then return 'قفل اینلاین فعال نیست .' else if is_muted(chat_id, msg_type..': yes') then unmute(chat_id, msg_type) data[tostring(target)]['settings']['lock_inline'] = 'no' save_data(_config.moderation.data, data) return 'قفل اینلاین غیرفعال شد .' end end end local function isABotBadWay (user) local username = user.username or '' return username:match("[Bb]ot$") end local function get_variables_hash(msg) return 'chat:'..msg.to.id..':badword' end local function list_variablesbad(msg) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = 'List of words :\n\n' for i=1, #names do text = text..'> '..names[i]..'\n' end return text else return end end local function list_variables2(msg, value) local hash = get_variables_hash(msg) if hash then local names = redis:hkeys(hash) local text = '' for i=1, #names do if string.match(value, names[i]) and not is_momod(msg) then if msg.to.type == 'channel' then delete_msg(msg.id,ok_cb,false) else kick_user(msg.from.id, msg.to.id) end return end --text = text..names[i]..'\n' end end end --Prerequisite. --Begin pre_process function local function pre_process(msg) -- Begin 'RondoMsgChecks' text checks by @rondoozle and Edited by @janlou -- Powered by @AdvanTm -- CopyRight all right reserved if is_chat_msg(msg) or is_super_group(msg) then if msg and not is_momod(msg) and not is_whitelisted(msg.from.id) then --if regular user local data = load_data(_config.moderation.data) local print_name = user_print_name(msg.from):gsub("‮", "") -- get rid of rtl in names local name_log = print_name:gsub("_", " ") -- name for log local to_chat = msg.to.type == 'chat' local to_super = msg.to.type == 'channel' if data[tostring(msg.to.id)] and data[tostring(msg.to.id)]['settings'] then settings = data[tostring(msg.to.id)]['settings'] else return end if settings.lock_arabic then lock_arabic = settings.lock_arabic else lock_arabic = 'no' end if settings.lock_rtl then lock_rtl = settings.lock_rtl else lock_rtl = 'no' end if settings.lock_tgservice then lock_tgservice = settings.lock_tgservice else lock_tgservice = 'no' end if settings.lock_link then lock_link = settings.lock_link else lock_link = 'no' end if settings.lock_member then lock_member = settings.lock_member else lock_member = 'no' end if settings.lock_spam then lock_spam = settings.lock_spam else lock_spam = 'no' end if settings.lock_sticker then lock_sticker = settings.lock_sticker else lock_sticker = 'no' end if settings.lock_contacts then lock_contacts = settings.lock_contacts else lock_contacts = 'no' end if settings.strict then strict = settings.strict else strict = 'no' end if msg and not msg.service and is_muted(msg.to.id, 'All: yes') or is_muted_user(msg.to.id, msg.from.id) and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then -- kick_user(msg.from.id, msg.to.id) end end if msg.text then -- msg.text checks local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') local _nl, real_digits = string.gsub(msg.text, '%d', '') if lock_spam == "yes" and string.len(msg.text) > 2049 or ctrl_chars > 40 or real_digits > 2000 then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local is_link_msg = msg.text:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.text:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") local is_bot = msg.text:match("?[Ss][Tt][Aa][Rr][Tt]=") if is_link_msg and lock_link == "yes" and not is_bot then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if msg.service then if lock_tgservice == "yes" then delete_msg(msg.id, ok_cb, false) if to_chat then return end end end local is_squig_msg = msg.text:match("[\216-\219][\128-\191]") if is_squig_msg and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl = print_name:match("‮") or msg.text:match("‮") if is_rtl and lock_rtl == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, "Text: yes") and msg.text and not msg.media and not msg.service then delete_msg(msg.id, ok_cb, false) if to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media then -- msg.media checks if msg.media.title then local is_link_title = msg.media.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.media.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.description then local is_link_desc = msg.media.description:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.description:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_desc and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_desc = msg.media.description:match("[\216-\219][\128-\191]") if is_squig_desc and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.caption then -- msg.media.caption checks local is_link_caption = msg.media.caption:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.media.caption:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") or msg.media.caption:match("@[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]") if is_link_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_caption = msg.media.caption:match("[\216-\219][\128-\191]") if is_squig_caption and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_username_caption = msg.media.caption:match("^@[%a%d]") if is_username_caption and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if lock_sticker == "yes" and msg.media.caption:match("sticker.webp") then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.media.type:match("contact") and lock_contacts == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_photo_caption = msg.media.caption and msg.media.caption:match("photo")--".jpg", if is_muted(msg.to.id, 'Photo: yes') and msg.media.type:match("photo") or is_photo_caption and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end local is_gif_caption = msg.media.caption and msg.media.caption:match(".mp4") if is_muted(msg.to.id, 'Gifs: yes') and is_gif_caption and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then -- kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Audio: yes') and msg.media.type:match("audio") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_video_caption = msg.media.caption and msg.media.caption:lower(".mp4","video") if is_muted(msg.to.id, 'Video: yes') and msg.media.type:match("video") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end if is_muted(msg.to.id, 'Documents: yes') and msg.media.type:match("document") and not msg.service then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if msg.fwd_from then if msg.fwd_from.title then local is_link_title = msg.fwd_from.title:match("[Tt][Ee][Ll][Ee][Gg][Rr][Aa][Mm].[Mm][Ee]/") or msg.fwd_from.title:match("[Tt][Ll][Gg][Rr][Mm].[Mm][Ee]/") if is_link_title and lock_link == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local is_squig_title = msg.fwd_from.title:match("[\216-\219][\128-\191]") if is_squig_title and lock_arabic == "yes" then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end end if is_muted_user(msg.to.id, msg.fwd_from.peer_id) then delete_msg(msg.id, ok_cb, false) end end if msg.service then -- msg.service checks local action = msg.action.type if action == 'chat_add_user_link' then local user_id = msg.from.id local _nl, ctrl_chars = string.gsub(msg.text, '%c', '') if string.len(msg.from.print_name) > 70 or ctrl_chars > 40 and lock_group_spam == 'yes' then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then kick_user(msg.from.id, msg.to.id) end end local print_name = msg.from.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then kick_user(user_id, msg.to.id) end if lock_member == 'yes' then kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end if action == 'chat_add_user' and not is_momod2(msg.from.id, msg.to.id) then local user_id = msg.action.user.id if string.len(msg.action.user.print_name) > 70 and lock_group_spam == 'yes' then delete_msg(msg.id, ok_cb, false) if strict == "yes" or to_chat then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end local print_name = msg.action.user.print_name local is_rtl_name = print_name:match("‮") if is_rtl_name and lock_rtl == "yes" then kick_user(user_id, msg.to.id) end if msg.to.type == 'channel' and lock_member == 'yes' then kick_user(user_id, msg.to.id) delete_msg(msg.id, ok_cb, false) end end end end if not is_momod(msg) and not is_whitelisted(msg.from.id) and not is_sudo(msg) and not is_owner(msg) and not is_vip(msg) then if msg.text:match("@[ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][_ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz][ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz]") then if lock_link == 'yes' then if msg.to.type == 'channel' then if strict == 'no' then delete_msg(msg.id, ok_cb, false) elseif strict == 'yes' then delete_msg(msg.id, ok_cb, false) kick_user(msg.from.id, msg.to.id) end end if msg.to.type == 'chat' then kick_user(msg.from.id, msg.to.id) end end end end if msg.text:match("/[Ss][Tt][Aa][Rr][Tt]") then if msg.to.type == "user" then return "Hello dear ["..msg.from.print_name.."], welcome to "..msg.to.print_name.."\nThanks for /start me :)\n" end end if msg.text:match("^[!/#][Aa][Dd][Vv][Aa][Nn]$") then txt = _config.about_text send_msg(get_receiver(msg), txt, ok_cb, false) end if msg.text:match("^[!/#][Rr][Aa][Tt][Ee]$") then Group_rate = _config.Group_rate Supergroup_rate = _config.Supergroup_rate if Group_rate ~= "" or Supergroup_rate ~= "" then rate = "Rate of:\n\nChat: "..Group_rate.."\nSuperGroup: "..Supergroup_rate send_msg(get_receiver(msg), rate, ok_cb, false) else rate = "Erore: Rate is not set!" send_msg(get_receiver(msg), rate, ok_cb, false) end end if is_chat_msg(msg) or is_super_group(msg) then receiver = get_receiver(msg) user = "user" chat = "chat" channel = "channel" if not is_momod(msg) and not is_whitelisted(msg.from.id) and not is_sudo(msg) and not is_owner(msg) and not is_admin1(msg) then local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_media'] then lock_media = data[tostring(msg.to.id)]['settings']['lock_media'] end if data[tostring(msg.to.id)]['settings']['lock_number'] then lock_number = data[tostring(msg.to.id)]['settings']['lock_number'] end if data[tostring(msg.to.id)]['settings']['lock_poker'] then lock_poker = data[tostring(msg.to.id)]['settings']['lock_poker'] end if data[tostring(msg.to.id)]['settings']['lock_tag'] then lock_tag = data[tostring(msg.to.id)]['settings']['lock_tag'] end if data[tostring(msg.to.id)]['settings']['lock_fwd'] then lock_fwd = data[tostring(msg.to.id)]['settings']['lock_fwd'] end if data[tostring(msg.to.id)]['settings']['lock_reply'] then lock_reply = data[tostring(msg.to.id)]['settings']['lock_reply'] end if data[tostring(msg.to.id)]['settings']['lock_share'] then lock_share = data[tostring(msg.to.id)]['settings']['lock_share'] end if data[tostring(msg.to.id)]['settings']['lock_bots'] then lock_bots = data[tostring(msg.to.id)]['settings']['lock_bots'] end if data[tostring(msg.to.id)]['settings']['lock_inline'] then lock_inline = data[tostring(msg.to.id)]['settings']['lock_inline'] end if data[tostring(msg.to.id)]['settings']['strict'] then lock_strict = data[tostring(msg.to.id)]['settings']['strict'] end end end --Media lock: if msg.text:match("%[(photo)%]") or msg.text:match("%[(video)%]") or msg.text:match("%[(document)%]") or msg.text:match("%[(gif)%]") or msg.text:match("%[(unsupported)%]") or msg.text:match("%[(audio)%]") then if lock_media == "yes" then if msg.to.type == channel then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Media lock. --Share lock: if msg.text:match("%[(contact)%]") then if lock_share == "yes" then if msg.to.type == channel then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Share lock. --Number lock: if msg.text:match("%d+") then if lock_number == "yes" then if msg.to.type == channel then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Number lock. --Poker lock: if msg.text:match("😐") then if lock_poker == "yes" then if msg.to.type == channel then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Poker lock. --Tag lock: if msg.text:match("#") then if lock_tag == "yes" then if msg.to.type == channel then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Tag lock. --Bots lock: if msg.text:match("^!!tgservice (chat_add_user)$") or msg.text:match("^!!tgservice (chat_add_user_link)$") then if lock_bots == "yes" then local user = msg.action.user or msg.from if isABotBadWay(user) then userId = user.id chatId = msg.to.id if msg.to.type == channel then kickUser("user#id"..userId, "channel#id"..chatId) channel_kick_user("channel#id"..msg.to.id, 'user#id'..userId, ok_cb, false) end end end end --Bots lock. --Inline lock: if msg.text == "[unsupported]" then if msg.to.type == channel then if lock_inline == "yes" then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end end end --Inline lock. --Remove filter word: if msg.text:match("^(.+)$") then name = user_print_name(msg.from) return list_variables2(msg, msg.text) end --Remove filter word. end end end --Fwd lock: if redis:get('fwd:'..msg.to.id) and msg.fwd_from and not is_sudo(msg) and not is_owner(msg) and not is_momod(msg) and not is_admin1(msg) then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end --Fwd lock. --Reply lock: if redis:get('reply:'..msg.to.id) and msg.reply_id and not is_sudo(msg) and not is_owner(msg) and not is_momod(msg) and not is_admin1(msg) then if lock_strict == "no" then delete_msg(msg.id, ok_cb, true) elseif lock_strict == "yes" then delete_msg(msg.id, ok_cb, true) kick_user(msg.from.id, msg.to.id) end end --Reply lock. -- End 'RondoMsgChecks' text checks by @Rondoozle return msg end --End pre_process function function run(msg, matches) --Lock or Unlock settings: if is_momod(msg) then if is_super_group(msg) then if matches[1] == 'قفل' then local target = msg.to.id local data = load_data(_config.moderation.data) if matches[2] == 'مدیا' then return lock_group_media(msg, data, target) end if matches[2] == 'فوروارد' then return lock_group_fwd(msg, data, target) end if matches[2] == 'ریپلای' then return lock_group_reply(msg, data, target) end if matches[2] == 'شیر' then return lock_group_share(msg, data, target) end if matches[2] == 'تگ' then return lock_group_tag(msg, data, target) end if matches[2] == 'ربات ها' then return lock_group_bots(msg, data, target) end if matches[2] == 'عدد' then return lock_group_number(msg, data, target) end if matches[2] == 'پوکر' then return lock_group_poker(msg, data, target) end if matches[2] == 'صدا' then return lock_group_audio(msg, data, target) end if matches[2] == 'عکس' then return lock_group_photo(msg, data, target) end if matches[2] == 'فیلم' then return lock_group_video(msg, data, target) end if matches[2] == 'فایل' then return lock_group_documents(msg, data, target) end if matches[2] == 'متن' then return lock_group_text(msg, data, target) end if matches[2] == 'همه' then return lock_group_all(msg, data, target) end if matches[2] == 'گیف' then return lock_group_gifs(msg, data, target) end if matches[2] == 'اینلاین' then return lock_group_inline(msg, data, target) end end if matches[1] == 'بازکردن' then local target = msg.to.id local data = load_data(_config.moderation.data) if matches[2] == 'مدیا' then return unlock_group_media(msg, data, target) end if matches[2] == 'فوروارد' then return unlock_group_fwd(msg, data, target) end if matches[2] == 'ریپلای' then return unlock_group_reply(msg, data, target) end if matches[2] == 'شیر' then return unlock_group_share(msg, data, target) end if matches[2] == 'تگ' then return unlock_group_tag(msg, data, target) end if matches[2] == 'ربات ها' then return unlock_group_bots(msg, data, target) end if matches[2] == 'عدد' then return unlock_group_number(msg, data, target) end if matches[2] == 'پوکر' then return unlock_group_poker(msg, data, target) end if matches[2] == 'صدا' then return unlock_group_audio(msg, data, target) end if matches[2] == 'عکس' then return unlock_group_photo(msg, data, target) end if matches[2] == 'فیلم' then return unlock_group_video(msg, data, target) end if matches[2] == 'فایل' then return unlock_group_documents(msg, data, target) end if matches[2] == 'متن' then return unlock_group_text(msg, data, target) end if matches[2] == 'همه' then return unlock_group_all(msg, data, target) end if matches[2] == 'گیف' then return unlock_group_gifs(msg, data, target) end if matches[2] == 'اینلاین' then return unlock_group_inline(msg, data, target) end end end end --Lock or Unlock settings. end --End run function return { patterns = { "^(قفل) (.*)$", "^(بازکردن) (.*)$", }, pre_process = pre_process, run = run } --End security.lua --By @Rondoozle
gpl-2.0
rainwoodman/fastPM
src/lua-runtime-fastpm.lua
1
22660
---------------------------------------------------- -- This is the main LUA runtime library of FastPM. -- -- Author: Yu Feng <rainwoodman@gmail.com> 2016 ---------------------------------------------------- local config = require("lua-runtime-config") local _NAME = ... or 'main' local fastpm = {} local schema = config.Schema() schema.declare{name='nc', type='int', required=true, help="Number of Particles Per side"} schema.declare{name='boxsize', type='number', required=true, help="Size of box in Mpc/h"} schema.declare{name='time_step', type='array:number', required=true, help="Scaling factor of steps, can be linspace(start, end, Nsteps)." } schema.declare{name='output_redshifts', type='array:number', required=false, help="Redshifts for outputs" } schema.declare{name='aout', type='array:number', required=false, help='a of redshifts'} -- set aout from output_redshifts function schema.aout.action(aout) schema.output_redshifts.required = false end -- set aout from output_redshifts function schema.output_redshifts.action(output_redshifts) local aout = {} if output_redshifts ~= nil then for i, z in pairs(output_redshifts) do aout[i] = 1.0 / (z + 1.) end schema.aout.default = aout end end -- Note: the order of variable declaration is important when applying scheme.variable.action later in this file. schema.declare{name='omega_m', type='number', required=false, help='This is depreciated. Please use Omega_m (uppercase O).'} schema.declare{name='Omega_m', type='number', required=false, help='Total matter (cdm + baryon + ncdm) density parameter at z=0'} schema.declare{name='T_cmb', type='number', required=false, default=0, help="CMB temperature in K, 0 to turn off radiation."} schema.declare{name='h', type='number', required=true, default=0.7, help="Dimensionless Hubble parameter"} schema.declare{name='Omega_k', type='number', required=false, default=0, help="Curvature density parameter. (Omega_k > 0 is an open universe.)"} schema.declare{name='w0', type='number', required=false, default=-1, help="Dark energy equation of state 0th order parameter: w(a) = w0 + (1-a) wa."} schema.declare{name='wa', type='number', required=false, default=0, help="Dark energy equation of state 1st order parameter: w(a) = w0 + (1-a) wa."} schema.declare{name='N_eff', type='number', required=false, default=3.046} schema.declare{name='N_nu', type='number', required=false, default=0, help="Total number of neutrinos, massive and massless."} schema.declare{name='m_ncdm', type='array:number', required=false, default={}, help="Mass of ncdm particles in eV. Enter in descending order."} schema.declare{name='pm_nc_factor', type='array:number', required=true, help="A list of {a, PM resolution}, "} schema.declare{name='lpt_nc_factor', type='number', required=false, default=1, help="PM resolution use in lpt and linear density field."} schema.declare{name='np_alloc_factor', type='number', required=true, help="Over allocation factor for load imbalance" } schema.declare{name='compute_potential', type='boolean', required=false, default=false, help="Calculate the gravitional potential."} schema.declare{name='n_shell', type='number', required=false, default=10, help="Number of shells of FD distribution for ncdm splitting. Set n_shell=0 for no ncdm particles."} schema.declare{name='lvk', type='boolean', required=false, default=true, help="Use the low velocity kernel when splitting FD for ncdm."} schema.declare{name='n_side', type='number', required=false, default=3, help="This is N_fib for fibonacci sphere splitting, or number of sides in HEALPix splitting."} schema.declare{name='every_ncdm', type='number', required=false, default=4, help="Subsample ncdm from cdm every..."} schema.declare{name='ncdm_sphere_scheme',type='enum', required=false, default="fibonacci", help="Split sphere with 'fibonacci' or 'healpix'?"} schema.ncdm_sphere_scheme.choices = { healpix = 'FASTPM_NCDM_SPHERE_HEALPIX', fibonacci = 'FASTPM_NCDM_SPHERE_FIBONACCI', } schema.declare{name='ncdm_matterlike', type='boolean', required=false, default=true, help="Approximate ncdm as matter-like in the background? If true, Omega_ncdm~1/a^3."} schema.declare{name='ncdm_freestreaming', type='boolean', required=false, default=true, help="Treat ncdm as free-streaming? If true, source terms ~Omega_c; if false, ~Omega_m."} schema.declare{name='growth_mode', type='enum', default='ODE', help="Evaluate growth factors using a Lambda+CDM-only approximation or with the full ODE. " .. "The full ODE is required for accurate results for runs with radiation or varying DE in the background, " .. "and can also be used for Lambda+CDM-only backgrounds. " .. "The LCDM approximation is included for backward compatibility."} schema.growth_mode.choices = { LCDM = 'FASTPM_GROWTH_MODE_LCDM', ODE = 'FASTPM_GROWTH_MODE_ODE', } -- enforce Omega_m function schema.omega_m.action (value) if value ~= nil then error("omega_m is depreciated, please use Omega_m (uppercase O) instead.") end end -- check for bad input function schema.T_cmb.action (T_cmb) if T_cmb ~= 0 then function schema.growth_mode.action (growth_mode) if growth_mode ~= 'ODE' then error("For a run with radiation (T_cmb > 0) use growth_mode='ODE' for accurate results.") end end end function schema.m_ncdm.action (m_ncdm) if #m_ncdm ~= 0 then for i=2, #m_ncdm do if m_ncdm[i] > m_ncdm[1] then error("Please input the heaviest ncdm particle first.") end end function schema.n_shell.action (n_shell) function schema.ncdm_freestreaming.action (ncdm_freestreaming) if ncdm_freestreaming and n_shell ~= 0 then error("For free-streaming ncdm use n_shell = 0 to turn off ncdm particles.") end end end function schema.ncdm_matterlike.action (ncdm_matterlike) if not ncdm_matterlike and T_cmb == 0 then error("For a run with exact Omega_ncdm, T_cmb > 0 is required.") end end end end end -- Force calculation -- schema.declare{name='painter_type', type='enum', default='cic', help="Type of painter."} schema.declare{name='painter_support', type='int', default=2, help="Support (size) of the painting kernel"} schema.painter_type.choices = { cic = 'FASTPM_PAINTER_CIC', linear = 'FASTPM_PAINTER_LINEAR', lanczos = 'FASTPM_PAINTER_LANCZOS', } function schema.painter_type.action(painter_type) if painter_type ~= 'cic' then schema.painter_support.required = true end end schema.declare{name='force_mode', type='enum', default='fastpm'} schema.force_mode.choices = { cola = 'FASTPM_FORCE_COLA', zola = 'FASTPM_FORCE_FASTPM', fastpm = 'FASTPM_FORCE_FASTPM', pm = 'FASTPM_FORCE_PM', } schema.declare{name='enforce_broadband_kmax', type='int', default=4} -- Primordial Non-Gaussianity -- schema.declare{name='f_nl_type', type='enum', default='none'} schema.f_nl_type.choices = { ['local'] = 'FASTPM_FNL_LOCAL', ['none'] = 'FASTPM_FNL_NONE', } schema.declare{name='f_nl', type='number'} schema.declare{name='kmax_primordial_over_knyquist', type='number', default=0.25} schema.declare{name='scalar_amp', type='number'} schema.declare{name='scalar_pivot', type='number'} schema.declare{name='scalar_spectral_index', type='number'} function schema.f_nl_type.action (f_nl_type) if f_nl_type ~= 'none' then schema.f_nl.required = true schema.scalar_amp.required = true schema.scalar_pivot.required = true schema.scalar_spectral_index.required = true end end -- Initial condition -- schema.declare{name='read_lineark', type='string', help='lineark for cdm'} schema.declare{name='read_powerspectrum', type='file', help='file to read the linear power spectrum for cdm.'} schema.declare{name='read_linear_growth_rate', type ='file', help='file to read the linear growth rate (f_1) of cdm. If left empty, will use internal f_1.'} schema.declare{name='linear_density_redshift', type='number', default=0, help='redshift of the input linear cdm density field. '} schema.declare{name='read_lineark_ncdm', type='string', help='file to read the lineark of ncdm.'} schema.declare{name='read_powerspectrum_ncdm', type='file', help='file to read the linear power spectrum of ncdm.'} schema.declare{name='read_linear_growth_rate_ncdm', type ='file', help='file to read the linear growth rate (f_1) of ncdm. If left empty, will use internal f_1.'} schema.declare{name='linear_density_redshift_ncdm', type='number', default=0, help='redshift of the input linear ncdm density field.'} schema.declare{name='read_grafic', type='string'} schema.declare{name='read_runpbic', type='string'} schema.declare{name='read_whitenoisek', type='string'} schema.declare{name='sigma8', type='number', default=0, help='normalize linear power spectrumt to sigma8(z); this shall be sigma8 at linear_density_redshift, not z=0.'} schema.declare{name='random_seed', type='int'} schema.declare{name='shift', type='boolean', default=false} schema.declare{name='inverted_ic', type='boolean', default=false} schema.declare{name='remove_cosmic_variance', type='boolean', default=false} function schema.read_grafic.action (read_grafic) if read_grafic ~= nil then schema.random_seed.required = false schema.read_powerspectrum.required = true end end function schema.read_lineark.action (read_lineark) if read_lineark ~= nil then schema.random_seed.required = false schema.read_powerspectrum.required = false end end function schema.read_runpbic.action (read_runpbic) if read_runpbic ~= nil then schema.random_seed.required = false schema.read_powerspectrum.required = false end end function schema.read_whitenoisek.action (read_whitenoisek) if read_whitenoisek ~= nil then schema.random_seed.required = false schema.read_powerspectrum.required = true end end schema.declare{name='write_lineark', type='string'} schema.declare{name='write_whitenoisek', type='string'} schema.declare{name='write_runpbic', type='string'} schema.declare{name='write_powerspectrum', type='string'} schema.declare{name='write_snapshot', type='string'} schema.declare{name='write_nonlineark', type='string'} schema.declare{name='write_runpb_snapshot', type='string'} schema.declare{name='particle_fraction', type='number', default=1.0, help='Fraction of particles to save in the snapshot (sub-sampling)'} schema.declare{name='sort_snapshot', type='boolean', default=true, help='sort snapshots by ID; very large communication is incurred during snapshots.'} schema.declare{name='write_fof', type='string', help='Path to save the fof catalog, will be in the FOF-0.200 dataset. (or other linking length).'} schema.declare{name='fof_linkinglength', type='number', default=0.2, help='linking length of FOF; in units of particle mean separation.'} schema.declare{name='fof_nmin', type='number', default=20, help='threshold for making into the FOF catalog.'} schema.declare{name='fof_kdtree_thresh', type='number', default=8, help='threshold for spliting a kdtree node. KDTree is used in fof. smaller uses more memory but fof runs faster.'} schema.declare{name='write_rfof', type='string', help='path to save the RFOF dataset; parameter defualts are fitted for Illustris sep=0.3 Mpc/h, 40 steps.'} schema.declare{name='rfof_kdtree_thresh', type='number', default=1, help='threshold for splitting a kdtree node. (Currently must be 1 due to a kdtree bug.)'} schema.declare{name='rfof_linkinglength', type='number', default=0.2, help='base linking length (0.2 in eq 2.4)'} schema.declare{name='rfof_nmin', type='number', default=8, help='threshold for making into the R-FOF catalog.'} schema.declare{name='rfof_l1', type='number', default=0.25, help=''} schema.declare{name='rfof_l6', type='number', default=0.24, help=''} schema.declare{name='rfof_a1', type='number', default=0.012, help=''} schema.declare{name='rfof_a2', type='number', default=0.06, help=''} schema.declare{name='rfof_b1', type='number', default=7.02, help=''} schema.declare{name='rfof_b2', type='number', default=6.025, help=''} schema.declare{name='lc_amin', type='number', help='min scale factor for truncation of lightcone.'} schema.declare{name='lc_amax', type='number', help='max scale factor for truncation of lightcone.'} schema.declare{name='lc_write_usmesh', type='string', help='file name base for writing the particle lightcone'} schema.declare{name='lc_usmesh_alloc_factor', type='number', default=1.0, help='allocation factor for the unstructured mesh, relative to alloc_factor.'} schema.declare{name='lc_usmesh_fof_padding', type='number', default=10.0, help='padding in the line of sight direction for light cone fof. roughly the size of a halo.'} schema.declare{name='lc_usmesh_tiles', type='array:number', default={ {0, 0, 0}, }, help=[[tiling of the simulation box, in units of box edges. all tiles will be considered during lightcone construction. tiling occurs before the glmatrix.]] } schema.declare{name='dh_factor', type='number', default=1.0, help='Scale Hubble distance to amplify the lightcone effect'} schema.declare{name='lc_fov', type='number', default=0.0, help=' field of view of the sky in degrees. 0 for flat sky and 360 for full sky. The beam is along the z-direction after glmatrix.'} schema.declare{name='lc_octants', type='array:number', default={0, 1, 2, 3, 4, 5, 6, 7}, help='list of octants to include when fov>=360 degrees.'} schema.declare{name='lc_glmatrix', type='array:number', default={ {1, 0, 0, 0,}, {0, 1, 0, 0,}, {0, 0, 1, 0,}, {0, 0, 0, 1,}, }, help=[[transformation matrix to move simulation coordinate (x, y, z, 1) to the observer coordinate with a left dot product. The observer is sitting at z=0 in the observer coordinate. The last column of the matrix is the translation in Mpc/h. use the translation and rotation methods provide in the intepreter to build the matrix. ]]} schema.declare{name='za', type='boolean', default=false, help='use ZA initial condition not 2LPT'} schema.declare{name='kernel_type', type='enum', default="1_4", help='Force kernel; affects low mass halos 3_4 gives more low mass halos; 1_4 is consistent with fastpm-python.'} schema.kernel_type.choices = { ['1_4'] = 'FASTPM_KERNEL_1_4', -- consistent with fastpm-python ['3_4'] = 'FASTPM_KERNEL_3_4', -- legacy fastpm ['gadget'] = 'FASTPM_KERNEL_GADGET', -- GADGET long range without exp smoothing. ['5_4'] = 'FASTPM_KERNEL_5_4', -- very bad do not use ['eastwood'] = 'FASTPM_KERNEL_EASTWOOD', ['naive'] = 'FASTPM_KERNEL_NAIVE', ['3_2'] = 'FASTPM_KERNEL_3_2', } schema.declare{name='force_softening_type', type='enum', default="none", help='Softening kernel (wipes out small scale force), very little effect)'} schema.force_softening_type.choices = { none = 'FASTPM_SOFTENING_NONE', gaussian = 'FASTPM_SOFTENING_GAUSSIAN', gadget_long_range = 'FASTPM_SOFTENING_GADGET_LONG_RANGE', gaussian36 = 'FASTPM_SOFTENING_GAUSSIAN36', twothird = 'FASTPM_SOFTENING_TWO_THIRD', } schema.declare{name='constraints', type='array:number', help="A list of {x, y, z, peak-sigma}, giving the constraints in MPC/h units. "} function schema.constraints.action (constraints) if constraints == nil then return end for i,v in pairs(constraints) do if #v ~= 4 then error("contraints must be a list of 4-vectors (x, y, z, peak-sigma)") end end end schema.declare{name='set_mode_method', type='string', default="override", help="override or relative"} schema.declare{name='set_mode', type='array:number', help="A list of {kix, kiy, kiz, ri, value}, set the IC mode at integer k (ri for real and imag) to value"} function schema.set_mode.action (set_mode) if set_mode == nil then return end for i,v in pairs(set_mode) do if #v ~= 5 then error("set_mode must be a list of 5-vectors (x, y, z, real_or_imag, value)") end if v[4] ~= 1 and v[4] ~=0 then error("the fourth component specifies real or imag part of the mode. must be 0 or 1") end end end schema.declare{name='pgdc', type='boolean', default=false, help="if enable pgd correction"} schema.declare{name='pgdc_alpha0', type='number', default=0.8, help="alpha parameter in pgd correction"} schema.declare{name='pgdc_A', type='number', default=4.0, help="alpha parameter in pgd correction"} schema.declare{name='pgdc_B', type='number', default=8.0, help="alpha parameter in pgd correction"} schema.declare{name='pgdc_kl', type='number', default=2.0, help="filter large scale parameter in pgd correction"} schema.declare{name='pgdc_ks', type='number', default=10.0, help="filter small scale parameter in pgd correction"} function fastpm.translation(dx, dy, dz) -- generate a translation gl matrix that shifts the coordinates return { {1, 0, 0, dx}, {0, 1, 0, dy}, {0, 0, 1, dz}, {0, 0, 0, 1 }, } end function fastpm.outerproduct(a, b, c) -- generate a list that is outer product of elements of a, b, c local r = {} for i=1, #a do for j=1, #b do for k=1, #c do r[#r + 1] = {a[i], b[j], c[k]} end end end return r end function fastpm.linspace(a, e, N, endpoint) -- Similar to numpy.linspace always append the end -- -- https://mail.scipy.org/pipermail/numpy-discussion/2016-February/075065.html if endpoint == nil then endpoint = true end local r = {} if endpoint then N1 = N - 1 else N1 = N end for i=1,N do r[i] = 1.0 * (e - a) * (i - 1) / N1 + a end if endpoint then r[N] = e end return r end function fastpm.logspace(a, e, N) -- a and end are in log10. -- Returns N elements, including e. local r r = fastpm.linspace(a, e, N) for i, j in pairs(r) do r[i] = math.pow(10, j) end return r end function fastpm.blendspace(a, e, a1, a2) local r = {} local a = a local i = 1 while a < e do r[i] = a dlna = math.pow(math.pow(1/a1, 2) + math.pow(a/a2, 2), -0.5) a = math.exp(math.log(a) + dlna) i = i + 1 end r[i] = e return r end function fastpm.loglinspace(a, m, e, Nlog, Nlin) -- Take Nlog log steps between a and m, -- then Nlin lin steps between m and e. -- a, m, ane e are in linear units. local r local s local t = {} local n = 0 r = fastpm.logspace(math.log10(a), math.log10(m), Nlog+1) s = fastpm.linspace(m, e, Nlin+1) for i=1,#r do n=n+1; t[n]=r[i] end for i=2,#s do n=n+1; t[n]=s[i] end -- ignore duplicate entry on boundary return t end function fastpm.test() ns = { __file__ = "standard.lua", boxsize = 384.0, cola_stdda = true, force_softening_type = "none", enforce_broadband_kmax = 4, f_nl = 0.100000000000000006, f_nl_type = "local", force_mode = "pm", h = 0.677400000000000002, inverted_ic = false, kernel_type = "3_4", nc = 128, np_alloc_factor = 4.0, omega_m = 0.30749399999999999, prefix = "results-za-nongaussian", random_seed = 100, read_powerspectrum = "powerspec.txt", remove_cosmic_variance = false, scalar_amp = 0.000000002441, scalar_pivot = 0.002, scalar_spectral_index = 0.966700000000000004, sigma8 = 0, write_lineark = "results-za-nongaussian/lineark", write_nonlineark = "results-za-nongaussian/nonlineark", write_powerspectrum = "results-za-nongaussian/powerspec", write_snapshot = "results-za-nongaussian/fastpm", write_whitenoisek = "results-za-nongaussian/whitenoisek", za = true, args = { "standard.lua", "za", "nongaussian", }, change_pm = { 0, }, output_redshifts = { 9.0, 0.0, }, pm_nc_factor = { 2, }, time_step = { 1.0, }, } schema.print() for i,k in pairs(schema.bind(ns)) do print(i, k) end end fastpm.schema = schema -- -- The main functions, must be a global symbol -- function _parse_runmain(filename, ...) local fastpm = require('lua-runtime-fastpm') local config = require('lua-runtime-config') local globals = setmetatable({}, {__index=_G}) globals.fastpm = fastpm globals.logspace = fastpm.logspace globals.linspace = fastpm.linspace globals.loglinspace = fastpm.loglinspace return config.parse(fastpm.schema, filename, true, globals, {...}) end function _parse(filename, ...) local fastpm = require('lua-runtime-fastpm') local config = require('lua-runtime-config') local globals = setmetatable({}, {__index=_G}) globals.fastpm = fastpm globals.logspace = fastpm.logspace globals.linspace = fastpm.linspace globals.loglinspace = fastpm.loglinspace return config.parse(fastpm.schema, filename, false, globals, {...}) end function _help(filename, ...) local fastpm = require('lua-runtime-fastpm') local config = require('lua-runtime-config') return fastpm.schema.format_help() end return fastpm
gpl-3.0
AresTao/darkstar
scripts/zones/Misareaux_Coast/npcs/_0p2.lua
28
1874
----------------------------------- -- Area: Misareaux Coast -- NPC: Dilapidated Gate -- Entrance to Riverne Site #B01 ----------------------------------- package.loaded["scripts/zones/Misareaux_Coast/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Misareaux_Coast/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == THE_SAVAGE and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0008); elseif (player:getCurrentMission(COP) == ANCIENT_VOWS and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x0006); elseif (player:getCurrentMission(COP) == FLAMES_IN_THE_DARKNESS and player:getVar("PromathiaStatus") == 0) then player:startEvent(0x000C); elseif (player:getCurrentMission(COP) > AN_ETERNAL_MELODY or player:hasCompletedMission(COP,THE_LAST_VERSE)) then player:startEvent(0x0228); else player:messageSpecial(DOOR_CLOSED); 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 == 0x0006 or csid == 0x000C) then player:setVar("PromathiaStatus",1); elseif (csid == 0x0008 and option == 1) then player:setVar("PromathiaStatus",1); player:setPos(729,-20,410,88,0x1D); -- Go to Riverne #B01 end end;
gpl-3.0
mehulsbhatt/ntopng
scripts/lua/hosts_interaction.lua
1
14937
-- -- (C) 2013-15 - ntop.org -- dirs = ntop.getDirs() package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path require "lua_utils" -- host_info = url2hostinfo(_GET) if(host_ip == nil) then host_info = url2hostinfo(_GET) else -- print("host_ip:"..host_ip.."<br>") host_info = {} host_info = hostkey2hostinfo(host_ip) end if(mode == nil) then mode = _GET["mode"] end if(host_name == nil) then host_name = _GET["name"] end if(mode ~= "embed") then sendHTTPHeader('text/html; charset=iso-8859-1') ntop.dumpFile(dirs.installdir .. "/httpdocs/inc/header.inc") active_page = "hosts" dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua") end num_top_hosts = 10 if(host_info["host"] ~= nil) then num = 1 else interface.select(ifname) hosts_stats = interface.getHostsInfo() num = 0 for key, value in pairs(hosts_stats) do num = num + 1 end end if(num > 0) then if(mode ~= "embed") then if(host_info["host"] == nil) then print("<hr><h2>Top Hosts Interaction</H2>") else name = host_name if(name == nil) then name = host_info["host"] end print("<hr><h2>"..name.." Interactions</H2><i class=\"fa fa-chevron-left fa-lg\"></i><small><A onClick=\"javascript:history.back()\">Back</A></small>") end end print [[ <style> svg { font: 10px sans-serif; } .axis path, .axis line { fill: none; stroke: #000; shape-rendering: crispEdges; } sup, sub { line-height: 0; } q:before, blockquote:before { content: "?"; } q:after, blockquote:after { content: "?"; } blockquote:before { position: absolute; left: 2em; } blockquote:after { position: absolute; } </style> <style> #chart { height: ]] if(mode ~= "embed") then print("600") elseif(interface.getNumAggregatedHosts() > 0) then print("400") else print("300") end print [[ px; } .node rect { cursor: move; fill-opacity: .9; shape-rendering: crispEdges; } .node text { pointer-events: none; text-shadow: 0 1px 0 #fff; } .link { fill: none; stroke: #000; stroke-opacity: .2; } .link:hover { stroke-opacity: .5; } circle.node-dot { fill: DarkSlateGray; stroke: SlateGray; stroke-width: 1px; } path.link { fill: none; stroke: SlateGray; stroke-width: 1.5px; } marker#defaultMarker { fill: SlateGray; } path.link.defaultMarker { stroke: SlateGray; } circle { fill: #ccc; stroke: #333; stroke-width: 1.5px; } text { pointer-events: none; } text.shadow { stroke: #fff; stroke-width: 3px; stroke-opacity: .8; } </style><style>path.link.proposer{stroke:red;} marker#bus{fill:blue;} marker#manual{fill:red;} path.link.direct{stroke:green; } path.link.bus{stroke:blue;} path.link.manual{stroke:red;stroke-dasharray: 0, 2 1;} </style><script> /** * do the force vizualization * @param {string} divName name of the div to hold the tree * @param {object} inData the source data */ function doTheTreeViz(divName, inData) { // tweak the options var options = $.extend({ stackHeight : 12, radius : 5, fontSize : 12, labelFontSize : 8, nodeLabel : null, markerWidth : 0, markerHeight : 0, width : $(divName).outerWidth(), gap : 1.5, nodeResize : "", linkDistance : 30, charge : -120, styleColumn : null, styles : null, linkName : null, height : $(divName).outerHeight() }, inData.d3.options); // set up the parameters options.gap = options.gap * options.radius; var width = options.width; var height = options.height; var data = inData.d3.data; var nodes = data.nodes; var links = data.links; var color = d3.scale.category10(); color["local"] = "#aec7e8"; color["remote"] = "#bcbd22"; color["sun"] = "#fd8d3c"; color["aggregation"] = "#008d3c"; var force = d3.layout.force().nodes(nodes).links(links).size([width, height]).linkDistance(options.linkDistance).charge(options.charge).on("tick", tick).start(); var main = d3.select(divName).append("svg:svg").attr("width", width).attr("height", height); var svg = main.append('svg:g') .call(d3.behavior.zoom().on("zoom", rescale)) .on("dblclick.zoom", null); function rescale() { trans=d3.event.translate; scale=d3.event.scale; svg.attr("transform", "translate(" + trans + ")" + " scale(" + scale + ")"); } // get list of unique values in stylecolumn linkStyles = []; if (options.styleColumn) { var x; for (var i = 0; i < links.length; i++) { if (linkStyles.indexOf( x = links[i][options.styleColumn].toLowerCase()) == -1) linkStyles.push(x); } } else linkStyles[0] = "defaultMarker"; // do we need a marker? if (options.markerWidth) { svg.append("svg:defs").selectAll("marker").data(linkStyles).enter().append("svg:marker").attr("id", String).attr("viewBox", "0 -5 10 10").attr("refX", 15).attr("refY", -1.5).attr("markerWidth", options.markerWidth).attr("markerHeight", options.markerHeight).attr("orient", "auto").append("svg:path").attr("d", "M0,-5L10,0L0,5"); } var path = svg.append("svg:g").selectAll("path").data(force.links()).enter().append("svg:path").attr("class", function(d) { return "link " + (options.styleColumn ? d[options.styleColumn].toLowerCase() : linkStyles[0]); }).attr("marker-end", function(d) { return "url(#" + (options.styleColumn ? d[options.styleColumn].toLowerCase() : linkStyles[0] ) + ")"; }); var circle = svg.append("svg:g").selectAll("circle") .data(force.nodes()) .enter() .append("svg:circle") .attr("r", function(d) { return getRadius(d); }) .style("fill", function(d) { return color[d.group]; }) .call(force.drag) //.on("mousedown", // function(d) { // disable zoom // svg.call(d3.behavior.zoom().on("zoom"), null); // }) //.on("mouseup", // function(d) { // enable zoom // svg.call(d3.behavior.zoom().on("zoom"), rescale); // }) ; if (options.nodeLabel) { circle.append("title").html(function(d) { return d[options.nodeLabel]; }); } circle.on("dblclick", function(d) { if(d.link.length > 0) { window.location.href = d.link; } } ); if (options.linkName) { path.append("title").text(function(d) { return d[options.linkName]; }); } var text = svg.append("svg:g").selectAll("g").data(force.nodes()).enter().append("svg:g"); // A copy of the text with a thick white stroke for legibility. text.append("svg:text").attr("x", options.labelFontSize).attr("y", ".31em").attr("class", "shadow").text(function(d) { return d[options.nodeLabel]; }); text.append("svg:text").attr("x", options.labelFontSize).attr("y", ".31em").text(function(d) { return d[options.nodeLabel]; }); function getRadius(d) { return options.radius * (options.nodeResize ? Math.sqrt(d[options.nodeResize]) / Math.PI : 1); } // Use elliptical arc path segments to doubly-encode directionality. function tick() { path.attr("d", function(d) { var dx = d.target.x - d.source.x, dy = d.target.y - d.source.y, dr = Math.sqrt(dx * dx + dy * dy); return "M" + d.source.x + "," + d.source.y + "A" + dr + "," + dr + " 0 0,1 " + d.target.x + "," + d.target.y; }); circle.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); text.attr("transform", function(d) { return "translate(" + d.x + "," + d.y + ")"; }); } } </script><script> window['ntopData'] = {"d3":{"options": {"radius":"16","fontSize":"30","labelFontSize":"30","charge":"-2000","nodeResize":"count","nodeLabel":"label","markerHeight":"6","markerWidth":"6","styleColumn":"styleColumn","linkName":"group"}, "data":{"links":[ ]] -- Nodes interface.select(ifname) if(host_info["host"] == nil) then hosts_stats = getTopInterfaceHosts(num_top_hosts, true) else hosts_stats = {} hosts_stats[host_info["host"]] = interface.getHostInfo(host_info["host"],host_info["vlan"]) end hosts_ctx = {} hosts_id = {} ids = {} num = 0 links = 0 local host local max_num_hosts = 50 local host_idx = 0 local num_contacts -- Enumerate contacts of each host for key, values in pairs(hosts_stats) do host = interface.getHostInfo(key) if (host ~= nil) then num_contacts = 0 if (host["contacts"]["client"] ~= nil) then for k,v in pairs(host["contacts"]["client"]) do num_contacts = num_contacts + 1 end end if (host["contacts"]["server"] ~= nil) then for k,v in pairs(host["contacts"]["server"]) do num_contacts = num_contacts + 1 end end end hosts_ctx[key] = num_contacts end for key, values in pairsByValues(hosts_ctx, rev) do host = interface.getHostInfo(key) if(host ~= nil) then -- init host if(hosts_id[key] == nil) then hosts_id[key] = { } hosts_id[key]['count'] = 0 hosts_id[key]['id'] = num ids[num] = key key_id = num num = num + 1 else key_id = hosts_id[key]['id'] end -- client contacts if(host["contacts"]["client"] ~= nil) then for k,v in pairs(host["contacts"]["client"]) do if(hosts_id[k] == nil) then hosts_id[k] = { } hosts_id[k]['count'] = 0 hosts_id[k]['id'] = num ids[num] = k peer_id = num num = num + 1 else peer_id = hosts_id[k]['id'] end hosts_id[key]['count'] = hosts_id[key]['count'] + v if(links > 0) then print(",") end print('\n{"source":'..key_id..',"target":'..peer_id..',"depth":6,"count":'..v..',"styleColumn":"client","linkName":""}') links = links + 1 end end -- server contacts if(host["contacts"]["server"] ~= nil) then for k,v in pairs(host["contacts"]["server"]) do if(hosts_id[k] == nil) then hosts_id[k] = { } hosts_id[k]['count'] = 0 hosts_id[k]['id'] = num ids[num] = k peer_id = num num = num + 1 else peer_id = hosts_id[k]['id'] end hosts_id[key]['count'] = hosts_id[key]['count'] + v if(links > 0) then print(",") end print('\n{"source":'..key_id..',"target":'..peer_id..',"depth":6,"count":'..v..',"styleColumn":"server"}') links = links + 1 end end end host_idx = host_idx + 1 if (host_idx > max_num_hosts) then break end end aggregation_ids = {} if(host_info["host"] ~= nil) then aggregations = interface.getAggregationsForHost(host_info["host"]) else aggregations = {} end for name,num_contacts in pairs(aggregations) do aggregation_ids[name] = num hosts_id[name] = { } hosts_id[name]['count'] = num_contacts hosts_id[name]['id'] = num ids[num] = name if(links > 0) then print(",") end print('\n{"source":'..num..',"target": 0,"depth":6,"count":'..num_contacts..',"styleColumn":"aggregation"}') links = links + 1 num = num + 1 end tot_hosts = num print [[ ],"nodes":[ ]] -- Nodes min_size = 5 maxval = 0 for k,v in pairs(hosts_id) do if(v['count'] > maxval) then maxval = v['count'] end end num = 0 for i=0,tot_hosts-1 do k = ids[i] v = hosts_id[k] k_info = hostkey2hostinfo(k) target_host = interface.getHostInfo(k) if(target_host ~= nil) then name = target_host["name"] if(name ~= nil) then name = name else name = ntop.getResolvedAddress(k_info["host"]) target_host["name"] = name end if(target_host['localhost'] ~= nil) then label = "local" else label = "remote" end else name = k if(aggregations[k] ~= nil) then label = "aggregation" else label = "remote" end end if ((host_info["host"] ~= nil) and (host_info["host"] == k_info["host"])) then label = "sun" end -- f(name == k) then name = ntop.getResolvedAddress(k) end if(name == nil) then name = k end if(maxval == 0) then tot = maxval else tot = math.floor(0.5+(v['count']*100)/maxval) if(tot < min_size) then tot = min_size end end if(num > 0) then print(",") end print('\n{"name":"'.. name ..'","count":'.. tot ..',"group":"' .. label .. '","linkCount": '.. tot .. ',"label":"'.. name..'"') if(target_host ~= nil) then -- Host still in memory if((host_info["host"] == nil) or (k_info["host"] ~= host_info["host"])) then print(', "link": "'..ntop.getHttpPrefix()..'/lua/hosts_interaction.lua?"}') else print(', "link": "'..ntop.getHttpPrefix()..'/lua/host_details.lua?host='.. k.. '"}') end else -- print('->>'..k..'<<-\n') if(aggregations[k] ~= nil) then print(', "link": "'..ntop.getHttpPrefix()..'/lua/aggregated_host_details.lua?host='.. k .. '"}') else -- Host purged ? print(', "link": ""}') end end num = num + 1 end if ((num == 0) and (host_info["host"] ~= nil)) then tot = 1 label = "" name = host_info["host"] print('\n{"name":"'.. name ..'","count":'.. tot ..',"group":"' .. label .. '","linkCount": '.. tot .. ',"label":"'.. name..'", "link": "'..ntop.getHttpPrefix()..'/lua/host_details.lua?host='.. hostinfo2hostkey(host_info).. '"}') end print [[ ] }}}; </script> <div id="chart"></div> <p>&nbsp;<p><small><b>NOTE</b></small> <ol> ]] if(host_info["host"] ~= nil) then print('<li><small>This map is centered on host <font color="#fd8d3c">'.. hostinfo2hostkey(host_info)) if(host_name ~= nil) then print('('.. host_name .. ')') end print('</font>. Clicking on this host you will visualize its details.</small></li>\n') else print('<li><small>This map depicts the interactions of the top '.. num_top_hosts .. ' hosts.</small></li>\n') end print('<li><small>Color map: <font color=#aec7e8><b>local</b></font>, <font color=#bcbd22><b>remote</b></font>, <font color=#008d3c><b>aggregation</b></font>, <font color=#fd8d3c><b>focus</b></font> host.</small></li>\n') print [[ <li> <small>Click is enabled only for hosts that have not been purged from memory.</small></li> </ol> <!-- http://ramblings.mcpher.com/Home/excelquirks/d3 --> <script type="text/javascript"> doTheTreeViz("#chart", ntopData); </script> ]] else print("<div class=\"alert alert-danger\"><img src=".. ntop.getHttpPrefix() .. "/img/warning.png> No results found</div>") end if(mode ~= "embed") then dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua") end
gpl-3.0
AresTao/darkstar
scripts/globals/spells/bluemagic/mysterious_light.lua
18
1889
----------------------------------------- -- Spell: Mysterious Light -- Deals wind damage to enemies within range. Additional effect: Weight -- Spell cost: 73 MP -- Monster Type: Arcana -- Spell Type: Magical (Wind) -- Blue Magic Points: 4 -- Stat Bonus: AGI+3 -- Level: 40 -- Casting Time: 3.75 seconds -- Recast Time: 24.5 seconds -- Magic Bursts on: Detonation, Fragmentation, Light -- Combos: Max MP Boost ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.multiplier = 2.0; params.tMultiplier = 1.0; params.duppercap = 56; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.2; damage = BlueMagicalSpell(caster, target, spell, params, CHR_BASED); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (damage > 0 and resist > 0.0625) then local typeEffect = EFFECT_WEIGHT; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,4,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
AresTao/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Animated_Tabar.lua
16
1477
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Animated Tabar ----------------------------------- require("scripts/globals/status"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if (mob:AnimationSub() == 3) then SetDropRate(116,1575,1000); else SetDropRate(116,1575,0); end target:showText(mob,ANIMATED_TABAR_DIALOG); SpawnMob(17330380,120):updateEnmity(target); SpawnMob(17330381,120):updateEnmity(target); SpawnMob(17330382,120):updateEnmity(target); SpawnMob(17330392,120):updateEnmity(target); SpawnMob(17330393,120):updateEnmity(target); SpawnMob(17330394,120):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) -- TODO: add battle dialog end; ----------------------------------- -- onMobDisengage ----------------------------------- function onMobDisengage(mob) mob:showText(mob,ANIMATED_TABAR_DIALOG+2); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) killer:showText(mob,ANIMATED_TABAR_DIALOG+1); DespawnMob(17330380); DespawnMob(17330381); DespawnMob(17330382); DespawnMob(17330392); DespawnMob(17330393); DespawnMob(17330394); end;
gpl-3.0
Gedo789/TrackAssemblyTool
lua/trackassembly/lang/ru.lua
1
12282
return function(sTool, sLimit) local tSet = {} -- Russian tSet["tool."..sTool..".workmode.1" ] = "Общее создание/прилепание куски" tSet["tool."..sTool..".workmode.2" ] = "Пересечение активной точки" tSet["tool."..sTool..".workmode.3" ] = "Кривой отрезок линии фитинг" tSet["tool."..sTool..".workmode.4" ] = "Нормаль поверхности перевернуть" tSet["tool."..sTool..".desc" ] = "Создает дорогу для транспортных средств" tSet["tool."..sTool..".name" ] = "Сборка дороги" tSet["tool."..sTool..".phytype" ] = "Выберите тип физических свойств из тех которые перечислены здесь" tSet["tool."..sTool..".phytype_con" ] = "Тип поверхности:" tSet["tool."..sTool..".phytype_def" ] = "<Выберите ТИП поверхности>" tSet["tool."..sTool..".phyname" ] = "Выберите имя физических свойств которые могут быть использованы при создании дороги так как это повлияет на поверхностное трение" tSet["tool."..sTool..".phyname_con" ] = "Имя поверхности:" tSet["tool."..sTool..".phyname_def" ] = "<Выберите ИМЯ поверхности>" tSet["tool."..sTool..".bgskids" ] = "Код выбора через запятую для Группа-тела/Кожа ID" tSet["tool."..sTool..".bgskids_con" ] = "Группа-тела/Кожа:" tSet["tool."..sTool..".bgskids_def" ] = "Написать код выбора здесь. Например 1,0,0,2,1/3" tSet["tool."..sTool..".mass" ] = "Как тяжелый кусок создал будет" tSet["tool."..sTool..".mass_con" ] = "Масса куска:" tSet["tool."..sTool..".model" ] = "Выберите кусок чтобы начать/продолжить свою дорогу выбирая тип дерева и нажав на листе" tSet["tool."..sTool..".model_con" ] = "Модель куска:" tSet["tool."..sTool..".activrad" ] = "Минимальное расстояние чтобы выбрать активную точку" tSet["tool."..sTool..".activrad_con" ] = "Активный радиус:" tSet["tool."..sTool..".stackcnt" ] = "Максимальное количество куски для нагромождения" tSet["tool."..sTool..".stackcnt_con" ] = "Количество кусков:" tSet["tool."..sTool..".angsnap" ] = "Приклейте первый кусок созданный тем положением градусов" tSet["tool."..sTool..".angsnap_con" ] = "Угловое выравнивание:" tSet["tool."..sTool..".resetvars" ] = "Нажмите чтобы сбросить дополнительные значения" tSet["tool."..sTool..".resetvars_con" ] = "V Сбросить переменные V" tSet["tool."..sTool..".nextpic" ] = "Дополнительный сдвиг начала тангажом" tSet["tool."..sTool..".nextpic_con" ] = "Начало тангажа:" tSet["tool."..sTool..".nextyaw" ] = "Дополнительный сдвиг начала рысканием" tSet["tool."..sTool..".nextyaw_con" ] = "Начало рыскания:" tSet["tool."..sTool..".nextrol" ] = "Дополнительный сдвиг начала рулона" tSet["tool."..sTool..".nextrol_con" ] = "Начало рулона:" tSet["tool."..sTool..".nextx" ] = "Дополнительное линейное смещение X" tSet["tool."..sTool..".nextx_con" ] = "Смещения X:" tSet["tool."..sTool..".nexty" ] = "Дополнительное линейное смещение Y" tSet["tool."..sTool..".nexty_con" ] = "Смещения Y:" tSet["tool."..sTool..".nextz" ] = "Дополнительное линейное смещение Z" tSet["tool."..sTool..".nextz_con" ] = "Смещения Z:" tSet["tool."..sTool..".gravity" ] = "Управляет гравитацию куска" tSet["tool."..sTool..".gravity_con" ] = "Применить силу тяжести к куске" tSet["tool."..sTool..".weld" ] = "Создает сварные швы между кусками или кусоком/якорем" tSet["tool."..sTool..".weld_con" ] = "Сварной шов" tSet["tool."..sTool..".forcelim" ] = "Управляет сколько сил требуется чтобы сломать сварной шов" tSet["tool."..sTool..".forcelim_con" ] = "Ограничение силы:" tSet["tool."..sTool..".ignphysgn" ] = "Игнорирует захвата физической пушки при созданием/приклеиванием/нагромождением куска" tSet["tool."..sTool..".ignphysgn_con" ] = "Игнорирует захвата физической пушки" tSet["tool."..sTool..".nocollide" ] = "Делает не-столкновение между кусками или кусоком/якорем" tSet["tool."..sTool..".nocollide_con" ] = "Не-столкновение" tSet["tool."..sTool..".nocollidew" ] = "Делает не-столкновение между кусками и миром" tSet["tool."..sTool..".nocollidew_con"] = "Не-столкновение миром" tSet["tool."..sTool..".freeze" ] = "Создает заморожений кусок" tSet["tool."..sTool..".freeze_con" ] = "Заморозить кусок" tSet["tool."..sTool..".igntype" ] = "Игнорирует различные типы кусков прилипания/накопления" tSet["tool."..sTool..".igntype_con" ] = "Игнорировать тип кусков" tSet["tool."..sTool..".spnflat" ] = "Следующий кусок будет создан/приклеен/накоплен по горизонтали" tSet["tool."..sTool..".spnflat_con" ] = "Нагромождать по горизонтали" tSet["tool."..sTool..".spawncn" ] = "Создание куска в центре иначе в выбранной активной точке" tSet["tool."..sTool..".spawncn_con" ] = "Происхождение из центра" tSet["tool."..sTool..".surfsnap" ] = "Приклеить кусок к поверхности к которой ссылается пользователь" tSet["tool."..sTool..".surfsnap_con" ] = "Приклеивать к поверхности" tSet["tool."..sTool..".appangfst" ] = "Применять угловое смещение только на первой кусок" tSet["tool."..sTool..".appangfst_con" ] = "Применять угловое на первой" tSet["tool."..sTool..".applinfst" ] = "Применять линейное смещение только на первой кусок" tSet["tool."..sTool..".applinfst_con" ] = "Применять линейное на первой" tSet["tool."..sTool..".adviser" ] = "Управляет отображением позиционного/углового советника" tSet["tool."..sTool..".adviser_con" ] = "Нарисовать советник" tSet["tool."..sTool..".pntasist" ] = "Управляет изображение помощника для прилипания" tSet["tool."..sTool..".pntasist_con" ] = "Нарисовать помощника" tSet["tool."..sTool..".ghostcnt" ] = "Управляет подсчет отображением куска-тени" tSet["tool."..sTool..".ghostcnt_con" ] = "Нарисовать подсчет кусок-тень" tSet["tool."..sTool..".engunsnap" ] = "Управляет приклеивание когда кусок выпущен физической пушки пользователя" tSet["tool."..sTool..".engunsnap_con" ] = "Приклеивать выпуском" tSet["tool."..sTool..".type" ] = "Выберите типа дороги для использования путем расширения папки" tSet["tool."..sTool..".type_con" ] = "Тип дороги:" tSet["tool."..sTool..".category" ] = "Выберите категорию дороги для использования путем расширения папки" tSet["tool."..sTool..".category_con" ] = "Категория дороги:" tSet["tool."..sTool..".workmode" ] = "Измените эту опцию чтобы использовать другой рабочий режим" tSet["tool."..sTool..".workmode_con" ] = "Рабочий режим:" tSet["tool."..sTool..".pn_export" ] = "Нажмите чтобы сохранить файл базы данных" tSet["tool."..sTool..".pn_export_lb" ] = "Экспорт БД" tSet["tool."..sTool..".pn_routine" ] = "Список регулярно используемых кусков дороги" tSet["tool."..sTool..".pn_routine_hd" ] = "Часто используемых кусков пользователя:" tSet["tool."..sTool..".pn_externdb" ] = "Внешние базы данных доступные для:" tSet["tool."..sTool..".pn_externdb_hd"] = "Внешние базы данных для:" tSet["tool."..sTool..".pn_externdb_lb"] = "Нажмите правой для вариантов:" tSet["tool."..sTool..".pn_externdb_1" ] = "Скопировать префикс" tSet["tool."..sTool..".pn_externdb_2" ] = "Скопировать път папку DSV" tSet["tool."..sTool..".pn_externdb_3" ] = "Скопировать ник таблицу" tSet["tool."..sTool..".pn_externdb_4" ] = "Скопировать път таблицу" tSet["tool."..sTool..".pn_externdb_5" ] = "Скопировать время таблицу" tSet["tool."..sTool..".pn_externdb_6" ] = "Скопировать размер таблицу" tSet["tool."..sTool..".pn_externdb_7" ] = "Изменить элементы (Luapad)" tSet["tool."..sTool..".pn_externdb_8" ] = "Удалить файл базы данных" tSet["tool."..sTool..".pn_ext_dsv_lb" ] = "Внешний список DSV" tSet["tool."..sTool..".pn_ext_dsv_hd" ] = "Список внешних баз данных DSV отображается здесь" tSet["tool."..sTool..".pn_ext_dsv_1" ] = "Уникальный префикс базы данных" tSet["tool."..sTool..".pn_ext_dsv_2" ] = "Активный" tSet["tool."..sTool..".pn_display" ] = "Модель вашего куска дороги здесь отображается" tSet["tool."..sTool..".pn_pattern" ] = "Напишите шаблон здесь и нажмите ВВОД для выполнения поиска" tSet["tool."..sTool..".pn_srchcol" ] = "Выберите столбец для поиска" tSet["tool."..sTool..".pn_srchcol_lb" ] = "<Искать по>" tSet["tool."..sTool..".pn_srchcol_lb1"] = "Модель" tSet["tool."..sTool..".pn_srchcol_lb2"] = "Тип" tSet["tool."..sTool..".pn_srchcol_lb3"] = "Имя" tSet["tool."..sTool..".pn_srchcol_lb4"] = "Конец" tSet["tool."..sTool..".pn_routine_lb" ] = "Часто используемых кусков" tSet["tool."..sTool..".pn_routine_lb1"] = "Срок" tSet["tool."..sTool..".pn_routine_lb2"] = "Конец" tSet["tool."..sTool..".pn_routine_lb3"] = "Тип" tSet["tool."..sTool..".pn_routine_lb4"] = "Имя" tSet["tool."..sTool..".pn_display_lb" ] = "Показать кусок" tSet["tool."..sTool..".pn_pattern_lb" ] = "Напишите шаблон" tSet["Cleanup_"..sLimit ] = "Собранные куски дороги" tSet["Cleaned_"..sLimit ] = "Все куски дороги очищены" tSet["SBoxLimit_"..sLimit ] = "Вы достигли предела созданных кусков дороги!" return tSet end
agpl-3.0
AresTao/darkstar
scripts/zones/Abyssea-Attohwa/npcs/Cavernous_Maw.lua
17
1245
----------------------------------- -- Area: Abyssea - Attohwa -- NPC: Cavernous Maw -- @pos -133.197 20.242 -181.658 215 -- Notes: Teleports Players to Buburimu Peninsula ----------------------------------- package.loaded["scripts/zones/Abyssea-Attohwa/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Abyssea-Attohwa/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00c8); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00c8 and option == 1) then player:setPos(-338,-23,47,167,118); end end;
gpl-3.0
AresTao/darkstar
scripts/zones/Heavens_Tower/npcs/Chumimi.lua
17
5934
----------------------------------- -- Area: Heaven's Tower -- NPC: Chumimi -- Starts and Finishes Quest: The Three Magi, Recollections -- @pos 0.1 30 21 242 ----------------------------------- package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Heavens_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(WINDURST,THE_THREE_MAGI) == QUEST_ACCEPTED) then if (trade:hasItemQty(1104,1) and trade:getItemCount() == 1) then -- Trade Glowstone player:startEvent(0x010d); -- Finish Quest "The Three Magi" end elseif (player:getQuestStatus(WINDURST,RECOLLECTIONS) == QUEST_ACCEPTED and player:getVar("recollectionsQuest") < 2) then if (trade:hasItemQty(1105,1) and trade:getItemCount() == 1) then player:startEvent(0x010F); end elseif (player:getQuestStatus(WINDURST,THE_ROOT_OF_THE_PROBLEM) == QUEST_ACCEPTED and player:getVar("rootProblem") == 1) then if (trade:hasItemQty(829,1) and trade:getItemCount() == 1) then player:startEvent(0x0116); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local theThreeMagi = player:getQuestStatus(WINDURST,THE_THREE_MAGI); local recollections = player:getQuestStatus(WINDURST,RECOLLECTIONS); local rootProblem = player:getQuestStatus(WINDURST,THE_ROOT_OF_THE_PROBLEM); local mLvl = player:getMainLvl(); local mJob = player:getMainJob(); if (theThreeMagi == QUEST_AVAILABLE and mJob == 4 and mLvl >= AF1_QUEST_LEVEL) then player:startEvent(0x0104,0,613,0,0,0,1104); -- Start Quest "The Three Magi" --- NOTE: 5th parameter is "Meteorites" but he doesn't exist --- elseif (theThreeMagi == QUEST_ACCEPTED) then player:startEvent(0x0105,0,0,0,0,0,1104); -- During Quest "The Three Magi" elseif (theThreeMagi == QUEST_COMPLETED and recollections == QUEST_AVAILABLE and (mJob == 4 and mLvl < AF2_QUEST_LEVEL or mJob ~= 4)) then player:startEvent(0x010c); -- New standard dialog after "The Three Magi" elseif (theThreeMagi == QUEST_COMPLETED and mJob == 4 and mLvl >= AF2_QUEST_LEVEL and player:needToZone() == false and recollections == QUEST_AVAILABLE) then player:startEvent(0x010E,0,1105); -- Start Quest "Recollections" elseif (recollections == QUEST_ACCEPTED and player:hasKeyItem(FOE_FINDER_MK_I)) then player:startEvent(0x0113); -- Finish Quest "Recollections" elseif (recollections == QUEST_COMPLETED and rootProblem == QUEST_AVAILABLE and mJob == 4 and mLvl >= 50 and player:needToZone() == false) then player:startEvent(0x114,0,829); -- Start Quest "The Root of The problem" elseif (rootProblem == QUEST_ACCEPTED) then if (player:getVar("rootProblem") == 1) then player:startEvent(0x115,0,829); elseif (player:getVar("rootProblem") == 2) then player:startEvent(0x117); elseif ( player:getVar("rootProblem") == 3) then player:startEvent(0x119); end else player:startEvent(0x0103); -- 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 == 0x0104) then -- option 3: Koru-Moru -- option 2: Shantotto -- option 1: Yoran-Oran player:addQuest(WINDURST,THE_THREE_MAGI); player:setVar("theThreeMagiSupport",option); elseif (csid == 0x010d) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17423); -- Casting Wand else choosetitle = player:getVar("theThreeMagiSupport"); if (choosetitle == 3) then player:addTitle(PROFESSOR_KORUMORU_SUPPORTER); elseif (choosetitle == 2) then player:addTitle(DOCTOR_SHANTOTTO_SUPPORTER); else player:addTitle(DOCTOR_YORANORAN_SUPPORTER); end player:tradeComplete(); player:addItem(17423); player:messageSpecial(ITEM_OBTAINED, 17423); -- Casting Wand player:needToZone(true); player:setVar("theThreeMagiSupport",0); player:addFame(WINDURST,WIN_FAME*AF1_FAME); player:completeQuest(WINDURST,THE_THREE_MAGI); end elseif (csid == 0x010E) then player:addQuest(WINDURST,RECOLLECTIONS); elseif (csid == 0x010F) then player:tradeComplete(); player:setVar("recollectionsQuest",2); elseif (csid == 0x0113) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14092); -- wizards sabots else player:setVar("recollectionsQuest",0); player:delKeyItem(FOE_FINDER_MK_I); player:addItem(14092); player:messageSpecial(ITEM_OBTAINED,14092); -- wizards sabots player:addFame(WINDURST,WIN_FAME*AF2_FAME); player:completeQuest(WINDURST,RECOLLECTIONS); end elseif (csid == 0x0114) then player:addQuest(WINDURST,THE_ROOT_OF_THE_PROBLEM); player:setVar("rootProblem",1); elseif (csid == 0x117) then player:addKeyItem(SLUICE_SURVEYOR_MK_I); player:messageSpecial(KEYITEM_OBTAINED,SLUICE_SURVEYOR_MK_I); elseif (csid == 0x119) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED); else player:completeQuest(WINDURST,THE_ROOT_OF_THE_PROBLEM); player:addItem(13856); player:messageSpecial(ITEM_OBTAINED,13856); player:addTitle(PARAGON_OF_BLACK_MAGE_EXCELLENCE); player:delKeyItem(SLUICE_SURVEYOR_MK_I); end end end;
gpl-3.0
AresTao/darkstar
scripts/zones/Vunkerl_Inlet_[S]/npcs/Leafy_Patch.lua
45
1646
----------------------------------- -- Area: Vunkerl Inlet (S) (F-5) -- NPC: Leafy Patch -- Involved in Quests -- @pos -418 -33 576 ----------------------------------- package.loaded["scripts/zones/Vunkerl_Inlet_[S]/TextIDs"] = nil; package.loaded["scripts/globals/quests"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Vunkerl_Inlet_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(CRYSTAL_WAR, BOY_AND_THE_BEAST) == QUEST_ACCEPTED and player:getVar("BoyAndTheBeast") == 2) then if (VanadielHour() < 8) then player:startEvent(0x006B); elseif (VanadielHour() < 16) then player:startEvent(0x006B,1); else player:startEvent(0x006B,2); end end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x006B) then if (option == 1) then player:addKeyItem(VUNKERL_HERB); player:messageSpecial(KEYITEM_OBTAINED, VUNKERL_HERB); player:setVar("BoyAndTheBeast",3); else player:addKeyItem(VUNKERL_HERB); player:messageSpecial(KEYITEM_OBTAINED, VUNKERL_HERB); player:setVar("BoyAndTheBeast",4); end end end;
gpl-3.0
AresTao/darkstar
scripts/zones/Windurst_Waters_[S]/npcs/Pahpe_Rauulih.lua
38
1053
----------------------------------- -- Area: Windurst Waters (S) -- NPC: Pahpe Rauulih -- Type: Standard NPC -- @zone: 94 -- @pos -39.740 -4.499 53.223 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01ab); 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
AresTao/darkstar
scripts/zones/Western_Altepa_Desert/Zone.lua
27
4592
----------------------------------- -- -- Zone: Western_Altepa_Desert (125) -- ----------------------------------- package.loaded["scripts/zones/Western_Altepa_Desert/TextIDs"] = nil; package.loaded["scripts/globals/chocobo_digging"] = nil; ----------------------------------- require("scripts/zones/Western_Altepa_Desert/TextIDs"); require("scripts/globals/icanheararainbow"); require("scripts/globals/weather"); require("scripts/globals/zone"); require("scripts/globals/chocobo_digging"); ----------------------------------- -- Chocobo Digging vars ----------------------------------- local itemMap = { -- itemid, abundance, requirement { 880, 224, DIGREQ_NONE }, { 887, 39, DIGREQ_NONE }, { 645, 14, DIGREQ_NONE }, { 893, 105, DIGREQ_NONE }, { 737, 17, DIGREQ_NONE }, { 643, 64, DIGREQ_NONE }, { 17296, 122, DIGREQ_NONE }, { 942, 6, DIGREQ_NONE }, { 642, 58, DIGREQ_NONE }, { 864, 22, DIGREQ_NONE }, { 843, 4, DIGREQ_NONE }, { 4096, 100, DIGREQ_NONE }, -- all crystals { 845, 122, DIGREQ_BURROW }, { 844, 71, DIGREQ_BURROW }, { 1845, 33, DIGREQ_BURROW }, { 838, 11, DIGREQ_BURROW }, { 902, 6, DIGREQ_BORE }, { 886, 3, DIGREQ_BORE }, { 867, 3, DIGREQ_BORE }, { 1587, 19, DIGREQ_BORE }, { 888, 25, DIGREQ_BORE }, { 1586, 8, DIGREQ_BORE }, { 885, 10, DIGREQ_BORE }, { 866, 3, DIGREQ_BORE }, { 4570, 10, DIGREQ_MODIFIER }, { 4487, 11, DIGREQ_MODIFIER }, { 4409, 12, DIGREQ_MODIFIER }, { 1188, 10, DIGREQ_MODIFIER }, { 4532, 12, DIGREQ_MODIFIER }, }; local messageArray = { DIG_THROW_AWAY, FIND_NOTHING, ITEM_OBTAINED }; ----------------------------------- -- onChocoboDig ----------------------------------- function onChocoboDig(player, precheck) return chocoboDig(player, itemMap, precheck, messageArray); end; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17289795,17289796,17289797}; SetFieldManual(manuals); -- King Vinegarroon SetRespawnTime(17289575, 900, 10800); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if ( player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( -19.901, 13.607, 440.058, 78); end if ( triggerLightCutscene( player)) then -- Quest: I Can Hear A Rainbow cs = 0x0002; end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if ( csid == 0x0002) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0002) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow end end; function onZoneWeatherChange(weather) if (GetMobAction(17289575) == 24 and (weather == WEATHER_DUST_STORM or weather == WEATHER_SAND_STORM)) then SpawnMob(17289575); -- King Vinegarroon elseif (GetMobAction(17289575) == 16 and (weather ~= WEATHER_DUST_STORM and weather ~= WEATHER_SAND_STORM)) then DespawnMob(17289575); end end;
gpl-3.0
AresTao/darkstar
scripts/zones/Castle_Oztroja/npcs/_47v.lua
17
1251
----------------------------------- -- Area: Castle Oztroja -- NPC: _47v (Handle) -- Notes: Opens door _472 from behind -- @pos -61 0 -36 151 ----------------------------------- package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Castle_Oztroja/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorID = npc:getID() - 1; local DoorA = GetNPCByID(DoorID):getAnimation(); if (player:getZPos() < -32) then if (DoorA == 9 and npc:getAnimation() == 9) then npc:openDoor(6.5); -- Should be a ~1 second delay here before the door opens GetNPCByID(DoorID):openDoor(4.5); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
patrikrm13/AVENGERS_ANTISPAMEER
plugins/time.lua
771
2865
-- Implement a command !time [area] which uses -- 2 Google APIs to get the desired result: -- 1. Geocoding to get from area to a lat/long pair -- 2. Timezone to get the local time in that lat/long location -- Globals -- If you have a google api key for the geocoding/timezone api api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "The local time in "..timeZoneId.." is: ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "!time [area]: Displays the local time in that area", patterns = {"^!time (.*)$"}, run = run }
gpl-2.0
AresTao/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/HomePoint#4.lua
19
1216
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: HomePoint#4 -- @pos -99 -6 -68 50 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21ff, 108); 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 == 0x21ff) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
AresTao/darkstar
scripts/globals/weaponskills/ruinator.lua
30
1646
----------------------------------- -- Ruinator -- Axe weapon skill -- Skill level: 357 -- Description: Delivers a four-hit attack. params.accuracy varies with TP -- In order to obtain Ruinator, the quest Martial Mastery must be completed. -- This Weapon Skill's first hit params.ftp is duplicated for all additional hits -- Aligned with the Aqua Gorget, Snow Gorget & Breeze Gorget -- Aligned with the Aqua Belt, Snow Belt & Breeze Belt. -- Element: None -- Modifiers: STR:73~85%, depending on merit points upgrades. -- 100%TP 200%TP 300%TP -- 1.08 1.08 1.08 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 4; params.ftp100 = 1.08; params.ftp200 = 1.08; params.ftp300 = 1.08; params.str_wsc = 0.85 + (player:getMerit(MERIT_RUINATOR) / 100); params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1.0; params.atkmulti = 1.1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.7 + (player:getMerit(MERIT_RUINATOR) / 100); end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
yinjun322/skynet
lualib/http/httpc.lua
42
2906
local socket = require "http.sockethelper" local url = require "http.url" local internal = require "http.internal" local string = string local table = table local httpc = {} local function request(fd, method, host, url, recvheader, header, content) local read = socket.readfunc(fd) local write = socket.writefunc(fd) local header_content = "" if header then if not header.host then header.host = host end for k,v in pairs(header) do header_content = string.format("%s%s:%s\r\n", header_content, k, v) end else header_content = string.format("host:%s\r\n",host) end if content then local data = string.format("%s %s HTTP/1.1\r\n%scontent-length:%d\r\n\r\n%s", method, url, header_content, #content, content) write(data) else local request_header = string.format("%s %s HTTP/1.1\r\n%scontent-length:0\r\n\r\n", method, url, header_content) write(request_header) end local tmpline = {} local body = internal.recvheader(read, tmpline, "") if not body then error(socket.socket_error) end local statusline = tmpline[1] local code, info = statusline:match "HTTP/[%d%.]+%s+([%d]+)%s+(.*)$" code = assert(tonumber(code)) local header = internal.parseheader(tmpline,2,recvheader or {}) if not header then error("Invalid HTTP response header") end local length = header["content-length"] if length then length = tonumber(length) end local mode = header["transfer-encoding"] if mode then if mode ~= "identity" and mode ~= "chunked" then error ("Unsupport transfer-encoding") end end if mode == "chunked" then body, header = internal.recvchunkedbody(read, nil, header, body) if not body then error("Invalid response body") end else -- identity mode if length then if #body >= length then body = body:sub(1,length) else local padding = read(length - #body) body = body .. padding end else body = nil end end return code, body end function httpc.request(method, host, url, recvheader, header, content) local hostname, port = host:match"([^:]+):?(%d*)$" if port == "" then port = 80 else port = tonumber(port) end local fd = socket.connect(hostname, port) local ok , statuscode, body = pcall(request, fd,method, host, url, recvheader, header, content) socket.close(fd) if ok then return statuscode, body else error(statuscode) end end function httpc.get(...) return httpc.request("GET", ...) end local function escape(s) return (string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02X", string.byte(c)) end)) end function httpc.post(host, url, form, recvheader) local header = { ["content-type"] = "application/x-www-form-urlencoded" } local body = {} for k,v in pairs(form) do table.insert(body, string.format("%s=%s",escape(k),escape(v))) end return httpc.request("POST", host, url, recvheader, header, table.concat(body , "&")) end return httpc
mit
balabit/zorp-openwrt-feed
net/mwan3-luci/files/usr/lib/lua/luci/model/cbi/mwan/ruleconfig.lua
14
4185
-- ------ extra functions ------ -- function ruleCheck() -- determine if rule needs a protocol specified local sourcePort = ut.trim(sys.exec("uci get -p /var/state mwan3." .. arg[1] .. ".src_port")) local destPort = ut.trim(sys.exec("uci get -p /var/state mwan3." .. arg[1] .. ".dest_port")) if sourcePort ~= "" or destPort ~= "" then -- ports configured local protocol = ut.trim(sys.exec("uci get -p /var/state mwan3." .. arg[1] .. ".proto")) if protocol == "" or protocol == "all" then -- no or improper protocol error_protocol = 1 end end end function ruleWarn() -- display warning message at the top of the page if error_protocol == 1 then return "<font color=\"ff0000\"><strong>WARNING: this rule is incorrectly configured with no or improper protocol specified! Please configure a specific protocol!</strong></font>" else return "" end end function cbiAddPolicy(field) uci.cursor():foreach("mwan3", "policy", function (section) field:value(section[".name"]) end ) end function cbiAddProtocol(field) local protocols = ut.trim(sys.exec("cat /etc/protocols | grep ' # ' | awk '{print $1}' | grep -vw -e 'ip' -e 'tcp' -e 'udp' -e 'icmp' -e 'esp' | grep -v 'ipv6' | sort | tr '\n' ' '")) for p in string.gmatch(protocols, "%S+") do field:value(p) end end -- ------ rule configuration ------ -- dsp = require "luci.dispatcher" sys = require "luci.sys" ut = require "luci.util" arg[1] = arg[1] or "" error_protocol = 0 ruleCheck() m5 = Map("mwan3", translate("MWAN Rule Configuration - ") .. arg[1], translate(ruleWarn())) m5.redirect = dsp.build_url("admin", "network", "mwan", "configuration", "rule") mwan_rule = m5:section(NamedSection, arg[1], "rule", "") mwan_rule.addremove = false mwan_rule.dynamic = false src_ip = mwan_rule:option(Value, "src_ip", translate("Source address"), translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes")) src_ip.datatype = ipaddr src_port = mwan_rule:option(Value, "src_port", translate("Source port"), translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes")) dest_ip = mwan_rule:option(Value, "dest_ip", translate("Destination address"), translate("Supports CIDR notation (eg \"192.168.100.0/24\") without quotes")) dest_ip.datatype = ipaddr dest_port = mwan_rule:option(Value, "dest_port", translate("Destination port"), translate("May be entered as a single or multiple port(s) (eg \"22\" or \"80,443\") or as a portrange (eg \"1024:2048\") without quotes")) proto = mwan_rule:option(Value, "proto", translate("Protocol"), translate("View the contents of /etc/protocols for protocol descriptions")) proto.default = "all" proto.rmempty = false proto:value("all") proto:value("ip") proto:value("tcp") proto:value("udp") proto:value("icmp") proto:value("esp") cbiAddProtocol(proto) sticky = mwan_rule:option(ListValue, "sticky", translate("Sticky"), translate("Traffic from the same source IP address that previously matched this rule within the sticky timeout period will use the same WAN interface")) sticky.default = "0" sticky:value("1", translate("Yes")) sticky:value("0", translate("No")) timeout = mwan_rule:option(Value, "timeout", translate("Sticky timeout"), translate("Seconds. Acceptable values: 1-1000000. Defaults to 600 if not set")) timeout.datatype = "range(1, 1000000)" ipset = mwan_rule:option(Value, "ipset", translate("IPset"), translate("Name of IPset rule. Requires IPset rule in /etc/dnsmasq.conf (eg \"ipset=/youtube.com/youtube\")")) use_policy = mwan_rule:option(Value, "use_policy", translate("Policy assigned")) cbiAddPolicy(use_policy) use_policy:value("unreachable", translate("unreachable (reject)")) use_policy:value("blackhole", translate("blackhole (drop)")) use_policy:value("default", translate("default (use main routing table)")) -- ------ currently configured policies ------ -- mwan_policy = m5:section(TypedSection, "policy", translate("Currently Configured Policies")) mwan_policy.addremove = false mwan_policy.dynamic = false mwan_policy.sortable = false mwan_policy.template = "cbi/tblsection" return m5
gpl-2.0
goldpizza44/automation
asterisk/etc/extensions.lua
1
5756
CONSOLE = "Console/dsp" -- Console interface for demo --CONSOLE = "Zap/1" --CONSOLE = "Phone/phone0" IAXINFO = "guest" -- IAXtel username/password --IAXINFO = "myuser:mypass" TRUNK = "Zap/G2" TRUNKMSD = 1 -- TRUNK = "IAX2/user:pass@provider" -- -- Extensions are expected to be defined in a global table named 'extensions'. -- The 'extensions' table should have a group of tables in it, each -- representing a context. Extensions are defined in each context. See below -- for examples. -- -- This file can be automatically included in the extensions.conf file using -- the 'utils/build-extensions-conf.lua' script and a #exec statement in -- extensions.conf. -- -- #exec /usr/bin/utils/build-extensions.conf.lua -c -- -- The 'execincludes' option must be set to 'yes' in the [options] section of -- asterisk.conf for this to work properly. -- -- Extension names may be numbers, letters, or combinations thereof. If -- an extension name is prefixed by a '_' character, it is interpreted as -- a pattern rather than a literal. In patterns, some characters have -- special meanings: -- -- X - any digit from 0-9 -- Z - any digit from 1-9 -- N - any digit from 2-9 -- [1235-9] - any digit in the brackets (in this example, 1,2,3,5,6,7,8,9) -- . - wildcard, matches anything remaining (e.g. _9011. matches -- anything starting with 9011 excluding 9011 itself) -- ! - wildcard, causes the matching process to complete as soon as -- it can unambiguously determine that no other matches are possible -- -- For example the extension _NXXXXXX would match normal 7 digit -- dialings, while _1NXXNXXXXXX would represent an area code plus phone -- number preceded by a one. -- -- If your extension has special characters in it such as '.' and '!' you must -- explicitly make it a string in the tabale definition: -- -- ["_special."] = function; -- ["_special!"] = function; -- -- There are no priorities. All extensions to asterisk appear to have a single -- priority as if they consist of a single priority. -- -- Each context is defined as a table in the extensions table. The -- context names should be strings. -- -- One context may be included in another context using the 'includes' -- extension. This extension should be set to a table containing a list -- of context names. Do not put references to tables in the includes -- table. -- -- include = {"a", "b", "c"}; -- -- Channel variables can be accessed thorugh the global 'channel' table. -- -- v = channel.var_name -- v = channel["var_name"] -- v.value -- v:get() -- -- channel.var_name = "value" -- channel["var_name"] = "value" -- v:set("value") -- -- channel.func_name(1,2,3):set("value") -- value = channel.func_name(1,2,3):get() -- -- channel["func_name(1,2,3)"]:set("value") -- channel["func_name(1,2,3)"] = "value" -- value = channel["func_name(1,2,3)"]:get() -- -- Note the use of the ':' operator to access the get() and set() -- methods. -- -- Also notice the absence of the following constructs from the examples above: -- channel.func_name(1,2,3) = "value" -- this will NOT work -- value = channel.func_name(1,2,3) -- this will NOT work as expected -- -- -- Dialplan applications can be accessed through the global 'app' table. -- -- app.Dial("Zap/1") -- app.dial("Zap/1") -- -- More examples can be found below. -- -- Before starting long running operations, an autoservice should be started -- using the autoservice_start() function. This autoservice will automatically -- be stopped before executing applications and dialplan functions and will be -- restarted afterwards. The autoservice can be stopped using -- autoservice_stop() and the autoservice_status() function will return true if -- an autoservice is currently running. -- function outgoing_local(c, e) app.dial("zap/1/" .. e, "", "") end function demo_instruct() app.background("demo-instruct") app.waitexten() end function demo_congrats() app.background("demo-congrats") demo_instruct() end -- Answer the chanel and play the demo sound files function demo_start(context, exten) app.wait(1) app.answer() channel.TIMEOUT("digit"):set(5) channel.TIMEOUT("response"):set(10) -- app.set("TIMEOUT(digit)=5") -- app.set("TIMEOUT(response)=10") demo_congrats(context, exten) end function demo_hangup() app.playback("demo-thanks") app.hangup() end extensions = { demo = { s = demo_start; ["2"] = function() app.background("demo-moreinfo") demo_instruct() end; ["3"] = function () channel.LANGUAGE():set("fr") -- set the language to french demo_congrats() end; ["1000"] = function() app.goto("default", "s", 1) end; ["1234"] = function() app.playback("transfer", "skip") -- do a dial here end; ["1235"] = function() app.voicemail("1234", "u") end; ["1236"] = function() app.dial("Console/dsp") app.voicemail(1234, "b") end; ["#"] = demo_hangup; t = demo_hangup; i = function() app.playback("invalid") demo_instruct() end; ["500"] = function() app.playback("demo-abouttotry") app.dial("IAX2/guest@misery.digium.com/s@default") app.playback("demo-nogo") demo_instruct() end; ["600"] = function() app.playback("demo-echotest") app.echo() app.playback("demo-echodone") demo_instruct() end; ["8500"] = function() app.voicemailmain() demo_instruct() end; }; default = { -- by default, do the demo include = {"demo"}; }; ["local"] = { ["_NXXXXXX"] = outgoing_local; }; }
gpl-3.0
wizardbottttt/X
plugins/rae.lua
616
1312
do function getDulcinea( text ) -- Powered by https://github.com/javierhonduco/dulcinea local api = "http://dulcinea.herokuapp.com/api/?query=" local query_url = api..text local b, code = http.request(query_url) if code ~= 200 then return "Error: HTTP Connection" end dulcinea = json:decode(b) if dulcinea.status == "error" then return "Error: " .. dulcinea.message end while dulcinea.type == "multiple" do text = dulcinea.response[1].id b = http.request(api..text) dulcinea = json:decode(b) end local text = "" local responses = #dulcinea.response if responses == 0 then return "Error: 404 word not found" end if (responses > 5) then responses = 5 end for i = 1, responses, 1 do text = text .. dulcinea.response[i].word .. "\n" local meanings = #dulcinea.response[i].meanings if (meanings > 5) then meanings = 5 end for j = 1, meanings, 1 do local meaning = dulcinea.response[i].meanings[j].meaning text = text .. meaning .. "\n\n" end end return text end function run(msg, matches) return getDulcinea(matches[1]) end return { description = "Spanish dictionary", usage = "!rae [word]: Search that word in Spanish dictionary.", patterns = {"^!rae (.*)$"}, run = run } end
gpl-2.0
omidas77/speedbot
plugins/plugins.lua
28
6273
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local tmp = '\n\n' local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '/Disable➣' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '/Enable➣' end nact = nact+1 end if not only_enabled or status == '/Enable➣' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'.'..status..' '..v..' \n' end end local text = text..'\n\n'..nsum..' plugins installed\n\n'..nact..' plugins enabled\n\n'..nsum-nact..' plugins disabled'..tmp return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '/Disable➣' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '/Enable➣' end nact = nact+1 end if not only_enabled or status == '/Enable➣' then -- get the name v = string.match (v, "(.*)%.lua") -- text = text..v..' '..status..'\n' end end local text = text.."\nAll Plugins Reloaded\n\n"..nact.." Plugins Enabled\n"..nsum.." Plugins Installed" return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return ''..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return ''..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return ' '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return ' '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return ' '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return ' '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if msg.text:match("^[!/#]plugins$") and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == '+' and matches[3] == 'chat' then if is_momod(msg) then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end end -- Enable a plugin if matches[1] == '+' and is_sudo(msg) then --after changed to moderator mode, set only sudo if is_momod(msg) then local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end end -- Disable a plugin on a chat if matches[1] == '-' and matches[3] == 'chat' then if is_momod(msg) then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end end -- Disable a plugin if matches[1] == '-' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == '*' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins - [name] chat : disable plugin only this chat.", "!plugins + [name] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins + [name] : enable plugin.", "!plugins - [name] : disable plugin.", "!plugins * : reloads all plugins." }, }, patterns = { "^[!/#]plugins$", "^[!/#]plugins? (+) ([%w_%.%-]+)$", "^[!/#]plugins? (-) ([%w_%.%-]+)$", "^[!/#]plugins? (+) ([%w_%.%-]+) (chat)", "^[!/#]plugins? (-) ([%w_%.%-]+) (chat)", "^[!/#]plugins? (*)$", }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
AresTao/darkstar
scripts/globals/items/sausage.lua
35
1650
----------------------------------------- -- ID: 4578 -- Item: sausage -- Food Effect: 30Min, All Races ----------------------------------------- -- Health % 3 -- Strength 3 -- Intelligence -1 -- Attack % 27 -- Attack Cap 30 -- Ranged ATT % 27 -- Ranged ATT Cap 30 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4578); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HPP, 3); target:addMod(MOD_STR, 3); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 27); target:addMod(MOD_FOOD_ATT_CAP, 30); target:addMod(MOD_FOOD_RATTP, 27); target:addMod(MOD_FOOD_RATT_CAP, 30); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HPP, 3); target:delMod(MOD_STR, 3); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 27); target:delMod(MOD_FOOD_ATT_CAP, 30); target:delMod(MOD_FOOD_RATTP, 27); target:delMod(MOD_FOOD_RATT_CAP, 30); end;
gpl-3.0
AdiAddons/AdiButtonAuras
config/UserRules.lua
1
7594
--[[ AdiButtonAuras - Display auras on action buttons. Copyright 2013-2022 Adirelle (adirelle@gmail.com) All rights reserved. This file is part of AdiButtonAuras. AdiButtonAuras 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. AdiButtonAuras 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 AdiButtonAuras. If not, see <http://www.gnu.org/licenses/>. --]] local _, private = ... local SAMPLE_RULE = [===[ -- Sample rule using Configure -- See https://github.com/AdiAddons/AdiButtonAuras/blob/master/doc/RulesRef.md#user-rules for more details. -- This rule is only meant as an example and is already included in AdiButtonAuras. Please do not activate it as is. return Configure { -- Unique Id "Execute", -- Description "Hint when the targeted enemy is below 20% health.", -- Spells to modify { 5308, -- Execute (Fury) 163201, -- Execute (Arms) }, -- Unit(s) to watch "enemy", -- Event(s) to watch { "UNIT_HEALTH", "UNIT_MAXHEALTH" }, -- Callback function(units, model) if UnitHealth(units.enemy) / UnitHealthMax(units.enemy) < 0.20 then model.hint = true end end } ]===] local _G = _G function private.GetUserRulesOptions(addon, addonName) local date = _G.date local format = _G.format local GetBuildInfo = _G.GetBuildInfo local GetRealmName = _G.GetRealmName local GetUnitName = _G.GetUnitName local next = _G.next local pairs = _G.pairs local time = _G.time local wipe = _G.wipe local GetAddOnMetadata = _G.GetAddOnMetadata local tostring = _G.tostring local type = _G.type local unpack = _G.unpack local L = addon.L local ADDON_VERSION = tostring(GetAddOnMetadata(addonName, "Version")) local PLAYER_NAME = GetUnitName("player", false).. '-'..GetRealmName() local PATCH_NUMBER = GetBuildInfo() --@debug@ ADDON_VERSION = 'dev' --@end-debug@ local handler = { current = next(addon.db.global.userRules) } function handler:Select(key) self.current = key end function handler:GetSelected() return self.current end function handler:HasNotSelection() return self.current == nil end function handler:Create() local key = #addon.db.global.userRules + 1 local rule = addon.db.global.userRules[key] rule.title = format(L['User rule #%d'], key) rule.code = SAMPLE_RULE rule.revision = 0 rule.created = self:GetHistoryPoint() self:Select(key) end function handler:Delete() addon.db.global.userRules[self.current] = nil self:Select(next(addon.db.global.userRules)) end function handler:Rule() return addon.db.global.userRules[self.current] end function handler:Get(property) local rule = self:Rule() if not rule then return end return rule[property] end function handler:Set(property, value) local rule = self:Rule() if not rule or rule[property] == value then return end if property ~= "enabled" then rule.revision = rule.revision + 1 rule.updated = self:GetHistoryPoint() end rule[property] = value if addon:CompileUserRules() then return addon:LibSpellbook_Spells_Changed('UserRuleChanged') end end function handler:GetHistoryPoint() return { PLAYER_NAME, time(), PATCH_NUMBER, ADDON_VERSION } end function handler:FormatHistoryPoint(property) local point = self:Get(property) if type(point) ~= "table" then return "???" end local name, timestamp, patch, addonVersion = unpack(point) return format(L["%s, %s, patch %s, v.%s"], name, date("%Y-%m-%d %H:%M", timestamp), patch, addonVersion) end local t = {} function handler:GetRuleList() wipe(t) for key, rule in pairs(addon.db.global.userRules) do local title = rule.title if rule.error then title = title..' |cffff0000('..L['error']..')|r' elseif not rule.enabled then title = title..' |cff7f7f7f('..L['disabled']..')|r' elseif not addon.isClass(rule.scope) then title = title..' |cff7f7f7f('..L['inactive']..')|r' end t[key] = title end return t end function handler:HasNoRules() return not next(addon.db.global.userRules) end return { name = L['User Rules'], desc = L['Allow to add user-defined rules using Lua snippets.'], type = 'group', order = 30, handler = handler, args = { selectedRule = { name = L['Selected rule'], type = 'select', order = 10, get = 'GetSelected', set = function(_, key) return handler:Select(key) end, values = 'GetRuleList', hidden = 'HasNoRules', }, newRule = { name = L['New rule'], type = 'execute', order = 20, func = 'Create', }, rule = { name = L['Edit rule'], type = 'group', inline = true, order = 30, hidden = 'HasNotSelection', get = function(info) return handler:Get(info[#info]) end, set = function(info, ...) return handler:Set(info[#info], ...) end, args = { title = { name = L['Title'], desc = L['The rule title, to be used in spell panel.'], type = 'input', width = 'full', order = 10, }, created = { name = function() return format(L["Created by %s"], handler:FormatHistoryPoint('created')) end, type = 'description', order = 11, fontSize = 'medium', hidden = function() return type(handler:Get('created')) ~= 'table' end, }, updated = { name = function() return format( L["Updated by %s, revision #%d"], handler:FormatHistoryPoint('updated'), handler:Get('revision') ) end, type = 'description', order = 12, fontSize = 'medium', hidden = function() return type(handler:Get('updated')) ~= 'table' end, }, enabled = { name = L['Enabled'], desc = L['Uncheck to disable this rule globally.'], type = 'toggle', order = 20, }, scope = { name = L['Class restriction'], desc = L['For which class should this rule be active ?'], type = 'select', order = 25, values = { ALL = L['None'], DEATHKNIGHT = L['DEATHKNIGHT'], DEMONHUNTER = L['DEMONHUNTER'], DRUID = L['DRUID'], HUNTER = L['HUNTER'], MAGE = L['MAGE'], MONK = L['MONK'], PALADIN = L['PALADIN'], PRIEST = L['PRIEST'], ROGUE = L['ROGUE'], SHAMAN = L['SHAMAN'], WARLOCK = L['WARLOCK'], WARRIOR = L['WARRIOR'], }, }, delete = { name = L['Delete'], type = 'execute', confirm = true, confirmText = L['Permanently delete this rule ?'], order = 26, func = 'Delete', }, _validation = { name = function() local msg = handler:Get('error') return msg and ('|cffff0000Error '..msg:gsub('^[^:]+:(%d+:)', 'line %1')..'|r') or 'OK' end, type = 'description', hidden = function() return not handler:Get('error') end, width = 'full', order = 29, fontSize = 'large', }, code = { name = L['Code'], desc = L['The code snippet defining the rule.'], type = 'input', width = 'full', multiline = 15, order = 30, }, }, }, }, } end
gpl-3.0
AresTao/darkstar
scripts/zones/Port_Bastok/npcs/Rosswald.lua
36
1683
----------------------------------- -- Area: Port Bastok -- NPC: Rosswald -- Only sells when Bastok controlls Zulkheim Region -- Confirmed shop stock, August 2013 ----------------------------------- require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(ZULKHEIM); if (RegionOwner ~= BASTOK) then player:showText(npc,ROSSWALD_CLOSED_DIALOG); else player:showText(npc,ROSSWALD_OPEN_DIALOG); stock = { 0x1114, 44, --Giant Sheep Meat 0x026E, 44, --Dried Marjoram 0x0262, 55, --San d'Orian Flour 0x0263, 36, --Rye Flour 0x0730, 1840, --Semolina 0x110E, 22, --La Theine Cabbage 0x111A, 55 --Selbina Milk } showShop(player,BASTOK,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
AresTao/darkstar
scripts/zones/Southern_San_dOria/npcs/Maugie.lua
13
2496
----------------------------------- -- Area: Southern San d'Oria -- NPC: Maugie -- General Info NPC ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ------------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) ==QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1 and player:getVar("tradeMaugie") == 0) then player:messageSpecial(8709); player:setVar("FFR",player:getVar("FFR") - 1); player:setVar("tradeMaugie",1); player:messageSpecial(FLYER_ACCEPTED); trade:complete(); elseif (player:getVar("tradeMaugie") ==1) then player:messageSpecial(8710); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local grimySignpost = player:getQuestStatus(SANDORIA,GRIMY_SIGNPOSTS); if (grimySignpost == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 2) then player:startEvent(0x002d); elseif (grimySignpost == QUEST_ACCEPTED) then if (player:getVar("CleanSignPost") == 15) then player:startEvent(0x002c); else player:startEvent(0x002b); end elseif (grimySignpost == QUEST_COMPLETED) then player:startEvent(0x002a); else player:startEvent(0x002e); -- default text 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 == 0x002d and option == 0) then player:addQuest(SANDORIA,GRIMY_SIGNPOSTS); elseif (csid == 0x002c) then player:setVar("CleanSignPost",0); player:addFame(SANDORIA,SAN_FAME*30); player:addGil(GIL_RATE*1500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500); player:completeQuest(SANDORIA,GRIMY_SIGNPOSTS); end end;
gpl-3.0
mohammadmtf/TeleSeed
plugins/stats.lua
866
4001
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(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("chat#id"..chat_id,"./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() == 'teleseed' 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' then 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(chat_id) else return end end if matches[2] == "teleseed" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(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) (teleseed)",-- Put everything you like :) "^[!/]([Tt]eleseed)"-- Put everything you like :) }, run = run } end
gpl-2.0
ArduPilot/ardupilot
libraries/AP_Scripting/examples/LED_roll.lua
26
2127
--[[ Script to control LED strips based on the roll of the aircraft. This is an example to demonstrate the LED interface for WS2812 LEDs --]] --[[ for this demo we will use a single strip with 30 LEDs --]] local num_leds = 30 --[[ use SERVOn_FUNCTION 94 for LED. We can control up to 16 separate strips of LEDs by putting them on different channels --]] local chan = SRV_Channels:find_channel(94) if not chan then gcs:send_text(6, "LEDs: channel not set") return end -- find_channel returns 0 to 15, convert to 1 to 16 chan = chan + 1 gcs:send_text(6, "LEDs: chan=" .. tostring(chan)) -- initialisation code --serialLED:set_num_neopixel(chan, num_leds) serialLED:set_num_profiled(chan, num_leds) -- constrain a value between limits function constrain(v, vmin, vmax) if v < vmin then v = vmin end if v > vmax then v = vmax end return v end --[[ Table of colors on a rainbow, red first --]] local rainbow = { { 255, 0, 0 }, { 255, 127, 0 }, { 255, 255, 0 }, { 0, 255, 0 }, { 0, 0, 255 }, { 75, 0, 130 }, { 143, 0, 255 }, } --[[ Function to set a LED to a color on a classic rainbow spectrum, with v=0 giving red --]] function set_Rainbow(chan, led, v) local num_rows = #rainbow local row = math.floor(constrain(v * (num_rows-1)+1, 1, num_rows-1)) local v0 = (row-1) / (num_rows-1) local v1 = row / (num_rows-1) local p = (v - v0) / (v1 - v0) r = math.floor(rainbow[row][1] + p * (rainbow[row+1][1] - rainbow[row][1])) g = math.floor(rainbow[row][2] + p * (rainbow[row+1][2] - rainbow[row][2])) b = math.floor(rainbow[row][3] + p * (rainbow[row+1][3] - rainbow[row][3])) serialLED:set_RGB(chan, led, r, g, b) end --[[ We will set the colour of the LEDs based on roll of the aircraft --]] function update_LEDs() local roll = constrain(ahrs:get_roll(), math.rad(-60), math.rad(60)) for led = 0, num_leds-1 do local v = constrain(0.5 + 0.5 * math.sin(roll * (led - num_leds/2) / (num_leds/2)), 0, 1) set_Rainbow(chan, led, v) end serialLED:send(chan) return update_LEDs, 20 -- run at 50Hz end return update_LEDs, 1000
gpl-3.0
DeinFreund/Zero-K
units/spiderriot.lua
1
3356
unitDef = { unitname = [[spiderriot]], name = [[Redback]], description = [[Riot Spider]], acceleration = 0.22, brakeRate = 0.66, buildCostMetal = 250, buildPic = [[spiderriot.png]], canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], collisionVolumeOffsets = [[0 5 0]], collisionVolumeScales = [[36 36 36]], collisionVolumeType = [[ellipsoid]], corpse = [[DEAD]], customParams = { aimposoffset = [[0 10 0]], }, explodeAs = [[BIG_UNITEX]], footprintX = 3, footprintZ = 3, iconType = [[spiderriot]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maxDamage = 900, maxSlope = 72, maxVelocity = 1.8, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[TKBOT3]], noChaseCategory = [[TERRAFORM FIXEDWING SUB]], objectName = [[spiderriot.s3o]], script = [[spiderriot.lua]], selfDestructAs = [[BIG_UNITEX]], sightDistance = 366, trackOffset = 0, trackStrength = 10, trackStretch = 1, trackType = [[ChickenTrackPointyShort]], trackWidth = 55, turnRate = 1700, weapons = { { def = [[PARTICLEBEAM]], badTargetCategory = [[FIXEDWING]], onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]], }, }, weaponDefs = { PARTICLEBEAM = { name = [[Auto Particle Beam]], beamDecay = 0.85, beamTime = 1/30, beamttl = 45, coreThickness = 0.5, craterBoost = 0, craterMult = 0, customParams = { light_color = [[0.9 0.22 0.22]], light_radius = 80, }, damage = { default = 60.01, subs = 3, }, explosionGenerator = [[custom:flash1red]], fireStarter = 100, impactOnly = true, impulseFactor = 0, interceptedByShieldType = 1, laserFlareSize = 7.5, minIntensity = 1, range = 300, reloadtime = 0.33, rgbColor = [[1 0 0]], soundStart = [[weapon/laser/mini_laser]], soundStartVolume = 6, thickness = 5, tolerance = 8192, turret = true, weaponType = [[BeamLaser]], }, }, featureDefs = { DEAD = { blocking = true, featureDead = [[HEAP]], footprintX = 3, footprintZ = 3, object = [[tarantula_dead.s3o]], }, HEAP = { blocking = false, footprintX = 3, footprintZ = 3, object = [[debris3x3a.s3o]], }, }, } return lowerkeys({ spiderriot = unitDef })
gpl-2.0
AresTao/darkstar
scripts/zones/Windurst_Walls/npcs/Juvillie.lua
38
1041
----------------------------------- -- Area: Windurst Walls -- NPC: Juvillie -- Type: Event Replayer -- @zone: 239 -- @pos -180.731 -3.451 143.138 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0196); 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
sipefree/guildpanel
Libs/AceConfig-3.0/AceConfig-3.0.lua
1
1578
--- AceConfig-3.0 wrapper library. -- Provides an API to register an options table with the config registry, -- as well as associate it with a slash command. -- @class file -- @name AceConfig-3.0 -- @release $Id: AceConfig-3.0.lua 710 2008-12-19 10:14:39Z nevcairiel $ --[[ AceConfig-3.0 Very light wrapper library that combines all the AceConfig subcomponents into one more easily used whole. Also automatically adds "config", "enable" and "disable" commands to options table as appropriate. ]] local MAJOR, MINOR = "AceConfig-3.0", 2 local lib = LibStub:NewLibrary(MAJOR, MINOR) if not lib then return end local cfgreg = LibStub("AceConfigRegistry-3.0") local cfgcmd = LibStub("AceConfigCmd-3.0") local cfgdlg = LibStub("AceConfigDialog-3.0") --TODO: local cfgdrp = LibStub("AceConfigDropdown-3.0") --------------------------------------------------------------------- -- :RegisterOptionsTable(appName, options, slashcmd, persist) -- -- - appName - (string) application name -- - options - table or function ref, see AceConfigRegistry -- - slashcmd - slash command (string) or table with commands, or nil to NOT create a slash command function lib:RegisterOptionsTable(appName, options, slashcmd) local ok,msg = pcall(cfgreg.RegisterOptionsTable, self, appName, options) if not ok then error(msg, 2) end if slashcmd then if type(slashcmd) == "table" then for _,cmd in pairs(slashcmd) do cfgcmd:CreateChatCommand(cmd, appName) end else cfgcmd:CreateChatCommand(slashcmd, appName) end end end
gpl-3.0
NeoRaider/luci
modules/luci-mod-admin-mini/luasrc/controller/mini/index.lua
74
1261
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.mini.index", package.seeall) function index() local root = node() if not root.lock then root.target = alias("mini") root.index = true end entry({"about"}, template("about")) local page = entry({"mini"}, alias("mini", "index"), _("Essentials"), 10) page.sysauth = "root" page.sysauth_authenticator = "htmlauth" page.index = true entry({"mini", "index"}, alias("mini", "index", "index"), _("Overview"), 10).index = true entry({"mini", "index", "index"}, form("mini/index"), _("General"), 1).ignoreindex = true entry({"mini", "index", "luci"}, cbi("mini/luci", {autoapply=true}), _("Settings"), 10) entry({"mini", "index", "logout"}, call("action_logout"), _("Logout")) end function action_logout() local dsp = require "luci.dispatcher" local utl = require "luci.util" if dsp.context.authsession then utl.ubus("session", "destroy", { ubus_rpc_session = dsp.context.authsession }) dsp.context.urltoken.stok = nil end luci.http.header("Set-Cookie", "sysauth=; path=" .. dsp.build_url()) luci.http.redirect(luci.dispatcher.build_url()) end
apache-2.0
NeoRaider/luci
modules/luci-mod-admin-mini/luasrc/model/cbi/mini/system.lua
78
2244
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. require("luci.sys") require("luci.sys.zoneinfo") require("luci.tools.webadmin") require("luci.util") m = Map("system", translate("System"), translate("Here you can configure the basic aspects of your device like its hostname or the timezone.")) s = m:section(TypedSection, "system", "") s.anonymous = true s.addremove = false local sysinfo = luci.util.ubus("system", "info") or { } local boardinfo = luci.util.ubus("system", "board") or { } local uptime = sysinfo.uptime or 0 local loads = sysinfo.load or { 0, 0, 0 } local memory = sysinfo.memory or { total = 0, free = 0, buffered = 0, shared = 0 } s:option(DummyValue, "_system", translate("Model")).value = boardinfo.model or "?" s:option(DummyValue, "_cpu", translate("System")).value = boardinfo.system or "?" s:option(DummyValue, "_la", translate("Load")).value = string.format("%.2f, %.2f, %.2f", loads[1] / 65535.0, loads[2] / 65535.0, loads[3] / 65535.0) s:option(DummyValue, "_memtotal", translate("Memory")).value = string.format("%.2f MB (%.0f%% %s, %.0f%% %s)", tonumber(memory.total) / 1024 / 1024, 100 * memory.buffered / memory.total, tostring(translate("buffered")), 100 * memory.free / memory.total, tostring(translate("free")) ) s:option(DummyValue, "_systime", translate("Local Time")).value = os.date("%c") s:option(DummyValue, "_uptime", translate("Uptime")).value = luci.tools.webadmin.date_format(tonumber(uptime)) hn = s:option(Value, "hostname", translate("Hostname")) function hn.write(self, section, value) Value.write(self, section, value) luci.sys.hostname(value) end tz = s:option(ListValue, "zonename", translate("Timezone")) tz:value("UTC") for i, zone in ipairs(luci.sys.zoneinfo.TZ) do tz:value(zone[1]) end function tz.write(self, section, value) local function lookup_zone(title) for _, zone in ipairs(luci.sys.zoneinfo.TZ) do if zone[1] == title then return zone[2] end end end AbstractValue.write(self, section, value) self.map.uci:set("system", section, "timezone", lookup_zone(value) or "GMT0") end return m
apache-2.0
AresTao/darkstar
scripts/globals/spells/bluemagic/regurgitation.lua
18
2057
----------------------------------------- -- Spell: Regurgitation -- Deals Water damage to an enemy. Additional Effect: Bind -- Spell cost: 69 MP -- Monster Type: Lizards -- Spell Type: Magical (Water) -- Blue Magic Points: 1 -- Stat Bonus: INT+1 MND+1 MP+3 -- Level: 68 -- Casting Time: 5 seconds -- Recast Time: 24 seconds -- Magic Bursts on: Reverberation, Distortion, and Darkness -- Combos: Resist Gravity ----------------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/bluemagic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local params = {}; params.multiplier = 1.83; params.tMultiplier = 2.0; params.duppercap = 69; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.30; params.chr_wsc = 0.0; damage = BlueMagicalSpell(caster, target, spell, params, INT_BASED); if (caster:isBehind(target, 15)) then -- guesstimating the angle at 15 degrees here damage = math.floor(damage * 1.25); -- printf("is behind mob") end; damage = BlueFinalAdjustments(caster, target, spell, damage, params); --TODO: Knockback? Where does that get handled? How much knockback does it have? local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT) - target:getStat(MOD_INT),BLUE_SKILL,1.0); if (damage > 0 and resist > 0.125) then local typeEffect = EFFECT_BIND; target:delStatusEffect(typeEffect); target:addStatusEffect(typeEffect,1,0,getBlueEffectDuration(caster,resist,typeEffect)); end return damage; end;
gpl-3.0
AresTao/darkstar
scripts/globals/spells/hyoton_ni.lua
17
1247
----------------------------------------- -- Spell: Hyoton: Ni -- Deals ice damage to an enemy and lowers its resistance against fire. ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --doNinjutsuNuke(V,M,caster,spell,target,hasMultipleTargetReduction,resistBonus) local duration = 15 + caster:getMerit(MERIT_HYOTON_EFFECT) -- T1 bonus debuff duration local bonusAcc = 0; local bonusMab = caster:getMerit(MERIT_HYOTON_EFFECT) + caster:getMod(MOD_NIN_NUKE_BONUS); -- T1 mag atk + "enhances Ninjustu damage" mod if (caster:isBehind(target,15) and caster:hasStatusEffect(EFFECT_INNIN)) then -- Innin mag atk bonus from behind, guesstimating angle at 15 degrees bonusMab = bonusMab + caster:getStatusEffect(EFFECT_INNIN):getPower(); end local dmg = doNinjutsuNuke(68,1,caster,spell,target,false,bonusAcc,bonusMab); handleNinjutsuDebuff(caster,target,spell,30,duration,MOD_FIRERES); return dmg; end;
gpl-3.0
tysonliddell/OpenRA
mods/d2k/maps/ordos-02b/ordos02b-AI.lua
8
1137
--[[ Copyright 2007-2020 The OpenRA Developers (see AUTHORS) This file is part of OpenRA, which is free software. It is made available to you 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. For more information, see COPYING. ]] AttackGroupSize = { easy = 6, normal = 8, hard = 10 } AttackDelays = { easy = { DateTime.Seconds(4), DateTime.Seconds(9) }, normal = { DateTime.Seconds(2), DateTime.Seconds(7) }, hard = { DateTime.Seconds(1), DateTime.Seconds(5) } } HarkonnenInfantryTypes = { "light_inf" } ActivateAI = function() IdlingUnits[harkonnen] = { } local delay = function() return Utils.RandomInteger(AttackDelays[Difficulty][1], AttackDelays[Difficulty][2] + 1) end local toBuild = function() return HarkonnenInfantryTypes end local attackThresholdSize = AttackGroupSize[Difficulty] * 2.5 DefendAndRepairBase(harkonnen, HarkonnenBase, 0.75, AttackGroupSize[Difficulty]) ProduceUnits(harkonnen, HBarracks, delay, toBuild, AttackGroupSize[Difficulty], attackThresholdSize) end
gpl-3.0
AresTao/darkstar
scripts/zones/Cloister_of_Gales/bcnms/trial_by_wind.lua
19
1769
----------------------------------- -- Area: Cloister of Gales -- BCNM: Trial by Wind -- @zone -361 1 -381 201 ----------------------------------- package.loaded["scripts/zones/Cloister_of_Gales/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Cloister_of_Gales/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompleteQuest(OUTLANDS,TRIAL_BY_WIND)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then player:delKeyItem(TUNING_FORK_OF_WIND); player:addKeyItem(WHISPER_OF_GALES); player:messageSpecial(KEYITEM_OBTAINED,WHISPER_OF_GALES); end end;
gpl-3.0
wizardbottttt/X
plugins/minecraft.lua
624
2605
local usage = { "!mine [ip]: Searches Minecraft server on specified ip and sends info. Default port: 25565", "!mine [ip] [port]: Searches Minecraft server on specified ip and port and sends info.", } local ltn12 = require "ltn12" local function mineSearch(ip, port, receiver) --25565 local responseText = "" local api = "https://api.syfaro.net/server/status" local parameters = "?ip="..(URL.escape(ip) or "").."&port="..(URL.escape(port) or "").."&players=true&favicon=true" local http = require("socket.http") local respbody = {} local body, code, headers, status = http.request{ url = api..parameters, method = "GET", redirect = true, sink = ltn12.sink.table(respbody) } local body = table.concat(respbody) if (status == nil) then return "ERROR: status = nil" end if code ~=200 then return "ERROR: "..code..". Status: "..status end local jsonData = json:decode(body) responseText = responseText..ip..":"..port.." ->\n" if (jsonData.motd ~= nil) then local tempMotd = "" tempMotd = jsonData.motd:gsub('%§.', '') if (jsonData.motd ~= nil) then responseText = responseText.." Motd: "..tempMotd.."\n" end end if (jsonData.online ~= nil) then responseText = responseText.." Online: "..tostring(jsonData.online).."\n" end if (jsonData.players ~= nil) then if (jsonData.players.max ~= nil) then responseText = responseText.." Max Players: "..jsonData.players.max.."\n" end if (jsonData.players.now ~= nil) then responseText = responseText.." Players online: "..jsonData.players.now.."\n" end if (jsonData.players.sample ~= nil and jsonData.players.sample ~= false) then responseText = responseText.." Players: "..table.concat(jsonData.players.sample, ", ").."\n" end end if (jsonData.favicon ~= nil and false) then --send_photo(receiver, jsonData.favicon) --(decode base64 and send) end return responseText end local function parseText(chat, text) if (text == nil or text == "!mine") then return usage end ip, port = string.match(text, "^!mine (.-) (.*)$") if (ip ~= nil and port ~= nil) then return mineSearch(ip, port, chat) end local ip = string.match(text, "^!mine (.*)$") if (ip ~= nil) then return mineSearch(ip, "25565", chat) end return "ERROR: no input ip?" end local function run(msg, matches) local chat_id = tostring(msg.to.id) local result = parseText(chat_id, msg.text) return result end return { description = "Searches Minecraft server and sends info", usage = usage, patterns = { "^!mine (.*)$" }, run = run }
gpl-2.0
Blu3wolf/HARDmod
prototypes/module.lua
1
2416
--[[Speed Modules]]-- data.raw["recipe"]["speed-module"].ingredients = {{"processing-unit", 2},{"module-case-mk1", 1}} data.raw["recipe"]["speed-module"].energy_required = 10 data.raw["module"]["speed-module"].subgroup = "speed-module" data.raw["recipe"]["speed-module-2"].ingredients = {{"motherboard", 1},{"heatsink", 1},{"processing-unit", 4},{"module-case-mk2", 1}} data.raw["recipe"]["speed-module-2"].energy_required = 20 data.raw["module"]["speed-module-2"].subgroup = "speed-module" data.raw["recipe"]["speed-module-3"].ingredients = {{"motherboard", 2},{"heatsink", 2},{"processing-unit", 6},{"module-case-mk3", 1}} data.raw["recipe"]["speed-module-3"].energy_required = 30 data.raw["module"]["speed-module-3"].subgroup = "speed-module" --[[Effectivity Modules]]-- data.raw["recipe"]["effectivity-module"].ingredients = {{"processing-unit", 2},{"module-case-mk1", 1}} data.raw["recipe"]["effectivity-module"].energy_required = 10 data.raw["module"]["effectivity-module"].subgroup = "effectivity-module" data.raw["recipe"]["effectivity-module-2"].ingredients = {{"motherboard", 1},{"heatsink", 1},{"processing-unit", 4},{"module-case-mk2", 1}} data.raw["recipe"]["effectivity-module-2"].energy_required = 20 data.raw["module"]["effectivity-module-2"].subgroup = "effectivity-module" data.raw["recipe"]["effectivity-module-3"].ingredients = {{"motherboard", 2},{"heatsink", 2},{"processing-unit", 6},{"module-case-mk3", 1}} data.raw["recipe"]["effectivity-module-3"].energy_required = 30 data.raw["module"]["effectivity-module-3"].subgroup = "effectivity-module" --[[Productivity Modules]]-- data.raw["recipe"]["productivity-module"].ingredients = {{"processing-unit", 2},{"module-case-mk1", 1}} data.raw["recipe"]["productivity-module"].energy_required = 10 data.raw["module"]["productivity-module"].subgroup = "productivity-module" data.raw["recipe"]["productivity-module-2"].ingredients = {{"motherboard", 1},{"heatsink", 1},{"processing-unit", 4},{"module-case-mk2", 1}} data.raw["recipe"]["productivity-module-2"].energy_required = 20 data.raw["module"]["productivity-module-2"].subgroup = "productivity-module" data.raw["recipe"]["productivity-module-3"].ingredients = {{"motherboard", 2},{"heatsink", 2},{"processing-unit", 6},{"module-case-mk3", 1}} data.raw["recipe"]["productivity-module-3"].energy_required = 30 data.raw["module"]["productivity-module-3"].subgroup = "productivity-module"
gpl-2.0
kidaa/luvit
tests/test-tls-connect-simple.lua
11
1050
require('tap')(function (test) local fixture = require('./fixture-tls') local tls = require('tls') local options = { cert = fixture.certPem, key = fixture.keyPem } local serverConnected = 0 local clientConnected = 0 local server local client1 test("tls connect simple test", function() server = tls.createServer(options, function(conn) serverConnected = serverConnected + 1 p('server accepted',serverConnected) if (serverConnected == 1) then server:close() p('server closed') conn:destroy() end end) server:listen(fixture.commonPort, function() p('server listening') client1 = tls.connect({port = fixture.commonPort, host = '127.0.0.1'}) client1:on('connect', function() p('client connected') clientConnected = clientConnected + 1 end) client1:on('error', function(err) p(err) client1:destroy() end) client1:on('end', function() p('client end') end) end) end) end)
apache-2.0
AresTao/darkstar
scripts/globals/settings.lua
13
12083
----------------------------------------------- ------------- GLOBAL SETTINGS ------------- ----------------------------------------------- -- This is to allow server operators to further customize their servers. As more features are added to pXI, the list will surely expand. -- Anything scripted can be customized with proper script editing. -- PLEASE REQUIRE THIS SCRIPT IN ANY SCRIPTS YOU DO: ADD THIS LINE TO THE TOP!!!! -- require("scripts/globals/settings"); -- With this script added to yours, you can pull variables from it!! -- Always include status.lua, which defines mods -- require("scripts/globals/status"); -- Common functions require("scripts/globals/common"); -- Enable Extension (1= yes 0= no) ENABLE_COP = 0; ENABLE_TOAU = 0; ENABLE_WOTG = 0; ENABLE_ACP = 0; ENABLE_AMK = 0; ENABLE_ASA = 0; ENABLE_ABYSSEA = 0; ENABLE_SOA = 0; -- Setting to lock content more accurately to the expansions you have defined above -- This generally results in a more accurate presentation of your selected expansions -- as well as a less confusing player experience for things that are disabled (things that are disabled are not loaded) -- This feature correlates to the required_expansion column in the SQL files RESTRICT_BY_EXPANSION = 0; -- CHARACTER CONFIG INITIAL_LEVEL_CAP = 50; -- The initial level cap for new players. There seems to be a hardcap of 255. MAX_LEVEL = 75; -- Level max of the server, lowers the attainable cap by disabling Limit Break quests. NORMAL_MOB_MAX_LEVEL_RANGE_MIN = 81; -- Lower Bound of Max Level Range for Normal Mobs (0 = Uncapped) NORMAL_MOB_MAX_LEVEL_RANGE_MAX = 84; -- Upper Bound of Max Level Range for Normal Mobs (0 = Uncapped) START_GIL = 10; --Amount of gil given to newly created characters. START_INVENTORY = 30; -- Starting inventory and satchel size. Ignores values < 30. Do not set above 80! OPENING_CUTSCENE_ENABLE = 0; --Set to 1 to enable opening cutscenes, 0 to disable. SUBJOB_QUEST_LEVEL = 18; -- Minimum level to accept either subjob quest. Set to 0 to start the game with subjobs unlocked. ADVANCED_JOB_LEVEL = 30; -- Minimum level to accept advanced job quests. Set to 0 to start the game with advanced jobs. ALL_MAPS = 0; -- Set to 1 to give starting characters all the maps. UNLOCK_OUTPOST_WARPS = 0; -- Set to 1 to give starting characters all outpost warps. 2 to add Tu'Lia and Tavnazia. SHOP_PRICE = 1.000; -- Multiplies prices in NPC shops. GIL_RATE = 1.000; -- Multiplies gil earned from quests. Won't always display in game. EXP_RATE = 1.000; -- Multiplies exp earned from fov. TABS_RATE = 1.000; -- Multiplies tabs earned from fov. SAN_FAME = 1.000; -- Multiplies fame earned from San d'Oria quests. BAS_FAME = 1.000; -- Multiplies fame earned from Bastok quests. WIN_FAME = 1.000; -- Multiplies fame earned from Windurst quests. NORG_FAME = 1.000; -- Multiplies fame earned from Norg and Tenshodo quests. JEUNO_FAME = 1.000; -- Multiplies fame earned from Jeuno quests. CURE_POWER = 1.000; -- Multiplies amount healed from Healing Magic, including the relevant Blue Magic. SPELL_POWER = 1.000; -- Multiplies damage dealt by Elemental and Divine Magic. BLUE_POWER = 1.000; -- Multiplies damage dealt by most Blue Magic. DRAIN_POWER = 1.000; -- Multiplies amount drained by Drain, Aspir, and relevant Blue Magic spells. ITEM_POWER = 1.000; -- Multiplies the effect of items such as Potions and Ethers. WEAPON_SKILL_POWER = 1.000; -- Multiplies damage dealt by Weapon Skills. WEAPON_SKILL_POINTS = 1.000; -- Multiplies points earned during weapon unlocking. USE_ADOULIN_WEAPON_SKILL_CHANGES = false; -- true/false. Change to toggle new Adoulin weapon skill damage calculations HARVESTING_BREAK_CHANCE = 0.33; -- % chance for the sickle to break during harvesting. Set between 0 and 1. EXCAVATION_BREAK_CHANCE = 0.33; -- % chance for the pickaxe to break during excavation. Set between 0 and 1. LOGGING_BREAK_CHANCE = 0.33; -- % chance for the hatchet to break during logging. Set between 0 and 1. MINING_BREAK_CHANCE = 0.33; -- % chance for the pickaxe to break during mining. Set between 0 and 1. HARVESTING_RATE = 0.50; -- % chance to recieve an item from haresting. Set between 0 and 1. EXCAVATION_RATE = 0.50; -- % chance to recieve an item from excavation. Set between 0 and 1. LOGGING_RATE = 0.50; -- % chance to recieve an item from logging. Set between 0 and 1. MINING_RATE = 0.50; -- % chance to recieve an item from mining. Set between 0 and 1. -- SE implemented coffer/chest illusion time in order to prevent coffer farming. No-one in the same area can open a chest or coffer for loot (gil, gems & items) -- till a random time between MIN_ILLSION_TIME and MAX_ILLUSION_TIME. During this time players can loot keyitem and item related to quests (AF, maps... etc.) COFFER_MAX_ILLUSION_TIME = 3600; -- 1 hour COFFER_MIN_ILLUSION_TIME = 1800; -- 30 minutes CHEST_MAX_ILLUSION_TIME = 3600; -- 1 hour CHEST_MIN_ILLUSION_TIME = 1800; -- 30 minutes -- Sets spawn type for: Behemoth, Fafnir, Adamantoise, King Behemoth, Nidhog, Aspidochelone. -- Use 0 for timed spawns, 1 for force pop only, 2 for both LandKingSystem_NQ = 2; LandKingSystem_HQ = 2; -- DYNAMIS SETTINGS BETWEEN_2DYNA_WAIT_TIME = 1; -- wait time between 2 Dynamis (in real day) min: 1 day DYNA_LEVEL_MIN = 65; -- level min for entering in Dynamis TIMELESS_HOURGLASS_COST = 500000; -- cost of the timeless hourglass for Dynamis. CURRENCY_EXCHANGE_RATE = 100; -- X Tier 1 ancient currency -> 1 Tier 2, and so on. Certain values may conflict with shop items. Not designed to exceed 198. RELIC_2ND_UPGRADE_WAIT_TIME = 604800; -- wait time for 2nd relic upgrade (stage 2 -> stage 3) in seconds. 604800s = 1 RL week. RELIC_3RD_UPGRADE_WAIT_TIME = 295200; -- wait time for 3rd relic upgrade (stage 3 -> stage 4) in seconds. 295200s = 82 hours. FREE_COP_DYNAMIS = 1 ; -- Authorize player to entering inside COP Dynamis without completing COP mission ( 1 = enable 0= disable) -- QUEST/MISSION SPECIFIC SETTINGS WSNM_LEVEL = 70; -- Min Level to get WSNM Quests WSNM_SKILL_LEVEL = 240; AF1_QUEST_LEVEL = 40; -- Minimum level to start AF1 quest AF2_QUEST_LEVEL = 50; -- Minimum level to start AF2 quest AF3_QUEST_LEVEL = 50; -- Minimum level to start AF3 quest AF1_FAME = 20; -- base fame for completing an AF1 quest AF2_FAME = 40; -- base fame for completing an AF2 quest AF3_FAME = 60; -- base fame for completing an AF3 quest DEBUG_MODE = 0; -- Set to 1 to activate auto-warping to the next location (only supported by certain missions / quests). QM_RESET_TIME = 300; -- Default time (in seconds) you have from killing ???-pop mission NMs to click again and get key item, until ??? resets. OldSchoolG1 = false; -- Set to true to require farming Exoray Mold, Bombd Coal, and Ancient Papyrus drops instead of allowing key item method. OldSchoolG2 = false; -- Set true to require the NMs for "Atop the Highest Mountains" be dead to get KI like before SE changed it. FrigiciteDuration = 30; -- When OldSChoolG2 is enabled, this is the time (in seconds) you have from killing Boreal NMs to click the "???" target. -- FIELDS OF VALOR/Grounds of Valor SETTINGS REGIME_WAIT = 1; --Make people wait till 00:00 game time as in retail. If it's 0, there is no wait time. FIELD_MANUALS = 1; -- Enables Fields of Valor manuals LOW_LEVEL_REGIME = 0; --Allow people to kill regime targets even if they give no exp, allowing people to farm regime targets at 75 in low level areas. GROUNDS_TOMES = 1; -- Enables Grounds of Valor tomes -- JOB ABILITY/TRAIT SPECIFIC SETTINGS CIRCLE_KILLER_EFFECT = 20; -- Intimidation percentage granted by circle effects. (made up number) KILLER_EFFECT = 10; -- Intimidation percentage from killer job traits. -- SPELL SPECIFIC SETTINGS DIA_OVERWRITE = 1; --Set to 1 to allow Bio to overwrite same tier Dia. Default is 1. BIO_OVERWRITE = 0; --Set to 1 to allow Dia to overwrite same tier Bio. Default is 0. BARELEMENT_OVERWRITE = 1; --Set to 1 to allow Barelement spells to overwrite each other (prevent stacking). Default is 1. BARSTATUS_OVERWRITE = 1; --Set to 1 to allow Barstatus spells to overwrite each other (prevent stacking). Default is 1. STONESKIN_CAP = 350; -- soft cap for hp absorbed by stoneskin BLINK_SHADOWS = 2; -- number of shadows supplied by Blink spell ENSPELL_DURATION = 180; -- duration of RDM en-spells SPIKE_EFFECT_DURATION = 180; -- the duration of RDM, BLM spikes effects (not Reprisal) ELEMENTAL_DEBUFF_DURATION = 120; -- base duration of elemental debuffs AQUAVEIL_INTERR_RATE = 25; -- percent spell interruption rate reduction from Aquaveil (see http://www.bluegartrls.com/forum/82143-spell-interruption-down-cap-aquaveil-tests.html) ABSORB_SPELL_AMOUNT = 8; -- how much of a stat gets absorbed by DRK absorb spells - expected to be a multiple of 8. ABSORB_SPELL_TICK = 9; -- duration of 1 absorb spell tick SNEAK_INVIS_DURATION_MULTIPLIER = 1; -- multiplies duration of sneak,invis,deodorize to reduce player torture. 1 = retail behavior. USE_OLD_CURE_FORMULA = false; -- true/false. if true, uses older cure formula (3*MND + VIT + 3*(healing skill/5)) // cure 6 will use the newer formula -- CELEBRATIONS EXPLORER_MOOGLE = 1; -- Enables Explorer Moogle teleports EXPLORER_MOOGLE_LEVELCAP = 10; JINX_MODE_2005 = 0; -- Set to 1 to give starting characters swimsuits from 2005. Ex: Hume Top JINX_MODE_2008 = 0; -- Set to 1 to give starting characters swimsuits from 2008. Ex: Custom Top JINX_MODE_2012 = 0; -- Set to 1 to give starting characters swimsuits from 2012. Ex: Marine Top SUMMERFEST_2004 = 0; -- Set to 1 to give starting characters Far East dress from 2004. Ex: Onoko Yukata SUNBREEZE_2009 = 0; -- Set to 1 to give starting characters Far East dress from 2009. Ex: Otokogusa Yukata SUNBREEZE_2011 = 0; -- Set to 1 to give starting characters Far East dress from 2011. Ex: Hikogami Yukata CHRISTMAS = 0; -- Set to 1 to give starting characters Christmas dress. HALLOWEEN = 0; -- Set to 1 to give starting characters Halloween items (Does not start event). HALLOWEEN_2005 = 0; -- Set to 1 to Enable the 2005 version of Harvest Festival, will start on Oct. 20 and end Nov. 1. HALLOWEEN_YEAR_ROUND = 0; -- Set to 1 to have Harvest Festival initialize outside of normal times. -- MISC HOMEPOINT_HEAL = 0; --Set to 1 if you want Home Points to heal you like in single-player Final Fantasy games. RIVERNE_PORTERS = 120; -- Time in seconds that Unstable Displacements in Cape Riverne stay open after trading a scale. LANTERNS_STAY_LIT = 1200; -- time in seconds that lanterns in the Den of Rancor stay lit. ENABLE_COP_ZONE_CAP=1; -- enable or disable lvl cap TIMEZONE_OFFSET = 9.0; -- Offset from UTC used to determine when "JP Midnight" is for the server. Default is JST (+9.0). ALLOW_MULTIPLE_EXP_RINGS = 0; -- Set to 1 to remove ownership restrictions on the Chariot/Empress/Emperor Band trio. BYPASS_EXP_RING_ONE_PER_WEEK = 0; -- -- Set to 1 to bypass the limit of one ring per Conquest Tally Week. NUMBER_OF_DM_EARRINGS = 1; -- Number of earrings players can simultaneously own from Divine Might before scripts start blocking them (Default: 1) HOMEPOINT_TELEPORT = 0; -- Enables the homepoint teleport system DIG_ABUNDANCE_BONUS = 0; -- Increase chance of digging up an item (450 = item digup chance +45) DIG_FATIGUE = 1; -- Set to 0 to disable Dig Fatigue MIASMA_FILTER_COOLDOWN = 5; -- Number of days a player can obtain a Miasma Filter KI for any of the Boneyard Gully ENMs (Minimum:1) -- LIMBUS BETWEEN_2COSMOCLEANSE_WAIT_TIME = 3; -- day between 2 limbus keyitem (default 3 days) DIMENSIONAL_PORTAL_UNLOCK = false; -- Set true to bypass requirements for using dimensional portals to reach sea for Limbus -- ABYSSEA VISITANT_BONUS = 1.00; -- Default: 1.00 - (retail) - Multiplies the base time value of each Traverser Stone.
gpl-3.0
AresTao/darkstar
scripts/zones/RuAun_Gardens/npcs/qm1.lua
16
1435
----------------------------------- -- Area: Ru'Aun Gardens -- NPC: ??? (Genbu's Spawn) -- Allows players to spawn the HNM Genbu with a Gem of the North and a Winterstone. -- @pos 257 -70 517 130 ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/zones/RuAun_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- Trade Gem of the North and Winterstone if (GetMobAction(17309980) == 0 and trade:hasItemQty(1424,1) and trade:hasItemQty(1425,1) and trade:getItemCount() == 2) then player:tradeComplete(); SpawnMob(17309980,300):updateClaim(player); -- Spawn Genbu player:showText(npc,SKY_GOD_OFFSET + 5); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(SKY_GOD_OFFSET); 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
brson/heka-rs
test/fxa_active_daily_users.lua
1
1541
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. require "circular_buffer" require "hyperloglog" require "math" local rows = 365 local sec_per_row = 60 * 60 * 24 active_day = 0 td = hyperloglog.new() -- total daily ad = hyperloglog.new() -- android daily tdcb = circular_buffer.new(rows, 1, sec_per_row) adcb = circular_buffer.new(rows, 1, sec_per_row) local USERS = 1 local NAME = "users" tdcb:set_header(USERS, NAME) adcb:set_header(USERS, NAME) local floor = math.floor function process_message () local ts = read_message("Timestamp") local day = floor(ts / (60 * 60 * 24 * 1e9)) if day < active_day then return 0 -- too old elseif day > active_day then active_day = day td:clear() ad:clear() end local uid = read_message("Fields[uid]") if type(uid) ~= "string" then return -1 end if td:add(uid) then tdcb:set(ts, USERS, td:count()) end local user_agent_os = read_message("Fields[user_agent_os]") if user_agent_os and user_agent_os == "Android" then if ad:add(uid) then adcb:set(ts, USERS, ad:count()) end end return 0 end function timer_event(ns) inject_payload("cbuf", "Estimated Active Daily Users", tdcb) inject_payload("cbuf", "Estimated Active Daily Android Users", adcb) end
mpl-2.0
AresTao/darkstar
scripts/zones/PsoXja/npcs/_09g.lua
17
1222
----------------------------------- -- Area: Pso'Xja -- NPC: Avatars Gate ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 1) then player:startEvent(0x0003); else player:messageSpecial(DOOR_LOCKED); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == 0x0003) then player:setVar("COP_Tenzen_s_Path",2); end end;
gpl-3.0
AresTao/darkstar
scripts/globals/items/fish_mithkabob.lua
35
1468
----------------------------------------- -- ID: 4398 -- Item: fish_mithkabob -- Food Effect: 30Min, All Races ----------------------------------------- -- Dexterity 1 -- Vitality 2 -- Mind -1 -- Defense % 25 -- Defense Cap 90 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4398); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 1); target:addMod(MOD_VIT, 2); target:addMod(MOD_MND, -1); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 90); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 1); target:delMod(MOD_VIT, 2); target:delMod(MOD_MND, -1); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 90); end;
gpl-3.0
DeinFreund/Zero-K
effects/lasers.lua
6
39354
-- gatorlaserflash -- flash1red2 -- flashlazer -- lasers_sparks1 -- lasers_melt1 -- flash1orange -- comlaserflash -- flash1purple -- lasers_melt3 -- flash1blue -- flash1green -- flash1red -- lasers_melt2 -- lasers_sparksr1 -- flash1yellow -- flash1white -- coregreen return { ["gatorlaserflash"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 1, flashalpha = 0.9, flashsize = 10.5, ttl = 3, color = { [1] = 1, [2] = 0, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT1]], pos = [[0, 0, 0]], }, }, sparkage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_SPARKS1]], pos = [[0, 0, 0]], }, }, }, ["flash1red2"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 1, flashalpha = 0.9, flashsize = 20, ttl = 3, color = { [1] = 1, [2] = 0, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT1]], pos = [[0, 0, 0]], }, }, sparkage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_SPARKSR1]], pos = [[0, 0, 0]], }, }, }, ["flashlazer"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = -0.02, flashalpha = 0.4, flashsize = 12, ttl = 120, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0,0,1]], dir = [[-1 r2,-1 r2,-1 r2]], length = 7.5, width = 15, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["lasers_sparks1"] = { sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 3, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["lasers_melt1"] = { groundflash = { circlealpha = 1, circlegrowth = -0.02, flashalpha = 0.6, flashsize = 3.5, ttl = 40, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, }, ["flash1orange"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 18, ttl = 3, color = { [1] = 1, [2] = 0.25, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[1,0.25,0]], dir = [[-1 r2,-1 r2,-1 r2]], length = 3, width = 5, lengthGrowth = 0.1, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 40, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["comlaserflash"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 0, flashalpha = 0.9, flashsize = 13, ttl = 3, color = { [1] = 1, [2] = 0, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT1]], pos = [[0, 0, 0]], }, }, pikage = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.2, color = [[1,0,0]], dir = [[-5 r10,-5 r10,-5 r10]], length = 6, width = 2, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 7.5, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 3, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1purple"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 18, ttl = 3, color = { [1] = 0.6, [2] = 0.2, [3] = 0.4, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0.6, 0.2, 0.41]], dir = [[-1 r2,-1 r2,-1 r2]], length = 5, width = 10, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 40, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["lasers_melt3"] = { groundflash = { circlealpha = 1, circlegrowth = -0.02, flashalpha = 0.6, flashsize = 6, ttl = 80, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, pikage = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.2, color = [[1,0,0]], dir = [[-5 r10,-5 r10,-5 r10]], length = 6, width = 2, }, }, }, ["flash1blue"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 20, ttl = 3, color = { [1] = 0, [2] = 0, [3] = 1, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0,0,1]], dir = [[-1 r2,-1 r2,-1 r2]], length = 5, width = 10, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1bluedark"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 20, ttl = 3, color = { [1] = 0, [2] = 0, [3] = 1, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0,0,1]], dir = [[-1 r2,-1 r2,-1 r2]], length = 5, width = 10, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 4, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1green"] = { usedefaultexplosions = false, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 0.75, alphadecay = 0.075, color = [[0,1,0]], dir = [[-1 r2,-1 r2,-1 r2]], length = 6, width = 10, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 20, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash2purple"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 15, ttl = 3, color = { [1] = 0.6, [2] = 0, [3] = 0.7, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0.4,0,0.5]], dir = [[-1 r2,-1 r2,-1 r2]], length = 5, width = 10, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 10, particlelife = 10, particlelifespread = 2, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash2purple_large"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 35, ttl = 4, color = { [1] = 0.6, [2] = 0, [3] = 0.7, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 3, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 8, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0.4,0,0.5]], dir = [[-1 r2,-1 r2,-1 r2]], length = 10, width = 20, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 10, particlelife = 15, particlelifespread = 5, particlesize = 2, particlesizespread = 4.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash2green_large"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 35, ttl = 4, color = { [1] = 0, [2] = 1, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 3, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 8, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0, 1, 0]], dir = [[-1 r2,-1 r2,-1 r2]], length = 10, width = 20, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 10, particlelife = 15, particlelifespread = 5, particlesize = 2, particlesizespread = 4.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1red"] = { usedefaultexplosions = false, groundflash = { circlealpha = 1, circlegrowth = 1, flashalpha = 0.9, flashsize = 20, ttl = 3, color = { [1] = 1, [2] = 0, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT1]], pos = [[0, 0, 0]], }, }, pikage = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.2, color = [[1,0,0]], dir = [[-5 r10,-5 r10,-5 r10]], length = 6, width = 2, }, }, sparkage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_SPARKS1]], pos = [[0, 0, 0]], }, }, }, ["lasers_melt2"] = { groundflash = { circlealpha = 1, circlegrowth = -0.02, flashalpha = 0.6, flashsize = 6, ttl = 80, color = { [1] = 1, [2] = 0.5, [3] = 0, }, }, }, ["lasers_sparksr1"] = { sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 5, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 3, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1yellow"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 18, ttl = 3, color = { [1] = 1, [2] = 1, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 15, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1white"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 18, ttl = 3, color = { [1] = 1, [2] = 1, [3] = 1, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 15, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["coregreen"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 30, ttl = 5, color = { [1] = 0, [2] = 1, [3] = 0, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, pikage = { air = true, class = [[explspike]], count = 15, ground = true, water = true, properties = { alpha = 0.8, alphadecay = 0.2, color = [[0,1,0]], dir = [[-7 r14,-7 r14,-7 r14]], length = 16, width = 6, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 80, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flash1teal"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 1, flashsize = 18, ttl = 3, color = { [1] = 0.2, [2] = 0.5, [3] = 1, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:LASERS_MELT2]], pos = [[0, 0, 0]], }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 15, particlelife = 15, particlelifespread = 0, particlesize = 1, particlesizespread = 2.5, particlespeed = 6, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["flashslow"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 0.5, flashsize = 25, ttl = 10, color = { [1] = 0.6, [2] = 0, [3] = 0.7, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:SLOW_MELT]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.05, color = [[0.4,0,0.5]], dir = [[-1 r2,-1 r2,-1 r2]], length = 4, width = 8, }, }, sparks = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1.0 0.2 1.0 0.01 0.9 0.3 0.9 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.1, 0]], numparticles = 5, particlelife = 7, particlelifespread = 3, particlesize = 6, particlesizespread = 2.5, particlespeed = 4, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, ["slow_melt"] = { groundflash = { circlealpha = 1, circlegrowth = -0.02, flashalpha = 0.4, flashsize = 6, ttl = 80, color = { [1] = 1, [2] = 0.0, [3] = 1, }, }, }, ["flashslowwithsparks"] = { usedefaultexplosions = false, groundflash = { circlealpha = 0, circlegrowth = 0, flashalpha = 0.5, flashsize = 25, ttl = 10, color = { [1] = 0.6, [2] = 0, [3] = 0.7, }, }, meltage = { air = true, class = [[CExpGenSpawner]], count = 1, ground = true, water = true, properties = { delay = 0, explosiongenerator = [[custom:SLOW_MELT]], pos = [[0, 0, 0]], }, }, pikes = { air = true, class = [[explspike]], count = 5, ground = true, water = true, properties = { alpha = 1, alphadecay = 0.04, color = [[0.4,0,0.5]], dir = [[-1 r2,-1 r2,-1 r2]], length = 4, width = 8, }, }, sparks_purple = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1.0 0.2 1.0 0.01 0.9 0.3 0.9 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.1, 0]], numparticles = 5, particlelife = 8, particlelifespread = 3, particlesize = 6, particlesizespread = 2.5, particlespeed = 4, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, sparks_yellow = { air = true, class = [[CSimpleParticleSystem]], count = 1, ground = true, water = true, properties = { airdrag = 0.97, colormap = [[1 1 1 0.01 1 0.7 0.2 0.01 0 0 0 0.01]], directional = true, emitrot = 0, emitrotspread = 80, emitvector = [[0, 1, 0]], gravity = [[0, -0.4, 0]], numparticles = 10, particlelife = 18, particlelifespread = 2, particlesize = 1, particlesizespread = 2.5, particlespeed = 3, particlespeedspread = 2, pos = [[0, 0, 0]], sizegrowth = 0, sizemod = 1.0, texture = [[plasma]], }, }, }, }
gpl-2.0
9seconds/dotfiles
neovim/lua/_lsp.lua
1
3546
local M = { servers={}, null_ls={ code_actions={}, diagnostics={}, formattings={}, hovers={}, completions={}, customs={} } } -- this function is executed when LSP attaches to a buffer. local function on_attach(client, bufnr) local navic = require("nvim-navic") navic.attach(client, bufnr) local function keymap(mode, lhs, rhs) vim.keymap.set(mode, lhs, rhs, {buffer=bufnr}) end vim.api.nvim_buf_set_option(bufnr, "omnifunc", "v:lua.vim.lsp.omnifunc") keymap("n", "<leader>fc", vim.lsp.buf.code_action) keymap("v", "<leader>fc", function() vim.lsp.buf.code_action({ options={ range=vim.lsp.util.make_range_params().range } }) end) keymap("n", "<c-]>", function() require('telescope.builtin').lsp_definitions() end) keymap("n", "<leader>f=", vim.lsp.buf.format) keymap("v", "<leader>f=", function() vim.lsp.buf.format({ options={ range=vim.lsp.util.make_range_params().range } }) end) keymap("n", "<leader>fr", function() require('telescope.builtin').lsp_references() end) keymap("n", "<leader>fd", function() require('telescope.builtin').lsp_document_symbols() end) keymap("n", "<leader>fh", vim.lsp.buf.hover) keymap("n", "<leader>fs", vim.lsp.buf.signature_help) keymap("n", "<leader>fn", vim.lsp.buf.rename) end -- add/modify config function M.configure_server(self, name, config) self.servers[name] = config or {} end -- add/modify null ls source function M.null_ls_set_code_action(self, name, config) self.null_ls.code_actions[name] = config or {} end -- add/modify null ls diagnostic function M.null_ls_set_diagnostic(self, name, config) self.null_ls.diagnostics[name] = config or {} end -- add/modify null ls diagnostic function M.null_ls_set_formatting(self, name, config) self.null_ls.formattings[name] = config or {} end -- add/modify null ls hovers function M.null_ls_set_hover(self, name, config) self.null_ls.hovers[name] = config or {} end -- add/modify null ls completions function M.null_ls_set_hover(self, name, config) self.null_ls.completions[name] = config or {} end -- add/modify null ls custom server definition function M.null_ls_set_custom(self, name, config) self.null_ls.customs[name] = config or {} end -- do setup lsp function M.setup(self) local lsp_installer = require("nvim-lsp-installer") local null_ls = require("null-ls") lsp_installer.on_server_ready(function(server) local opts = vim.tbl_deep_extend( "force", { on_attach=on_attach, flags={ debounce_text_changes=100, }, }, self.servers[server.name] or {} ) server:setup(opts) end) local null_ls_sources = {} local function add(source, config) if config ~= nil then source = source.with(config) end table.insert(null_ls_sources, source) end for k, v in pairs(self.null_ls.code_actions) do add(null_ls.builtins.code_actions[k], v) end for k, v in pairs(self.null_ls.diagnostics) do add(null_ls.builtins.diagnostics[k], v) end for k, v in pairs(self.null_ls.formattings) do add(null_ls.builtins.formatting[k], v) end for k, v in pairs(self.null_ls.hovers) do add(null_ls.builtins.hover[k], v) end for k, v in pairs(self.null_ls.completions) do add(null_ls.builtins.completion[k], v) end for k, v in pairs(self.null_ls.customs) do null_ls.register(v) end null_ls.setup({ sources=null_ls_sources }) end return M
mit
matthewbauer/wesnoth
data/ai/micro_ais/cas/ca_forest_animals_tusker_attack.lua
26
2575
local H = wesnoth.require "lua/helper.lua" local AH = wesnoth.require "ai/lua/ai_helper.lua" local function get_tuskers(cfg) local tuskers = AH.get_units_with_moves { side = wesnoth.current.side, type = cfg.tusker_type } return tuskers end local function get_adjacent_enemies(cfg) local adjacent_enemies = wesnoth.get_units { { "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } }, { "filter_adjacent", { side = wesnoth.current.side, type = cfg.tusklet_type } } } return adjacent_enemies end local ca_forest_animals_tusker_attack = {} function ca_forest_animals_tusker_attack:evaluation(ai, cfg) -- Check whether there is an enemy next to a tusklet and attack it ("protective parents" AI) if (not cfg.tusker_type) or (not cfg.tusklet_type) then return 0 end if (not get_tuskers(cfg)[1]) then return 0 end if (not get_adjacent_enemies(cfg)[1]) then return 0 end return cfg.ca_score end function ca_forest_animals_tusker_attack:execution(ai, cfg) local tuskers = get_tuskers(cfg) local adjacent_enemies = get_adjacent_enemies(cfg) -- Find the closest enemy to any tusker local min_dist, attacker, target = 9e99 for _,tusker in ipairs(tuskers) do for _,enemy in ipairs(adjacent_enemies) do local dist = H.distance_between(tusker.x, tusker.y, enemy.x, enemy.y) if (dist < min_dist) then min_dist, attacker, target = dist, tusker, enemy end end end -- The tusker moves as close to enemy as possible -- Closeness to tusklets is secondary criterion local adj_tusklets = wesnoth.get_units { side = wesnoth.current.side, type = cfg.tusklet_type, { "filter_adjacent", { id = target.id } } } local best_hex = AH.find_best_move(attacker, function(x, y) local rating = - H.distance_between(x, y, target.x, target.y) for _,tusklet in ipairs(adj_tusklets) do if (H.distance_between(x, y, tusklet.x, tusklet.y) == 1) then rating = rating + 0.1 end end return rating end) AH.movefull_stopunit(ai, attacker, best_hex) if (not attacker) or (not attacker.valid) then return end if (not target) or (not target.valid) then return end local dist = H.distance_between(attacker.x, attacker.y, target.x, target.y) if (dist == 1) then AH.checked_attack(ai, attacker, target) else AH.checked_stopunit_attacks(ai, attacker) end end return ca_forest_animals_tusker_attack
gpl-2.0
AresTao/darkstar
scripts/zones/Cape_Teriggan/npcs/HomePoint#1.lua
19
1196
----------------------------------- -- Area: Cape Teriggan -- NPC: HomePoint#1 -- @pos -303 -8 526 113 ----------------------------------- package.loaded["scripts/zones/Cape_Teriggan/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Cape_Teriggan/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 91); 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 == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
erfan1292/sezar
plugins/expire.lua
4
1948
local filename='data/expire.lua' local cronned = load_from_file(filename) local function save_cron(msg, text,date) local origin = get_receiver(msg) if not cronned[date] then cronned[date] = {} end local arr = { origin, text } ; table.insert(cronned[date], arr) serialize_to_file(cronned, filename) return 'ذخیره شد' end local function delete_cron(date) for k,v in pairs(cronned) do if k == date then cronned[k]=nil end end serialize_to_file(cronned, filename) end local function cron() for date, values in pairs(cronned) do if date < os.time() then --time's up send_msg(values[1][1], "مدت زمان گروه شما به اتمام رسید"..values[1][2], ok_cb, false) delete_cron(date) end end end local function actually_run(msg, delay,text) if (not delay or not text) then return "Usage: !remind [delay: 2h3m1s] text" end save_cron(msg, text,delay) return "مدت زمان انقضای گروه به" .. os.date("%x at %H:%M:%S",delay) .. " تنظیم شد \n\nتوضیحات\n" .. text .. "'" end local function run(msg, matches) local sum = 0 for i = 1, #matches-1 do local b,_ = string.gsub(matches[i],"[a-zA-Z]","") if string.find(matches[i], "s") then sum=sum+b end if string.find(matches[i], "m") then sum=sum+b*60 end if string.find(matches[i], "h") then sum=sum+b*3600 end end local date=sum+os.time() local text = matches[#matches] local text = actually_run(msg, date, text) return text end return { patterns = { "^[!/](expire) ([0-9]+[hmsdHMSD]) (.+)$", --- e.g : for a month enter : 720hms - then , in text enter gp id and admin id "^[!/](expire) ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$", "^[!/](expire) ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$" }, run = run, cron = cron }
gpl-2.0
socurites/tic-tac-toe-rl.torch
TicTacToeMemory.lua
1
2587
--[[ -- Relay Memory for Tic Tac Toe -- @maxMemory number the max number of experience to be remembered -- @discount number the discount factor ]]-- function TicTacToeMemory(maxMemory, discount) local memory = {} -- Appends the experience to the memory. -- @param memoryInput table the newly expierenced state transition of an episode function memory.remember(memoryInput) --[[ for i=1, #memory do local target = memory[i] local other = memoryInput if ( target.action == other.action and target.reward == other.reward and target.gameOver == other.gameOver and torch.all(torch.eq(target.inputState, other.inputState)) and torch.all(torch.eq(target.nextState, other.nextState)) ) then return nil end end ]]-- table.insert(memory, memoryInput) if (#memory > maxMemory) then table.remove(memory, 1) end end -- Get mini-batch -- @param model -- @param batchSize -- @param numActions -- @param numStates function memory.getBatch(model, batchSize, numActions, numStates) local memoryLength = #memory local chosenBatchSize = math.min(batchSize, memoryLength) local inputs = torch.Tensor(chosenBatchSize, numStates):zero() local targets = torch.Tensor(chosenBatchSize, numActions):zero() for i = 1, chosenBatchSize do -- Choose a random memory experience to add to the batch. local randomIndex = math.random(1, memoryLength) local memoryInput = memory[randomIndex] local target = model:forward(memoryInput.inputState):clone() --Gives us Q_sa, the max q for the next state. local nextStateMaxQ = torch.max(model:forward(memoryInput.nextState), 1)[1] if (memoryInput.gameOver) then target[memoryInput.action] = memoryInput.reward else -- reward + discount(gamma) * max_a' Q(s',a') -- We are setting the Q-value for the action to r + γmax a’ Q(s’, a’). The rest stay the same -- to give an error of 0 for those outputs. target[memoryInput.action] = memoryInput.reward + discount * nextStateMaxQ end -- Update the inputs and targets. inputs[i] = memoryInput.inputState targets[i] = target end return inputs, targets end return memory end
mit
AresTao/darkstar
scripts/zones/Castle_Zvahl_Keep/npcs/HomePoint#1.lua
17
1261
----------------------------------- -- Area: Castle_Zvahl_Keep -- NPC: HomePoint#1 -- @pos -554 -70 66 162 ----------------------------------- package.loaded["scripts/zones/Castle_Zvahl_Keep/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Castle_Zvahl_Keep/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 58); 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 == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
AresTao/darkstar
scripts/globals/weaponskills/realmrazer.lua
30
1450
----------------------------------- -- Realmrazer -- Club weapon skill -- Skill Level: 357 -- Delivers a seven-hit attack. params.accuracy varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Shadow Gorget & Soil Gorget. -- Aligned with the Shadow Belt & Soil Belt. -- Element: None -- Modifiers: MND:73~85% -- 100%TP 200%TP 300%TP -- .88 .88 .88 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 7; params.ftp100 = 0.88; params.ftp200 = 0.88; params.ftp300 = 0.88; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.85 + (player:getMerit(MERIT_REALMRAZER) / 100); params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.mnd_wsc = 0.7 + (player:getMerit(MERIT_REALMRAZER) / 100); end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
letoram/arcan-legacy
attic/streamer/streamer.lua
1
22126
-- -- Development test-script for the layout config tool -- settings = { out_url = "rtmp://", record_fps = 30, record_vqual= 6, record_aqual= 4, record_res = 480, record_vpts = 12, record_apts = 0 }; soundmap = {}; function get_recstr() local recstr = "vcodec=H264:container=%s:acodec=MP3:fps=%d:" .. "apreset=%d:vpreset=%d:vptsofs=%d:aptsofs=%d%s"; local fname = ""; local args = ""; if (string.sub(settings.out_url, 1, 7) == "rtmp://") then fname = "stream"; args = string.format(recstr, "stream", settings.record_fps, settings.record_aqual, settings.record_vqual, settings.record_vpts, settings.record_apts, ":streamdst=" .. string.gsub(settings.out_url, ":", "\t")); elseif (string.sub(settings.out_url, 1, 7) == "file://") then fname = string.sub(settings.out_url, 8); args = string.format(recstr, "MKV", settings.record_fps, settings.record_aqual, settings.record_vqual, settings.record_vpts, settings.record_apts, ""); end return fname, args; end function streamer() system_load("scripts/listview.lua")(); system_load("scripts/keyconf.lua")(); -- input configuration dialogs system_load("scripts/3dsupport.lua")(); system_load("scripts/layout_editor.lua")(); -- used to define layouts system_load("scripts/osdkbd.lua")(); -- for defining stream destination system_load("scripts/calltrace.lua")(); system_load("scripts/resourcefinder.lua")(); system_load("scripts/calltrace.lua")(); system_load("shared.lua")(); dispatch_push({}, "default", nil, 200); setup_3dsupport(); settings.adevs = list_audio_inputs(); -- regular setup patterns for the necessary inputs keyconfig = keyconf_create({"rMENU_ESCAPE", "rMENU_UP", "rMENU_DOWN", "rMENU_LEFT", "rMENU_RIGHT", "rMENU_SELECT", "rCONTEXT", "aMOUSE_X", "aMOUSE_Y"}); if (keyconfig.active == false) then keyconfig:to_front(); dispatch_push({}, "keyconfig (full)", function(iotbl) if (keyconfig:input(iotbl) == true) then dispatch_pop(); toggle_main_menu(false, 0); end end, 0); else toggle_main_menu(); end end -- copied from gridle function osdkbd_inputfun(iotbl, dstkbd) local restbl = keyconfig:match(iotbl); local done = false; local resstr = nil; if (restbl) then for ind,val in pairs(restbl) do if (val == "MENU_ESCAPE" and iotbl.active) then play_audio(soundmap["OSDKBD_HIDE"]); return true, nil elseif (val == "MENU_SELECT" or val == "MENU_UP" or val == "MENU_LEFT" or val == "MENU_RIGHT" or val == "MENU_DOWN" or val == "CONTEXT") then resstr = dstkbd:input(val, iotbl.active); if (iotbl.active) then play_audio(val == "MENU_SELECT" and soundmap["OSDKBD_SELECT"] or soundmap["OSDKBD_MOVE"]); end -- also allow direct keyboard input elseif (iotbl.translated) then resstr = dstkbd:input_key(iotbl, iotbl.active); end -- stop processing labels immediately after we get a valid filterstring end else -- still need to try and input even if we didn't find a matching value if (iotbl.translated) then resstr = dstkbd:input_key(iotbl, iotbl.active); end end if (resstr) then return true, resstr; end return false, nil; end function show_helper() if (settings.infowin) then settings.infowin:destroy(); settings.infowin = nil; end local status = {}; local statusfmt = {}; if (settings.layout) then table.insert(status, string.format("Layout (%s) Loaded", settings.layout_name)); if (settings.layout["internal"] ~= nil) then if (settings.gametbl) then table.insert(status, "Game:" .. settings.gametbl.title); else table.insert(status, "No Game Defined"); statusfmt["No Game Defined"] = "\\b\\#ff9999"; end else table.insert(status, "No Internal Slot"); end if (settings.layout["vidcap"] ~= nil) then table.insert(status, tostring(#settings.layout["vidcap"]) .. " Video Feed Slots"); local str = "Feeds: "; for ind, val in ipairs(settings.layout["vidcap"]) do str = str .. string.format("(%d) => (%d)", ind, settings.vidcap[ind] ~= nil and settings.vidcap[ind] or 0); end table.insert(status, str); end if (settings.out_url ~= "rtmp://") then local streamlbl = "Stream to:" .. settings.out_url; table.insert(status, streamlbl); statusfmt[streamlbl] = "\\b\\#99ff99"; else table.insert(status, "No Stream Defined"); statusfmt["No Stream Defined"] = "\\b\\#ff9999"; end else table.insert(status, "No Layout"); end settings.infowin = listview_create( status, VRESW / 2, VRESH / 2, statusfmt ); settings.infowin:show(); hide_image(settings.infowin.cursorvid); move_image(settings.infowin.anchor, VRESW * 0.5, 0); end -- -- game should already be running, -- load and add video capture devices based on the mapping in settings -- populate static / dynamic images into a shared recordtarget -- function start_streaming() if (not run_view(false)) then toggle_main_menu(); return; end -- allocate intermediate storage local dstvid = fill_surface(VRESW, VRESH, 0, 0, 0, VRESW, VRESH); image_tracetag(dstvid, "[streaming source]"); local recordset = {}; for ind,val in ipairs(settings.layout.temporary) do table.insert(recordset, val); end for ind, val in ipairs(settings.layout.temporary_static) do table.insert(recordset, val); end local audset = {}; for ind, val in pairs(settings.atoggles) do local cap = capture_audio(ind); if (cap ~= nil and cap ~= BADID) then table.insert(audset, cap); end end if (internal_aid) then table.insert(audset, internal_aid); end local outfn, outurl = get_recstr(); if (#audset == 0) then outurl = outurl .. ":noaudio"; end define_recordtarget(dstvid, outfn, outurl, recordset, audset, RENDERTARGET_NODETACH, RENDERTARGET_SCALE, -1, function(source, status) print("recordtarget status", status.kind); end); while (current_menu ~= nil) do current_menu:destroy(); current_menu = current_menu.parent; end if (settings.infowin) then settings.infowin:destroy(); settings.infowin = nil; end local resetfun = function() settings.layout:destroy(); settings.layout = nil; end -- -- hide menu, cascade, go! -- dispatch_push({MENU_ESCAPE = resetfun}, "runtime_input", function(iotbl) local restbl = keyconfig:match(iotbl); if (restbl) then for ind, val in pairs(restbl) do if (val and valid_vid(settings.target)) then res = keyconfig:buildtbl(val, iotbl); if (res) then res.label = val; target_input(res, settings.target); else iotbl.label = val; target_input(iotbl, settings.target); end end end end end); video_3dorder(ORDER_LAST); end function get_audio_toggles() local lbls = {}; local ptrs = {}; local fmts = {}; local function toggle_audio(label) if (settings.atoggles[label] == nil) then settings.atoggles[label] = true; else settings.atoggles[label] = not settings.atoggles[label]; end current_menu.formats[label] = settings.atoggles[label] and settings.colourtable.notice_fontstr or nil; current_menu:invalidate(); current_menu:redraw(); end if (#settings.adevs > 0) then for ind, val in ipairs(settings.adevs) do table.insert(lbls, val); ptrs[val] = toggle_audio; if (settings.atoggles[val]) then fmts[ val] = settings.colourtable.notice_fontstr; end end end return lbls, ptrs, fmts; end function query_destination(file) local resstr = nil; local opts = {}; if (file) then opts.case_insensitive = false; opts.prefix = "file://"; opts.startstr = ""; else opts.case_insensitive = false; opts.prefix = "rtmp://"; opts.startstr = settings.out_url; -- quick hack to make it slightly easier ' -- to enter "big and nasty justin.tv kind" keys if (settings.out_url == "rtmp://" and resource("stream.key")) then if (open_rawresource("stream.key")) then local line = read_rawresource(); if (line ~= nil and string.len(line) > 0) then opts.startstr = line; end close_rawresource(); end end end local osdsavekbd = osdkbd_create( osdkbd_extended_table(), opts ); osdsavekbd:show(); -- do this here so we have access to the namespace where osdsavekbd exists dispatch_push({}, "osdkbd (streaming)", function(iotbl) complete, resstr = osdkbd_inputfun(iotbl, osdsavekbd); if (complete) then osdsavekbd:destroy(); osdsavekbd = nil; dispatch_pop(); if (resstr ~= nil and string.len(resstr) > 0) then settings.out_url = resstr; store_key("out_url", resstr); end toggle_main_menu(); end end , -1); end -- -- this parses the currently active layout (if any) -- and generates the appropriate menu entries -- depends on current layout (if any), target in layout, vidcap feeds in layout -- function toggle_main_menu() ready = settings.out_url ~= "rtmp://"; target = (settings.layout and settings.layout["internal"] ~= nil) and (#settings.layout["internal"] > 0) or nil; nvc = (settings.layout and settings.layout["vidcap"]) and #settings.layout["vidcap"] or 0; while current_menu ~= nil do current_menu:destroy(); dispatch_pop(); current_menu = current_menu.parent; end local menulbls = {"Layouts...", }; local menuptrs = {}; local menufmts = {}; menuptrs["Layouts..."] = gen_layout_menu; local streammenu = {}; local streamptrs = {}; local streamfmts = {}; add_submenu(streammenu, streamptrs, "Framerate...", "record_fps", gen_tbl_menu("record_fps", {12, 24, 25, 30, 50, 60}, function() end)); add_submenu(streammenu, streamptrs, "Max Vertical Resolution...", "record_res", gen_tbl_menu("record_res", {720, 576, 480, 360, 288, 240}, function() end)); add_submenu(streammenu, streamptrs, "Video Quality...", "record_vqual", gen_tbl_menu("record_vqual", {2, 4, 6, 8, 10}, function() end)); add_submenu(streammenu, streamptrs, "Audio Quality...", "record_aqual", gen_tbl_menu("record_aqual", {2, 4, 6, 8, 10}, function() end)); add_submenu(streammenu, streamptrs, "VPTS offset...", "record_vpts", gen_num_menu("record_vpts", 0, 4, 12, function() end)); add_submenu(streammenu, streamptrs, "APTS offset...", "record_apts", gen_num_menu("record_apts", 0, 4, 12, function() end)); table.insert(streammenu, "Define Stream..."); table.insert(streammenu, "Define File..."); if (settings.layout ~= nil) then add_submenu(menulbls, menuptrs, "Streaming Settings...", nil, streammenu, streamptrs, {}); table.insert(menulbls, "Audio Sources..."); menuptrs["Audio Sources..."] = function() menu_spawnmenu(get_audio_toggles()); end end -- copied from gridle internal streamptrs["Define Stream..."] = function(label, store) query_destination(false); end streamptrs["Define File..."] = function(label, store) query_destination(true); end add_submenu(menulbls, menuptrs, "Destination...", streammenu, streamptrs, {}); -- need a layout set in order to know what to define the different slots as if (target) then add_submenu(menulbls, menuptrs, "Setup Game...", nil, gen_tbl_menu(nil, list_targets(), list_targetgames, true)); end if (nvc > 0) then local ptrs = {}; local lbls = {}; for num=1, nvc do add_submenu(lbls, ptrs, "Slot " .. tostring(num) .. "...", nil, gen_num_menu(nil, 1, 1, 10, function(lbl) settings.vidcap[num] = tonumber(lbl); toggle_main_menu(); end )); end add_submenu(menulbls, menuptrs, "Video Feeds...", nil, lbls, ptrs, {}); end -- if everything is set up correctly, let the user start if (ready) then table.insert(menulbls, "Start Streaming"); menufmts["Start Streaming"] = [[\b\#00ff00]]; menuptrs["Start Streaming"] = start_streaming; end table.insert(menulbls, "--------"); table.insert(menulbls, "Quit"); menuptrs["Quit"] = shutdown; menufmts["Quit"] = [[\#ff0000]]; -- finally, activate (but don't allow escape to terminate) local imenu = {}; local escape_menu = function(label, save, sound) if (current_menu.parent ~= nil) then current_menu:destroy(); current_menu = current_menu.parent; if (sound == nil or sound == false) then play_audio(soundmap["MENU_FADE"]); end end end imenu["MENU_LEFT"] = escape_menu; imenu["MENU_ESCAPE"] = escape_menu; current_menu = listview_create(menulbls, VRESH * 0.9, VRESW / 3, fmts); current_menu.ptrs = menuptrs; current_menu.parent = nil; menu_defaultdispatch(imenu); dispatch_push(imenu, "streamer_main", nil, -1); current_menu:show(); show_helper(); end -- -- Will be triggered everytime the layout editor rebuilds its view -- Mostly expect the script to resolve a full resource description -- based on type and idtag Although some properties could be altered -- "in flight" and LAYRES_SPECIAL are even expected to be -- function load_cb(restype, lay) print("lay.idtag:", lay.idtag); if (restype == LAYRES_STATIC or restype == LAYRES_MODEL) then if (lay.idtag == "background") then return "backgrounds/" .. lay.res, (function(newvid) settings.background = newvid; end); elseif (lay.idtag == "image") then return "images/" .. lay.res; elseif (lay.idtag == "static_model") then return load_model(lay.res); else warning("load_cb(), unknown idtag: " .. tostring(lay.idtag)); end end -- don't progress until we have a data-source set if (settings.restbl == nil) then return nil; end if (restype == LAYRES_IMAGE or restype == LAYRES_FRAMESERVER) then local locfun = settings.restbl["find_" .. lay.idtag]; if (locfun ~= nil) then return locfun(settings.restbl); end elseif (restype == LAYRES_TEXT) then return settings.gametbl[lay.idtag]; end end function run_view(dry_run) settings.layout:show(); -- -- NOTE: missing: with a dry_run, just use placeholders -- for all "dynamic" sources -- -- NOTE:For creating the record-set, the temporary and -- temporary_static tables are swept -- and just re-added. When (if?) MRT or WORLDID -- recordsets are working, we'll switch to that -- if (settings.layout["internal"] and #settings.layout["internal"] > 0 and settings.gametbl) then local internal_vid, internal_aid = launch_target(settings.gametbl.gameid, LAUNCH_INTERNAL, function(source, status) if (status == "resized") then play_audio(status.source_audio); end end); if (not valid_vid(internal_vid)) then spawn_warning("Couldn't launch game, giving up."); return false; end show_image(internal_vid); settings.layout:add_imagevid(internal_vid, settings.layout["internal"][1]); settings.target = internal_vid; -- reuse the VID if we have clones, same with models and "display" ID if (#settings.layout["internal"] > 1) then for i=2, #settings.layout["internal"] do local newvid = instance_image(internal_vid); image_mask_clearall(newvid); settings.layout:add_imagevid(newvid, settings.layout["internal"][i]); end end end -- -- for each vidcap, check if the user has specified a mapping, -- if he has, check if there's already a session running -- (most capture devices don't permit sharing) -- and if so, instance, otherwise spawn a new one -- if (settings.layout["vidcap"] and #settings.layout["vidcap"] > 0) then for i=1,#settings.layout["vidcap"] do if (settings.vidcap[i] ~= nil) then if (settings.vidcaps[ settings.vidcap[i] ] ~= nil) then local newvid = instance_image(settings.vidcaps[ settings.vidcap[i] ]); image_mask_clearall(newvid); settings.layout:add_imagevid(newvid, settings.layout["vidcap"][i]); else local elem = settings.layout["vidcap"][i]; local reqstr = string.format("capture:device=%d:width=%d:height=%d", 1, elem.size[1], elem.size[2]); settings.vidcaps[ settings.vidcap[i] ] = load_movie(reqstr, FRAMESERVER_NOLOOP, function(source, status) if (status.kind == "resized") then resize_image(source, elem.size[1], elem.size[2]); end end ); settings.layout:add_imagevid(settings.vidcaps[ settings.vidcap[i] ], settings.layout["vidcap"][i]); end end end end if (settings.layout["bgeffect"]) then update_shader(settings.layout["bgeffect"][1].res); end return true; end function setup_game(label) local game = list_games({target = settings.current_target, game = label}); if (game and game[1]) then settings.gametbl = game[1]; local restbl = resourcefinder_search(settings.gametbl, true ); settings.restbl = restbl; toggle_main_menu(); end end function list_targetgames(label) gamelist = {}; games = list_games({target = label}); if not games or #games == 0 then return; end for ind, tbl in ipairs(games) do table.insert(gamelist, tbl.title); end settings.current_target = label; lbls, ptrs = gen_tbl_menu(nil, gamelist, setup_game, true); menu_spawnmenu(lbls, ptrs, {}); end function load_layout(lay) if (settings.layout) then settings.layout:destroy(); settings.layout = nil; end settings.layout = layout_load("layouts/" .. lay, load_cb); settings.layout_name = lay; settings.vidcap = {}; settings.restbl = nil; settings.gametbl = nil; settings.atoggles = {}; settings.vidcaps = {}; if (settings.layout ~= nil) then toggle_main_menu(settings.layout["internal"] ~= nil and (#settings.layout["internal"] > 0), settings.layout["vidcap"] and #settings.layout["vidcap"] or 0); else spawn_warning("Couldn't load layout: " .. lay); toggle_main_menu(false, 0); end end function define_layout() local osdsavekbd = osdkbd_create( osdkbd_alphanum_table(), opts ); osdsavekbd:show(); -- do this here so we have access to the namespace where osdsavekbd exists dispatch_push({}, "osdkbd (layout)", function(iotbl) complete, resstr = osdkbd_inputfun(iotbl, osdsavekbd); if (complete) then osdsavekbd:destroy(); osdsavekbd = nil; dispatch_pop(); if (resstr ~= nil and string.len(resstr) > 0) then if (string.sub(resstr, -4, -1) ~= ".lay") then resstr = resstr .. ".lay"; end lay_setup("layouts/" .. resstr); end end end, -1); end function gen_layout_menu() local laymenu, layptrs = build_globmenu("layouts/*.lay", load_layout, THEME_RESOURCE); local layfmt = {}; table.insert(laymenu, 1, "New Layout"); table.insert(laymenu, 2, "----------"); layptrs["New Layout"] = define_layout; layfmt["New Layout"] = [[\b\#00ff00]]; menu_spawnmenu(laymenu, layptrs, layfmt); end function update_shader(resname) if (valid_vid(settings.background)) then settings.shader = load_shader("shaders/fullscreen/default.vShader", "shaders/bgeffects/" .. resname, "bgeffect", {}); image_shader(settings.background, settings.shader); shader_uniform(settings.shader, "display", "ff", PERSIST, VRESW, VRESH); end end function hookfun(newitem) -- autotile! if (newitem.idtag == "background") then local props = image_surface_initial_properties(newitem.vid); if (props.width / VRESW < 0.3 and newitem.tile_h == 1) then newitem.tile_h = math.ceil(VRESW / props.width); end if (props.height / VRESH < 0.3 and newitem.tile_v == 1) then newitem.tile_v = math.ceil(VRESH / props.height); end newitem.zv = 1; newitem.x = 0; newitem.y = 0; newitem.width = VRESW; newitem.height = VRESH; settings.background = newitem.vid; switch_default_texmode(TEX_REPEAT, TEX_REPEAT, newitem.vid); newitem:update(); elseif (newitem.idtag == "bgeffect") then update_shader(newitem.res); end end function lay_setup(layname) while current_menu ~= nil do current_menu:destroy(); current_menu = current_menu.parent; end if (settings.infowin) then settings.infowin:destroy(); settings.infowin = nil; end if (settings.layout) then settings.layout:destroy(); settings.layout = nil; end local identtext = function(key) vid = render_text(settings.colourtable.label_fontstr .. key); return vid; end local identphold = function(key) vid = load_image("images/placeholders/" .. string.lower(key) .. ".png"); if (not valid_vid(vid)) then vid = fill_surface(64, 64, math.random(128), math.random(128), math.random(128)); end return vid; end layout = layout_new(layname); layout:add_resource("background", "Background...", function() return glob_resource("backgrounds/*.png"); end, nil, LAYRES_STATIC, true, function(key) return load_image("backgrounds/" .. key); end); layout:add_resource("bgeffect", "Background Effect...", function() return glob_resource("shaders/bgeffects/*.fShader"); end, nil, LAYRES_SPECIAL, true, nil); layout:add_resource("movie", "Movie", "Movie", "Dynamic Media...", LAYRES_FRAMESERVER, false, identphold); layout:add_resource("image", "Image...", function() return glob_resource("images/*.png"); end, nil, LAYRES_STATIC, false, function(key) return load_image("images/" .. key); end); for ind, val in ipairs( {"Screenshot", "Boxart", "Boxart (Back)", "Fanart", "Bezel", "Marquee"} ) do layout:add_resource(string.lower(val), val, val, "Dynamic Media...", LAYRES_IMAGE, false, identphold); end for ind, val in ipairs( {"Title", "Genre", "Subgenre", "Setname", "Manufacturer", "Buttons", "Players", "Year", "Target", "System"} ) do layout:add_resource(string.lower(val), val, val, "Dynamic Text...", LAYRES_TEXT, false, nil); end layout:add_resource("internal", "internal", "Internal Launch", "Input Feeds...", LAYRES_FRAMESERVER, false, load_image("images/placeholders/internal.png")); layout:add_resource("vidcap", "vidcap", "Video Capture", "Input Feeds...", LAYRES_FRAMESERVER, false, load_image("images/placeholders/vidcap.png")); layout.post_save_hook = hookfun; layout.finalizer = function(state) if (state) then load_layout(string.sub(layname, 9)); else toggle_main_menu(); end end layout.validation_hook = function() for ind, val in ipairs(layout.items) do if (val.idtag == "internal" or val.idtag == "vidcap") then return true; end end return false; end layout:show(); end -- the shared code partially uses this, -- since the soundmap is empty, just stop sources that are null. local oldplay = play_audio; function play_audio(source) if (source) then oldplay(source); end end
unlicense
AdiAddons/AdiButtonAuras
core/AuraTools.lua
1
7609
--[[ AdiButtonAuras - Display auras on action buttons. Copyright 2013-2022 Adirelle (adirelle@gmail.com) All rights reserved. This file is part of AdiButtonAuras. AdiButtonAuras 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. AdiButtonAuras 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 AdiButtonAuras. If not, see <http://www.gnu.org/licenses/>. --]] local addonName, addon = ... local _G = _G local CreateFrame = _G.CreateFrame local ipairs = _G.ipairs local next = _G.next local pairs = _G.pairs local rawget = _G.rawget local setmetatable = _G.setmetatable local UnitAura = _G.UnitAura local wipe = _G.wipe local math = _G.math local GetTime = _G.GetTime local type = _G.type local UnitExists = _G.UnitExists local UnitGUID = _G.UnitGUID local Debug = function(...) addon.Debug('AuraTools', ...) end ------------------------------------------------------------------------------ -- Table recycling ------------------------------------------------------------------------------ local new, del do local heap = setmetatable({}, { __mode = 'k' }) function new() local t = next(heap) if not t then return {} end heap[t] = nil return t end function del(t) if t then heap[t] = true end end end ------------------------------------------------------------------------------ -- Prototypes ------------------------------------------------------------------------------ local function UpdateAuras(self) self.__guid = UnitGUID(self.__unit) if not self.__guid then for k, v in pairs(self) do if type(k) == "number" then self[k] = del(v) end end return end return self:_Update(self.__unit, self.__filter) end local function CheckGUID(self) if self.__guid ~= UnitGUID(self.__unit) then self:Update() end return self end local playerAurasMetatable = { __index = { Update = UpdateAuras, CheckGUID = CheckGUID, _Update = function(self, unit, filter) local serial = GetTime() for index = 1, math.huge do local name, _, count, dispel, _, expiration, _, _, _, id = UnitAura(unit, index, filter) if not name then break end local aura = rawget(self, id) if not aura then aura = new() self[id] = aura end aura.count = count aura.dispel = dispel aura.expiration = expiration aura.id = id aura.serial = serial end for id, aura in pairs(self) do if type(id) == "number" and aura.serial ~= serial then self[id] = del(aura) end end return self end, GetById = function(self, id) return rawget(self, id) end, } } local allAurasMetatable = { __index = { Update = UpdateAuras, CheckGUID = CheckGUID, _Update = function(self, unit, filter) for index = 1, math.huge do local name, _, count, dispel, _, expiration, _, canRemove, _, id = UnitAura(unit, index, filter) if not name then for i = index, #self do self[i] = del(rawget(self, i)) end return end local aura = rawget(self, index) if not aura then aura = new() self[index] = aura end if canRemove and dispel == "" then -- TODO: check bleeds dispel = "Enrage" end aura.count = count aura.dispel = dispel aura.expiration = expiration aura.id = id end return self end, GetById = function(self, id) for _, aura in ipairs(self) do if aura.id == id then return aura end end end, } } local function UpdateUnit(self) for _, auras in pairs(self) do if type(auras) == "table" then auras:Update() end end end local mts = { PlayerBuff = { filter = 'HELPFUL PLAYER', metatable = playerAurasMetatable }, PlayerDebuff = { filter = 'HARMFUL PLAYER', metatable = playerAurasMetatable }, Buff = { filter = 'HELPFUL', metatable = allAurasMetatable }, Debuff = { filter = 'HARMFUL', metatable = allAurasMetatable }, } local unitMetatable = { __index = function(self, key) if key == 'Update' then return UpdateUnit elseif key and mts[key] then Debug('Spawning', key, 'cache for', self.__unit) local auras = setmetatable( { __unit = self.__unit, __filter = mts[key].filter, }, mts[key].metatable ) auras:Update() self[key] = auras return auras end end } ------------------------------------------------------------------------------ -- The cache and its updater ------------------------------------------------------------------------------ local cache = setmetatable({}, { __index = function(self, unit) Debug('Spawning cache for', unit) local unitAuras = setmetatable({__unit = unit}, unitMetatable) self[unit] = unitAuras return unitAuras end }) local eventFrame = CreateFrame("Frame") eventFrame:SetScript('OnEvent', function(self, event, unit) if event == 'UNIT_AURA' then if rawget(cache, unit) then cache[unit]:Update() end elseif event == 'PLAYER_REGEN_ENABLED' then wipe(cache) end end) eventFrame:RegisterEvent('UNIT_AURA') eventFrame:RegisterEvent('PLAYER_REGEN_ENABLED') ------------------------------------------------------------------------------ -- Accessors ------------------------------------------------------------------------------ local function auraIterator(auras, index) local nextIndex, aura = index repeat nextIndex, aura = next(auras, nextIndex) if type(nextIndex) == "number" then return nextIndex, aura.id, aura.count, aura.expiration, aura.dispel end until not nextIndex end local function NOP() end local getters = {} local iterators = {} for key in pairs(mts) do getters[key] = function(unit, id) if unit and UnitExists(unit) then local aura = cache[unit][key]:CheckGUID():GetById(id) if aura then return id, aura.count, aura.expiration, aura.dispel end end end iterators[key] = function(unit) if not unit or not UnitExists(unit) then return NOP end return auraIterator, cache[unit][key]:CheckGUID() end end ------------------------------------------------------------------------------ -- Filter parser, memoized ------------------------------------------------------------------------------ local parsedFilter = addon.Memoize(function(filter) return (filter:match('PLAYER') and 'Player' or '') .. (filter:match('HARMFUL') and 'Debuff' or 'Buff') end) ------------------------------------------------------------------------------ -- Functions for the rule environment ------------------------------------------------------------------------------ addon.AuraTools = { GetAura = function(unit, id, filter) return getters[parsedFilter[filter]](unit, id) end, IterateAuras = function(unit, filter) return iterators[parsedFilter[filter]](unit) end } for suffix, getter in pairs(getters) do addon.AuraTools["Get"..suffix] = getter end for suffix, iterator in pairs(iterators) do addon.AuraTools["Iterate"..suffix.."s"] = iterator end ------------------------------------------------------------------------------ -- Helpers to build rules ------------------------------------------------------------------------------ function addon.GetAuraGetter(filter) return getters[parsedFilter[filter]] end function addon.GetAuraIterator(filter) return iterators[parsedFilter[filter]] end
gpl-3.0
AresTao/darkstar
scripts/globals/items/cup_of_chocomilk.lua
35
1163
----------------------------------------- -- ID: 4498 -- Item: cup_of_chocomilk -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic Regen While Healing 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4498); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 3); end;
gpl-3.0
AresTao/darkstar
scripts/globals/spells/ionohelix.lua
22
1721
-------------------------------------- -- Spell: Ionohelix -- Deals lightning damage that gradually reduces -- a target's HP. Damage dealt is greatly affected by the weather. -------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --get helix acc/att merits local merit = caster:getMerit(MERIT_HELIX_MAGIC_ACC_ATT); --calculate raw damage local dmg = calculateMagicDamage(35,1,caster,spell,target,ELEMENTAL_MAGIC_SKILL,MOD_INT,false); dmg = dmg + caster:getMod(MOD_HELIX_EFFECT); --get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ELEMENTAL_MAGIC_SKILL,merit*3); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg,merit*2); --add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); local dot = dmg; --add in final adjustments dmg = finalMagicAdjustments(caster,target,spell,dmg); -- calculate Damage over time dot = target:magicDmgTaken(dot); utils.clamp(dot, 0, 99999); local duration = getHelixDuration(caster) + caster:getMod(MOD_HELIX_DURATION); duration = duration * (resist/2); target:addStatusEffect(EFFECT_HELIX,dot,3,duration); return dmg; end;
gpl-3.0
thess/OpenWrt-luci
applications/luci-app-pbx/luasrc/model/cbi/pbx-advanced.lua
99
14473
--[[ Copyright 2011 Iordan Iordanov <iiordanov (AT) gmail.com> This file is part of luci-pbx. luci-pbx is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. luci-pbx is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with luci-pbx. If not, see <http://www.gnu.org/licenses/>. ]]-- if nixio.fs.access("/etc/init.d/asterisk") then server = "asterisk" elseif nixio.fs.access("/etc/init.d/freeswitch") then server = "freeswitch" else server = "" end appname = "PBX" modulename = "pbx-advanced" defaultbindport = 5060 defaultrtpstart = 19850 defaultrtpend = 19900 -- Returns all the network related settings, including a constructed RTP range function get_network_info() externhost = m.uci:get(modulename, "advanced", "externhost") ipaddr = m.uci:get("network", "lan", "ipaddr") bindport = m.uci:get(modulename, "advanced", "bindport") rtpstart = m.uci:get(modulename, "advanced", "rtpstart") rtpend = m.uci:get(modulename, "advanced", "rtpend") if bindport == nil then bindport = defaultbindport end if rtpstart == nil then rtpstart = defaultrtpstart end if rtpend == nil then rtpend = defaultrtpend end if rtpstart == nil or rtpend == nil then rtprange = nil else rtprange = rtpstart .. "-" .. rtpend end return bindport, rtprange, ipaddr, externhost end -- If not present, insert empty rules in the given config & section named PBX-SIP and PBX-RTP function insert_empty_sip_rtp_rules(config, section) -- Add rules named PBX-SIP and PBX-RTP if not existing found_sip_rule = false found_rtp_rule = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' then found_sip_rule = true elseif s1._name == 'PBX-RTP' then found_rtp_rule = true end end) if found_sip_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-SIP') end if found_rtp_rule ~= true then newrule=m.uci:add(config, section) m.uci:set(config, newrule, '_name', 'PBX-RTP') end end -- Delete rules in the given config & section named PBX-SIP and PBX-RTP function delete_sip_rtp_rules(config, section) -- Remove rules named PBX-SIP and PBX-RTP commit = false m.uci:foreach(config, section, function(s1) if s1._name == 'PBX-SIP' or s1._name == 'PBX-RTP' then m.uci:delete(config, s1['.name']) commit = true end end) -- If something changed, then we commit the config. if commit == true then m.uci:commit(config) end end -- Deletes QoS rules associated with this PBX. function delete_qos_rules() delete_sip_rtp_rules ("qos", "classify") end function insert_qos_rules() -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("qos", "classify") -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() -- Iterate through the QoS rules, and if there is no other rule with the same port -- range at the priority service level, insert this rule. commit = false m.uci:foreach("qos", "classify", function(s1) if s1._name == 'PBX-SIP' then if s1.ports ~= bindport or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", bindport) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end elseif s1._name == 'PBX-RTP' then if s1.ports ~= rtprange or s1.target ~= "Priority" or s1.proto ~= "udp" then m.uci:set("qos", s1['.name'], "ports", rtprange) m.uci:set("qos", s1['.name'], "proto", "udp") m.uci:set("qos", s1['.name'], "target", "Priority") commit = true end end end) -- If something changed, then we commit the qos config. if commit == true then m.uci:commit("qos") end end -- This function is a (so far) unsuccessful attempt to manipulate the firewall rules from here -- Need to do more testing and eventually move to this mode. function maintain_firewall_rules() -- Get the network information bindport, rtprange, ipaddr, externhost = get_network_info() commit = false -- Only if externhost is set, do we control firewall rules. if externhost ~= nil and bindport ~= nil and rtprange ~= nil then -- Insert empty PBX-SIP and PBX-RTP rules if not present. insert_empty_sip_rtp_rules ("firewall", "rule") -- Iterate through the firewall rules, and if the dest_port and dest_ip setting of the\ -- SIP and RTP rule do not match what we want configured, set all the entries in the rule\ -- appropriately. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then if s1.dest_port ~= bindport then m.uci:set("firewall", s1['.name'], "dest_port", bindport) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end elseif s1._name == 'PBX-RTP' then if s1.dest_port ~= rtprange then m.uci:set("firewall", s1['.name'], "dest_port", rtprange) m.uci:set("firewall", s1['.name'], "src", "wan") m.uci:set("firewall", s1['.name'], "proto", "udp") m.uci:set("firewall", s1['.name'], "target", "ACCEPT") commit = true end end end) else -- We delete the firewall rules if one or more of the necessary parameters are not set. sip_rule_name=nil rtp_rule_name=nil -- First discover the configuration names of the rules. m.uci:foreach("firewall", "rule", function(s1) if s1._name == 'PBX-SIP' then sip_rule_name = s1['.name'] elseif s1._name == 'PBX-RTP' then rtp_rule_name = s1['.name'] end end) -- Then, using the names, actually delete the rules. if sip_rule_name ~= nil then m.uci:delete("firewall", sip_rule_name) commit = true end if rtp_rule_name ~= nil then m.uci:delete("firewall", rtp_rule_name) commit = true end end -- If something changed, then we commit the firewall config. if commit == true then m.uci:commit("firewall") end end m = Map (modulename, translate("Advanced Settings"), translate("This section contains settings that do not need to be changed under \ normal circumstances. In addition, here you can configure your system \ for use with remote SIP devices, and resolve call quality issues by enabling \ the insertion of QoS rules.")) -- Recreate the voip server config, and restart necessary services after changes are commited -- to the advanced configuration. The firewall must restart because of "Remote Usage". function m.on_after_commit(self) -- Make sure firewall rules are in place maintain_firewall_rules() -- If insertion of QoS rules is enabled if m.uci:get(modulename, "advanced", "qos_enabled") == "yes" then insert_qos_rules() else delete_qos_rules() end luci.sys.call("/etc/init.d/pbx-" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/" .. server .. " restart 1\>/dev/null 2\>/dev/null") luci.sys.call("/etc/init.d/firewall restart 1\>/dev/null 2\>/dev/null") end ----------------------------------------------------------------------------- s = m:section(NamedSection, "advanced", "settings", translate("Advanced Settings")) s.anonymous = true s:tab("general", translate("General Settings")) s:tab("remote_usage", translate("Remote Usage"), translatef("You can use your SIP devices/softphones with this system from a remote location \ as well, as long as your Internet Service Provider gives you a public IP. \ You will be able to call other local users for free (e.g. other Analog Telephone Adapters (ATAs)) \ and use your VoIP providers to make calls as if you were local to the PBX. \ After configuring this tab, go back to where users are configured and see the new \ Server and Port setting you need to configure the remote SIP devices with. Please note that if this \ PBX is not running on your router/gateway, you will need to configure port forwarding (NAT) on your \ router/gateway. Please forward the ports below (SIP port and RTP range) to the IP address of the \ device running this PBX.")) s:tab("qos", translate("QoS Settings"), translate("If you experience jittery or high latency audio during heavy downloads, you may want \ to enable QoS. QoS prioritizes traffic to and from your network for specified ports and IP \ addresses, resulting in better latency and throughput for sound in our case. If enabled below, \ a QoS rule for this service will be configured by the PBX automatically, but you must visit the \ QoS configuration page (Network->QoS) to configure other critical QoS settings like Download \ and Upload speed.")) ringtime = s:taboption("general", Value, "ringtime", translate("Number of Seconds to Ring"), translate("Set the number of seconds to ring users upon incoming calls before hanging up \ or going to voicemail, if the voicemail is installed and enabled.")) ringtime.datatype = "port" ringtime.default = 30 ua = s:taboption("general", Value, "useragent", translate("User Agent String"), translate("This is the name that the VoIP server will use to identify itself when \ registering to VoIP (SIP) providers. Some providers require this to a specific \ string matching a hardware SIP device.")) ua.default = appname h = s:taboption("remote_usage", Value, "externhost", translate("Domain/IP Address/Dynamic Domain"), translate("You can enter your domain name, external IP address, or dynamic domain name here. \ The best thing to input is a static IP address. If your IP address is dynamic and it changes, \ your configuration will become invalid. Hence, it's recommended to set up Dynamic DNS in this case. \ and enter your Dynamic DNS hostname here. You can configure Dynamic DNS with the luci-app-ddns package.")) h.datatype = "host" p = s:taboption("remote_usage", Value, "bindport", translate("External SIP Port"), translate("Pick a random port number between 6500 and 9500 for the service to listen on. \ Do not pick the standard 5060, because it is often subject to brute-force attacks. \ When finished, (1) click \"Save and Apply\", and (2) look in the \ \"SIP Device/Softphone Accounts\" section for updated Server and Port settings \ for your SIP Devices/Softphones.")) p.datatype = "port" p = s:taboption("remote_usage", Value, "rtpstart", translate("RTP Port Range Start"), translate("RTP traffic carries actual voice packets. This is the start of the port range \ that will be used for setting up RTP communication. It's usually OK to leave this \ at the default value.")) p.datatype = "port" p.default = defaultrtpstart p = s:taboption("remote_usage", Value, "rtpend", translate("RTP Port Range End")) p.datatype = "port" p.default = defaultrtpend p = s:taboption("qos", ListValue, "qos_enabled", translate("Insert QoS Rules")) p:value("yes", translate("Yes")) p:value("no", translate("No")) p.default = "yes" return m
apache-2.0
DeinFreund/Zero-K
LuaUI/Widgets/api_selectionsend.lua
9
3751
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:GetInfo() return { name = "Selection Send", desc = "v0.02 Sends and Receives IDs of selected units to allies to be used by other widgets.", author = "CarRepairer", date = "2009-4-27", license = "GNU GPL, v2 or later", layer = 5, enabled = true, -- loaded by default? alwaysStart = true, hidden = true, } end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- local selUnitsSend = {} local timeSinceBroadcast = 0 local BROADCAST_PERIOD = 10 local selchanged = false local allySelData = {} local allyActiveTx = {} WG.allySelUnits = {} local echo = Spring.Echo -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function widget:Initialize() WG.allySelUnits = {} end function widget:Shutdown() WG.allySelUnits = {} end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- -- -- Speed-ups -- local spGetMyPlayerID = Spring.GetMyPlayerID local spGetPlayerInfo = Spring.GetPlayerInfo local spGetSelectedUnits = Spring.GetSelectedUnits local SendLuaUIMsg = Spring.SendLuaUIMsg local function IsSpec() local _, _, spec, _, _, _, _, _ = spGetPlayerInfo(spGetMyPlayerID()) return spec --[[ if spec then Spring.Echo("<SelectionSend> Spectator mode. Widget removed.") widgetHandler:RemoveWidget() end --]] end local function SendSelUnits(selUnitsToSend) if IsSpec() then return end numSelUnits = #selUnitsToSend numSelUnits = numSelUnits < 10 and numSelUnits or 10 local uStr = '@' for i = 1, numSelUnits do --Spring.Echo ("pack to", selUnitsToSend[i], VFS.PackU16(selUnitsToSend[i])) uStr = uStr .. VFS.PackU16(selUnitsToSend[i]) end SendLuaUIMsg(uStr,"allies") end local function UpdateAllySelUnits() local allSelStr = '' for pid,dataStr in pairs(allySelData) do allSelStr = allSelStr .. dataStr end local allySelUnits2 = {} local num_units = allSelStr:len() / 2 for i = 1, num_units do local code = allSelStr:sub(i*2-1,i*2) --allySelUnits2[i] = VFS.UnpackU16(code) allySelUnits2[VFS.UnpackU16(code)] = true --Spring.Echo (i, "unpack to", code, VFS.UnpackU16(code)) end WG.allySelUnits = allySelUnits2 end function widget:Update(dt) timeSinceBroadcast = timeSinceBroadcast + dt if timeSinceBroadcast > BROADCAST_PERIOD then timeSinceBroadcast = 0 SendSelUnits(spGetSelectedUnits()) for pid,dataStr in pairs(allySelData) do allyActiveTx[pid] = allyActiveTx[pid] - 1 end if allyActiveTx[pid] == 0 then allySelData[playerID] = nil end elseif timeSinceBroadcast > 1 and selchanged then timeSinceBroadcast = 0 selchanged = false SendSelUnits(spGetSelectedUnits()) end end function widget:SelectionChanged(selectedUnits) selchanged = true end function widget:RecvLuaMsg(msg, playerID) if (msg:sub(1,1)=="@") then local _, _, spec = spGetPlayerInfo(playerID) if spec or (playerID==Spring.GetMyPlayerID()) then return true; end if msg == '@' then allySelData[playerID] = '' else allySelData[playerID] = msg:sub(2) end allyActiveTx[playerID] = 2 UpdateAllySelUnits() end end -------------------------------------------------------------------------------- --------------------------------------------------------------------------------
gpl-2.0
AresTao/darkstar
scripts/zones/The_Sanctuary_of_ZiTah/npcs/Ajimo-Majimo_WW.lua
30
3078
----------------------------------- -- Area: The Sanctuary of Zi'Tah -- NPC: Ajimo-Majimo, W.W. -- Outpost Conquest Guards -- @pos -40.079 -0.642 -148.785 121 ----------------------------------- package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"); local guardnation = WINDURST; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = LITELOR; local csid = 0x7ff7; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
AresTao/darkstar
scripts/zones/Quicksand_Caves/Zone.lua
17
5995
----------------------------------- -- -- Zone: Quicksand_Caves (208) -- ----------------------------------- package.loaded["scripts/zones/Quicksand_Caves/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/zone"); require("scripts/zones/Quicksand_Caves/TextIDs"); base_id = 17629685; ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local tomes = {17629766,17629767,17629768,17629769,17629770,17629771}; SetGroundsTome(tomes); -- Weight Door System (RegionID, X, Radius, Z) zone:registerRegion(1, -15, 5, -60, 0,0,0); -- 0x010D01EF Door zone:registerRegion(3, 15, 5,-180, 0,0,0); -- 0x010D01F1 Door zone:registerRegion(5, -580, 5,-420, 0,0,0); -- 0x010D01F3 Door zone:registerRegion(7, -700, 5,-420, 0,0,0); -- 0x010D01F5 Door zone:registerRegion(9, -700, 5,-380, 0,0,0); -- 0x010D01F7 Door zone:registerRegion(11, -780, 5,-460, 0,0,0); -- 0x010D01F9 Door zone:registerRegion(13, -820, 5,-380, 0,0,0); -- 0x010D01FB Door zone:registerRegion(15, -260, 5, 740, 0,0,0); -- 0x010D01FD Door zone:registerRegion(17, -340, 5, 660, 0,0,0); -- 0x010D01FF Door zone:registerRegion(19, -420, 5, 740, 0,0,0); -- 0x010D0201 Door zone:registerRegion(21, -340, 5, 820, 0,0,0); -- 0x010D0203 Door zone:registerRegion(23, -409, 5, 800, 0,0,0); -- 0x010D0205 Door zone:registerRegion(25, -400, 5, 670, 0,0,0); -- 0x010D0207 Door --[[ -- (Old) zone:registerRegion(1,-18,-1, -62,-13,1, -57); zone:registerRegion(3, 13,-1, -183, 18,1, -177); zone:registerRegion(5,-583,-1,-422,-577,1,-418); zone:registerRegion(7,-703,-1,-423,-697,1,-417); zone:registerRegion(9,-703,-1,-383,-697,1,-377); zone:registerRegion(11,-782,-1,-462,-777,1,-457); zone:registerRegion(13,-823,-1,-383,-817,1,-377); zone:registerRegion(15,-262,-1, 737,-257,1, 742); zone:registerRegion(17,-343,-1, 657,-337,1, 662); zone:registerRegion(19,-343,-1, 818,-337,1, 822); zone:registerRegion(21,-411,-1, 797,-406,1, 803); zone:registerRegion(23,-422,-1, 737,-417,1, 742); zone:registerRegion(25,-403,-1, 669,-397,1, 674); ]]-- -- Hole in the Sand zone:registerRegion(30,495,-9,-817,497,-7,-815); -- E-11 (Map 2) zone:registerRegion(31,815,-9,-744,817,-7,-742); -- M-9 (Map 2) zone:registerRegion(32,215,6,-17,217,8,-15); -- K-6 (Map 3) zone:registerRegion(33,-297,6,415,-295,8,417); -- E-7 (Map 6) zone:registerRegion(34,-137,6,-177,-135,8,-175); -- G-7 (Map 8) SetServerVariable("BastokFight8_1" ,0); SetServerVariable("Bastok8-1LastClear", os.time()-QM_RESET_TIME); -- Set a delay on ??? mission NM pop. UpdateTreasureSpawnPoint(17629735); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-980.193,14.913,-282.863,60); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) local RegionID = region:GetRegionID(); if (RegionID >= 30) then switch (RegionID): caseof { [30] = function (x) player:setPos(496,-6,-816); end, [31] = function (x) player:setPos(816,-6,-743); end, [32] = function (x) player:setPos(216,9,-16); end, [33] = function (x) player:setPos(-296,9,416); end, [34] = function (x) player:setPos(-136,9,-176); end, } else local race = player:getRace(); printf("entering region %u",RegionID); if (race == 8) then -- Galka weight = 3; elseif (race == 5 or race == 6) then -- Taru male or female weight = 1; else -- Hume/Elvaan/Mithra weight = 2; end local varname = "[DOOR]Weight_Sensor_"..RegionID; w = GetServerVariable(varname); w = w + weight; SetServerVariable(varname,w); if (player:hasKeyItem(2051) or w >= 3) then local door = GetNPCByID(base_id + RegionID - 1); door:openDoor(15); -- open door with a 15 second time delay. --platform = GetNPCByID(base_id + RegionID + 1); --platform:setAnimation(8); -- this is supposed to light up the platform but it's not working. Tried other values too. end end end; ----------------------------------- -- OnRegionLeave ----------------------------------- function onRegionLeave(player,region) local RegionID = region:GetRegionID(); if (RegionID < 30) then local race = player:getRace(); -- printf("exiting region %u",RegionID); if (race == 8) then -- Galka weight = 3; elseif (race == 5 or race == 6) then -- Taru male or female weight = 1; else -- Hume/Elvaan/Mithra weight = 2; end; local varname = "[DOOR]Weight_Sensor_"..RegionID; w = GetServerVariable(varname); lastWeight = w; w = w - weight; SetServerVariable(varname,w); if (lastWeight >= 3 and w < 3) then --platform = GetNPCByID(base_id + RegionID + 1); --platform:setAnimation(9); 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
AresTao/darkstar
scripts/globals/spells/bluemagic/regeneration.lua
46
1483
----------------------------------------- -- Spell: Regeneration -- Gradually restores HP -- Spell cost: 36 MP -- Monster Type: Aquans -- Spell Type: Magical (Light) -- Blue Magic Points: 2 -- Stat Bonus: MND+2 -- Level: 78 -- Casting Time: 2 Seconds -- Recast Time: 60 Seconds -- Spell Duration: 30 ticks, 90 Seconds -- -- Combos: None ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local typeEffect = EFFECT_REGEN; local power = 25; local duration = 90; if (caster:hasStatusEffect(EFFECT_DIFFUSION)) then local diffMerit = caster:getMerit(MERIT_DIFFUSION); if (diffMerit > 0) then duration = duration + (duration/100)* diffMerit; end; caster:delStatusEffect(EFFECT_DIFFUSION); end; if (target:hasStatusEffect(EFFECT_REGEN) and target:getStatusEffect(EFFECT_REGEN):getTier() == 1) then target:delStatusEffect(EFFECT_REGEN); end if (target:addStatusEffect(typeEffect,power,3,duration,0,0,0) == false) then spell:setMsg(75); end; return typeEffect; end;
gpl-3.0
AresTao/darkstar
scripts/zones/Hall_of_Transference/npcs/_0e1.lua
32
1340
----------------------------------- -- Area: Hall of Transference -- NPC: Cermet Gate - Dem -- @pos -220 -46 -279 14 ----------------------------------- package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Hall_of_Transference/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) > BELOW_THE_ARKS) then player:startEvent(0x0096); else player:messageSpecial(NO_RESPONSE_OFFSET+1); -- The door is firmly shut. 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 == 0x0096 and option == 1) then player:setPos(185.891, 0, -52.331, 128, 18); -- To Promyvion Dem {R} end end;
gpl-3.0
AresTao/darkstar
scripts/zones/Valkurm_Dunes/npcs/Quanteilleron_RK.lua
28
3133
----------------------------------- -- Area: Valkurm Dunes -- NPC: Quanteilleron, R.K. -- Outpost Conquest Guards -- @pos 144 -7 104 103 ------------------------------------- package.loaded["scripts/zones/Valkurm_Dunes/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Valkurm_Dunes/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = ZULKHEIM; local csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
socurites/tic-tac-toe-rl.torch
test.lua
1
8036
require 'nn' require 'optim' require 'TicTacToeMemory' require 'TicTacToeEnvironment' require 'TicTacToeRandomAgent' require 'TicTacToeQLearningAgent' require 'TicTacToeUtil' local cmd = torch.CmdLine() cmd:text('Training options') cmd:option('-epsilon', 0.9, 'The probability of choosing a random action (in training). This decays as iterations increase. (0 to 1)') cmd:option('-epsilonMinimumValue', 0.001, 'The minimum value we want epsilon to reach in training. (0 to 1)') cmd:option('-numActions', 9, 'The number of actions.') cmd:option('-epoch', 10, 'The number of games we want the system to run for.') cmd:option('-hiddenSize', 50, 'Number of neurons in the hidden layers.') cmd:option('-maxMemory', 362880, 'How large should the memory be (where it stores its past experiences).') cmd:option('-batchSize', 100, 'The mini-batch size for training. Samples are randomly taken from memory till mini-batch size.') cmd:option('-gridSize', 3, 'The size of the grid that the agent is going to play the game on.') cmd:option('-discount', 0.9, 'the discount is used to force the network to choose states that lead to the reward quicker (0 to 1)') cmd:option('-savePrefix', 'tictactoc-', 'Save path for model') cmd:option('-learningRate', 0.1) --cmd:option('-learningRateDecay', 1e-10) cmd:option('-learningRateDecay', 0.0) cmd:option('-weightDecay', 0) cmd:option('-momentum', 0.9) local opt = cmd:parse(arg) local epsilon = opt.epsilon local epsilonMinimumValue = opt.epsilonMinimumValue local numActions = opt.numActions local epoch = opt.epoch local hiddenSize = opt.hiddenSize local maxMemory = opt.maxMemory local batchSize = opt.batchSize local gridSize = opt.gridSize local numStates = gridSize * gridSize local discount = opt.discount -- Params for Stochastic Gradient Descent (our optimizer). local sgdParams = { learningRate = opt.learningRate, learningRateDecay = opt.learningRateDecay, weightDecay = opt.weightDecay, momentum = opt.momentum, dampening = 0, nesterov = true } math.randomseed(os.time()) local util = TicTacToeUtil() --[[ Runs one gradient update using SGD returning the loss.]] -- local function trainNetwork(model, inputs, targets, criterion, sgdParams) local loss = 0 local x, gradParameters = model:getParameters() local function feval(x_new) gradParameters:zero() local predictions = model:forward(inputs) local loss = criterion:forward(predictions, targets) local gradOutput = criterion:backward(predictions, targets) model:backward(inputs, gradOutput) return loss, gradParameters end local _, fs = optim.sgd(feval, x, sgdParams) loss = loss + fs[1] return loss end -- Create the base model. local modelO = nn.Sequential() modelO:add(nn.Linear(numStates, hiddenSize)) modelO:add(nn.Tanh()) modelO:add(nn.Linear(hiddenSize, hiddenSize)) modelO:add(nn.Tanh()) modelO:add(nn.Linear(hiddenSize, numActions)) modelO:add(nn.LogSoftMax()) local modelX = nn.Sequential() modelX:add(nn.Linear(numStates, hiddenSize)) modelX:add(nn.Tanh()) modelX:add(nn.Linear(hiddenSize, hiddenSize)) modelX:add(nn.Tanh()) modelX:add(nn.Linear(hiddenSize, numActions)) modelX:add(nn.LogSoftMax()) --[[ local modelO = torch.load("tictactoc-" .. "6000" .. ".t7") ]]-- -- Mean Squared Error for our loss function. local criterion = nn.ClassNLLCriterion() memoryO = TicTacToeMemory(maxMemory, discount) memoryX = TicTacToeMemory(maxMemory, discount) local env = TicTacToeEnvironment(gridSize) local agentO = TicTacToeQLearningAgent(numActions, modelO, -1) local agentX = TicTacToeQLearningAgent(numActions, modelX, 1) local winOCount = 0 local winXCount = 0 local drawCount = 0 local gameResult = '' for i = 1, epoch do -- Initialise the environment. env.reset() local errO = 0 local errX = 0 local gameOver = false local reward = 0 -- The initial state of the environment. local currState, nextState local action local experienceO = nil while (gameOver ~= true) do currState = env.observe():clone() -- First action = agentO.chooseAction(currState, epsilon) print('[agentO] : ' .. action) -- Update Enviroiment nextState, reward, gameOver = env.act(action, agentO.stone()) nextState = nextState:clone() if ( nextState ~= currState ) then experienceO = { inputState = currState:view(-1), action = action, reward = reward, nextState = nextState:view(-1), gameOver = gameOver } end -- Game over by player O if ( gameOver == true and experienceO ~= nil) then memoryO.remember(experienceO) if ( experienceO.reward == 1 ) then winOCount = winOCount + 1 experienceX.reward = -1 experienceX.gameOver = true gameResult = 'O Win' memoryX.remember(experienceX) experienceX = nil else drawCount = drawCount + 1 experienceX.reward = 0.5 experienceX.gameOver = true gameResult = 'Draw' memoryX.remember(experienceX) experienceX = nil end experienceO = nil else if ( experienceX ~= nil ) then memoryX.remember(experienceX) end -- Later currState = env.observe():clone() action = agentX.chooseAction(currState, epsilon) print('[agentX] : ' .. action) -- Update Enviroiment nextState, reward, gameOver = env.act(action, agentX.stone()) nextState = nextState:clone() if ( nextState ~= currState ) then experienceX = { inputState = currState:view(-1), action = action, reward = reward, nextState = nextState:view(-1), gameOver = gameOver } end -- Game over by player X if ( gameOver == true and experienceX ~= nil) then memoryX.remember(experienceX) if ( experienceX.reward == 1 ) then winXCount = winXCount + 1 experienceO.reward = -1 experienceO.gameOver = true gameResult = 'X Win' memoryO.remember(experienceO) experienceO = nil else drawCount = drawCount + 1 gameResult = 'Draw' memoryO.remember(experienceO) experienceO = nil end experienceX = nil elseif ( gameOver ~= true and experienceX ~= nil ) then memoryO.remember(experienceO) end end local inputs, targets = memoryO.getBatch(modelO, batchSize, numActions, numStates) if ( inputs:size(1) == 1 ) then inputs_1 = inputs:view(-1) else inputs_1 = inputs end _, index = torch.max(targets, 2) targets_1 = index:view(-1) errO = errO + trainNetwork(modelO, inputs_1, targets_1, criterion, sgdParams) if ( #memoryX > 0 ) then local inputs, targets = memoryX.getBatch(modelX, batchSize, numActions, numStates) if ( inputs:size(1) == 1 ) then inputs_1 = inputs:view(-1) else inputs_1 = inputs end _, index = torch.max(targets, 2) targets_1 = index:view(-1) errX = errX + trainNetwork(modelX, inputs_1, targets_1, criterion, sgdParams) print("here") end -- Decay the epsilon by multiplying by 0.999, not allowing it to go below a certain threshold. if (epsilon > epsilonMinimumValue) then --epsilon = epsilon * 0.9999 end end print(string.format("Epoch %d: [%s] [WinO Rate = %.2f WinX Rate = %.2f Draw Rate = %.2f] err = %.5f : err = %.5f : WinO count %d : WinX count %d : Draw Count %d", i, gameResult, winOCount / i * 100, winXCount / i * 100, drawCount / i * 100, errO, errX, winOCount, winXCount, drawCount)) print(nextState) if ( i > 0 and i % 3000 == 0 ) then torch.save(opt.savePrefix .. i .. '-O' .. '.t7', modelO) torch.save(opt.savePrefix .. i .. '-X' .. '.t7', modelX) end end
mit
AresTao/darkstar
scripts/globals/spells/diaga_ii.lua
18
1869
----------------------------------------- -- Spell: Diaga II -- Lowers an enemy's defense and gradually deals light elemental damage. ----------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) --calculate raw damage local basedmg = caster:getSkillLevel(ENFEEBLING_MAGIC_SKILL) / 4; local dmg = calculateMagicDamage(basedmg,3,caster,spell,target,ENFEEBLING_MAGIC_SKILL,MOD_INT,false); dmg = utils.clamp(dmg, 1, 40); --get resist multiplier (1x if no resist) local resist = applyResistance(caster,spell,target,caster:getStat(MOD_INT)-target:getStat(MOD_INT),ENFEEBLING_MAGIC_SKILL,1.0); --get the resisted damage dmg = dmg*resist; --add on bonuses (staff/day/weather/jas/mab/etc all go in this function) dmg = addBonuses(caster,spell,target,dmg); --add in target adjustment dmg = adjustForTarget(target,dmg,spell:getElement()); --add in final adjustments including the actual damage dealt local final = finalMagicAdjustments(caster,target,spell,dmg); -- Calculate duration. local duration = 120; -- Check for Bio. local bio = target:getStatusEffect(EFFECT_BIO); -- Do it! if (bio == nil or (DIA_OVERWRITE == 0 and bio:getPower() <= 2) or (DIA_OVERWRITE == 1 and bio:getPower() < 2)) then target:addStatusEffect(EFFECT_DIA,2,3,duration,FLAG_ERASABLE, 10); spell:setMsg(2); else spell:setMsg(75); end -- Try to kill same tier Bio if (BIO_OVERWRITE == 1 and bio ~= nil) then if (bio:getPower() <= 2) then target:delStatusEffect(EFFECT_BIO); end end return final; end;
gpl-3.0
AresTao/darkstar
scripts/globals/mobskills/Light_Blade.lua
21
1350
--------------------------------------------- -- Light Blade -- Description: Deals very high physical damage to a single player. -- Type: Ranged -- Damage decreases the farther away the target is from him. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 8; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_RANGED,MOBPARAM_SLASH,info.hitslanded); -- TODO: There's no MOBPARAM_RANGED, but MOBPARAM doesn't appear to do anything? -- Guessing ~40-100% damage based on range (20/50+). TODO: Find better data? -- ~400-450ish at tanking/melee range for a PLD with defender up and earth staff. -- ~750 for a DRG/BLU w/o Cocoon up at melee range. -- Wiki says 1k, videos were actually less, so trusting videos. local distance = mob:checkDistance(target) utils.clamp(distance, 0, 40) dmg = dmg * ((50 - distance) / 50); target:delHP(dmg); return dmg; end;
gpl-3.0
trishume/hammerspoon
extensions/fnutils/init.lua
1
7458
--- === hs.fnutils === --- --- Functional programming utility functions local fnutils = {} --- hs.fnutils.map(table, fn) -> table --- Function --- Execute a function across a table and collect the results --- --- Parameters: --- * table - A table containing some sort of data --- * fn - A function that accepts a single parameter. Whatever this function returns, will be collected and returned --- --- Returns: --- * A table containing the results of calling the function on every element in the table function fnutils.map(t, fn) local nt = {} for k, v in pairs(t) do table.insert(nt, fn(v) or nil) end return nt end --- hs.fnutils.each(table, fn) --- Function --- Execute a function across a table and discard the results --- --- Parameters: --- * table - A table containing some sort of data --- * fn - A function taht accepts a single parameter --- --- Returns: --- * None function fnutils.each(t, fn) for k, v in pairs(t) do fn(v) end end --- hs.fnutils.filter(table, fn) -> table --- Function --- Filter a table using a function --- --- Parameters: --- * table - A table containing some sort of data --- * fn - A function that accepts a single parameter and returns a boolean value, true if the parameter should be kept, false if it should be discarded --- --- Returns: --- * A table containing the elements of the table for which fn(element) returns true function fnutils.filter(t, fn) local nt = {} for k, v in pairs(t) do if fn(v) then table.insert(nt, v) end end return nt end --- hs.fnutils.copy(table) -> table --- Function --- Copy a table using `pairs()` --- --- Parameters: --- * table - A table containing some sort of data --- --- Returns: --- * A new table containing the same data as the input table function fnutils.copy(t) local nt = {} for k, v in pairs(t) do nt[k] = v end return nt end --- hs.fnutils.contains(table, element) -> bool --- Function --- Determine if a table contains a given object --- --- Parameters: --- * table - A table containing some sort of data --- * element - An object to search the table for --- --- Returns: --- * A boolean, true if the element could be found in the table, otherwise false function fnutils.contains(t, el) for k, v in pairs(t) do if v == el then return true end end return false end --- hs.fnutils.indexOf(table, element) -> number or nil --- Function --- Determine the location in a table of a given object --- --- Parameters: --- * table - A table containing some sort of data --- * element - An object to search the table for --- --- Returns: --- * A number containing the index of the element in the table, or nil if it could not be found function fnutils.indexOf(t, el) for k, v in pairs(t) do if v == el then return k end end return nil end --- hs.fnutils.concat(table1, table2) --- Function --- Join two tables together --- --- Parameters: --- * table1 - A table containing some sort of data --- * table2 - A table containing some sort of data --- --- Returns: --- * table1, with all of table2's elements added to the end of it --- --- Notes: --- * table2 cannot be a sparse table, see [http://www.luafaq.org/gotchas.html#T6.4](http://www.luafaq.org/gotchas.html#T6.4) function fnutils.concat(t1, t2) for i = 1, #t2 do t1[#t1 + 1] = t2[i] end return t1 end --- hs.fnutils.mapCat(table, fn) -> table --- Function --- Execute, across a table, a function that outputs tables, and concatenate all of those tables together --- --- Parameters: --- * table - A table containing some sort of data --- * fn - A function that takes a single parameter and returns a table --- --- Returns: --- * A table containing the concatenated results of calling fn(element) for every element in the supplied table function fnutils.mapCat(t, fn) local nt = {} for k, v in pairs(t) do fnutils.concat(nt, fn(v)) end return nt end --- hs.fnutils.reduce(table, fn) -> table --- Function --- Reduce a table to a single element, using a function --- --- Parameters: --- * table - A table containing some sort of data --- * fn - A function that takes two parameters, which will be elements of the supplied table. It should choose one of these elements and return it --- --- Returns: --- * The element of the supplied table that was chosen by the iterative reducer function --- --- Notes: --- * table cannot be a sparse table, see [http://www.luafaq.org/gotchas.html#T6.4](http://www.luafaq.org/gotchas.html#T6.4) --- * The first iteration of the reducer will call fn with the first and second elements of the table. The second iteration will call fn with the result of the first iteration, and the third element. This repeats until there is only one element left function fnutils.reduce(t, fn) local len = #t if len == 0 then return nil end if len == 1 then return t[1] end local result = t[1] for i = 2, #t do result = fn(result, t[i]) end return result end --- hs.fnutils.find(table, fn) -> element --- Function --- Execute a function across a table and return the first element where that function returns true --- --- Parameters: --- * table - A table containing some sort of data --- * fn - A function that takes one parameter and returns a boolean value --- --- Returns: --- * The element of the supplied table that first caused fn to return true function fnutils.find(t, fn) for _, v in pairs(t) do if fn(v) then return v end end return nil end --- hs.fnutils.sequence(...) -> fn --- Constructor --- Creates a function that will collect the result of a series of functions into a table --- --- Parameters: --- * ... - A number of functions, passed as different arguments. They should accept zero parameters, and return something --- --- Returns: --- * A function that, when called, will call all of the functions passed to this constructor. The output of these functions will be collected together and returned. function fnutils.sequence(...) local arg = table.pack(...) return function() local results = {} for _, fn in ipairs(arg) do table.insert(results, fn()) end return results end end --- hs.fnutils.partial(fn, ...) -> fn' --- Constructor --- Returns fn partially applied to arg (...) --- --- Parameters: --- * fn - A function --- * ... - A number of things --- --- Returns: --- * A function --- --- Notes: --- * The documentation for this function is currently insufficient. Please submit an improvement if you can! function fnutils.partial(fn, ...) local args = table.pack(...) return function(...) for idx, val in ipairs(table.pack(...)) do args[args.n + idx] = val end return fn(table.unpack(args)) end end --- hs.fnutils.cycle(table) -> fn() --- Constructor --- Creates a function that repeatedly iterates a table --- --- Parameters: --- * table - A table containing some sort of data --- --- Returns: --- * A function that, when called repeatedly, will return all of the elements of the supplied table, repeating indefinitely --- --- Notes: --- * table cannot be a sparse table, see [http://www.luafaq.org/gotchas.html#T6.4](http://www.luafaq.org/gotchas.html#T6.4) --- * An example usage: --- ```lua --- f = cycle({4, 5, 6}) --- {f(), f(), f(), f(), f(), f(), f()} == {4, 5, 6, 4, 5, 6, 4} --- ``` function fnutils.cycle(t) local i = 1 return function() local x = t[i] i = i % #t + 1 return x end end return fnutils
mit
kidaa/luvit
tests/test-tls-junk-closes-server.lua
11
1323
--[[ Copyright 2012-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. ]]-- require('tap')(function (test) local fixture = require('./fixture-tls') local tls = require('tls') local net = require('net') local options = { key = fixture.loadPEM('agent2-key'), cert = fixture.loadPEM('agent2-cert') } test("tls server side ssl error when accepting", function() local server server = tls.createServer(options, function(s,err) assert(err=='ssl') s:destroy() server:close() end) server:listen(fixture.commonPort, function() local c c = net.createConnection({port = fixture.commonPort, host = '127.0.0.1'}) c:on('connect', function() c:write('blah\nblah\nblah\n') c:destroy() end) end) end) end)
apache-2.0
AresTao/darkstar
scripts/zones/Port_Windurst/npcs/Odilia.lua
38
1029
----------------------------------- -- Area: Port Windurst -- NPC: Odilia -- Type: Standard NPC -- @zone: 240 -- @pos 78.801 -6 118.653 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0121); 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
DeinFreund/Zero-K
units/vehaa.lua
1
4139
unitDef = { unitname = [[vehaa]], name = [[Crasher]], description = [[Fast Anti-Air Rover]], acceleration = 0.05952, brakeRate = 0.14875, buildCostMetal = 220, builder = false, buildPic = [[vehaa.png]], canGuard = true, canMove = true, canPatrol = true, category = [[LAND]], collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[18 20 40]], collisionVolumeType = [[box]], corpse = [[DEAD]], customParams = { modelradius = [[9]], }, explodeAs = [[BIG_UNITEX]], footprintX = 3, footprintZ = 3, iconType = [[vehicleaa]], idleAutoHeal = 5, idleTime = 1800, leaveTracks = true, maneuverleashlength = [[30]], maxDamage = 900, maxSlope = 18, maxVelocity = 3.7, maxWaterDepth = 22, minCloakDistance = 75, movementClass = [[TANK3]], moveState = 0, noAutoFire = false, noChaseCategory = [[TERRAFORM LAND SINK TURRET SHIP SATELLITE SWIM FLOAT SUB HOVER]], objectName = [[vehaa.s3o]], script = [[vehaa.lua]], selfDestructAs = [[BIG_UNITEX]], sfxtypes = { explosiongenerators = { [[custom:STORMMUZZLE]], [[custom:STORMBACK]], }, }, sightDistance = 660, trackOffset = 6, trackStrength = 5, trackStretch = 1, trackType = [[StdTank]], trackWidth = 32, turninplace = 0, turnRate = 653, upright = false, workerTime = 0, weapons = { { def = [[MISSILE]], onlyTargetCategory = [[FIXEDWING GUNSHIP]], }, }, weaponDefs = { MISSILE = { name = [[Heavy Missile]], areaOfEffect = 32, canattackground = false, cegTag = [[missiletrailblue]], craterBoost = 0, craterMult = 0, cylinderTargeting = 1, customParams = { isaa = [[1]], light_color = [[0.5 0.6 0.6]], }, damage = { default = 29.01, planes = 290.1, subs = 16, }, explosionGenerator = [[custom:FLASH2]], fixedlauncher = true, fireStarter = 70, flightTime = 3, impactOnly = true, impulseBoost = 0, impulseFactor = 0.4, interceptedByShieldType = 2, model = [[wep_m_phoenix.s3o]], noSelfDamage = true, range = 730, reloadtime = 4, smokeTrail = true, soundHit = [[weapon/missile/sabot_hit]], soundStart = [[weapon/missile/missile_fire]], startVelocity = 300, texture2 = [[AAsmoketrail]], tolerance = 9000, tracks = true, turnRate = 63000, turret = true, weaponAcceleration = 250, weaponType = [[MissileLauncher]], weaponVelocity = 700, }, }, featureDefs = { DEAD = { blocking = true, collisionVolumeOffsets = [[0 0 0]], collisionVolumeScales = [[32 40 52]], collisionVolumeType = [[box]], featureDead = [[HEAP]], footprintX = 2, footprintZ = 2, object = [[vehaa_dead.s3o]], }, HEAP = { blocking = false, footprintX = 2, footprintZ = 2, object = [[debris2x2a.s3o]], }, }, } return lowerkeys({ vehaa = unitDef })
gpl-2.0
AresTao/darkstar
scripts/zones/Altar_Room/npcs/Hooknox.lua
38
1033
----------------------------------- -- Area: Altar Room -- NPC: Hooknox -- Type: Standard NPC -- @zone: 152 -- @pos -265.248 11.693 -102.547 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Altar_Room/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x002e); 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
AresTao/darkstar
scripts/globals/abilities/sic.lua
28
1058
----------------------------------- -- Ability: Sic -- Commands the charmed Pet to make a random special attack. -- Obtained: Beastmaster Level 25 -- Recast Time: 2 minutes -- Duration: N/A ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getPet() == nil) then return MSGBASIC_REQUIRES_A_PET,0; else if (player:getPet():getHP() == 0) then return MSGBASIC_UNABLE_TO_USE_JA,0; elseif (player:getPet():getTarget() == nil) then return MSGBASIC_PET_CANNOT_DO_ACTION,0; elseif (not player:getPet():hasTPMoves()) then return MSGBASIC_UNABLE_TO_USE_JA,0; else return 0,0; end end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) end;
gpl-3.0
wizardbottttt/X
plugins/twitter_send.lua
627
1555
do local OAuth = require "OAuth" local consumer_key = "" local consumer_secret = "" local access_token = "" local access_token_secret = "" local client = OAuth.new(consumer_key, consumer_secret, { RequestToken = "https://api.twitter.com/oauth/request_token", AuthorizeUser = {"https://api.twitter.com/oauth/authorize", method = "GET"}, AccessToken = "https://api.twitter.com/oauth/access_token" }, { OAuthToken = access_token, OAuthTokenSecret = access_token_secret }) function run(msg, matches) if consumer_key:isempty() then return "Twitter Consumer Key is empty, write it in plugins/twitter_send.lua" end if consumer_secret:isempty() then return "Twitter Consumer Secret is empty, write it in plugins/twitter_send.lua" end if access_token:isempty() then return "Twitter Access Token is empty, write it in plugins/twitter_send.lua" end if access_token_secret:isempty() then return "Twitter Access Token Secret is empty, write it in plugins/twitter_send.lua" end if not is_sudo(msg) then return "You aren't allowed to send tweets" end local response_code, response_headers, response_status_line, response_body = client:PerformRequest("POST", "https://api.twitter.com/1.1/statuses/update.json", { status = matches[1] }) if response_code ~= 200 then return "Error: "..response_code end return "Tweet sent" end return { description = "Sends a tweet", usage = "!tw [text]: Sends the Tweet with the configured account.", patterns = {"^!tw (.+)"}, run = run } end
gpl-2.0
AresTao/darkstar
scripts/zones/Mhaura/npcs/Nomad_Moogle.lua
34
1116
----------------------------------- -- Area: Mhaura -- NPC: Nomad Moogle ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,NOMAD_MOOGLE_DIALOG); player:sendMenu(1); end; ----------------------------------- -- onEventUpdate Action ----------------------------------- function onEventUpdate(player,csid,option) --print("onEventUpdate"); --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --print("onEventFinish"); --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
roboxt/fik
plugins/ActiveUser.lua
11
11812
local function checktodaygr(cb_extra, success, result) local hash = '' local thash='' for k,user in pairs(result.members) do thash = 'today:'..user.peer_id if redis:get(thash) then if redis:get(thash) < os.date("%x",os.time() + 16200) then hash = 'utmsgst:'..user.peer_id..':'..cb_extra redis:set(hash,0) hash = 'utmsgph:'..user.peer_id..':'..cb_extra redis:set(hash,0) hash = 'utmsgtex:'..user.peer_id..':'..cb_extra redis:set(hash,0) hash = 'utmsgoth:'..user.peer_id..':'..cb_extra redis:set(hash,0) redis:set(thash,os.date("%x",os.time() + 16200)) end else redis:set(thash,os.date("%x",os.time() + 16200)) end end end local function checktodaych(cb_extra, success, result) local hash = '' local thash='' for k,user in pairs(result) do thash = 'today:'..user.peer_id if redis:get(thash) then if redis:get(thash) < os.date("%x",os.time() + 16200) then hash = 'utmsgst:'..user.peer_id..':'..cb_extra redis:set(hash,0) hash = 'utmsgph:'..user.peer_id..':'..cb_extra redis:set(hash,0) hash = 'utmsgtex:'..user.peer_id..':'..cb_extra redis:set(hash,0) hash = 'utmsgoth:'..user.peer_id..':'..cb_extra redis:set(hash,0) redis:set(thash,os.date("%x",os.time() + 16200)) end else redis:set(thash,os.date("%x",os.time() + 16200)) end end end local function cron() for v,chat in pairs(_chats.chats) do channel_get_users('channel#id'..chat[1], checktodaych, chat[1]) chat_info('chat#id'..chat[1], checktodaygr, chat[1]) end end local function pre_process(msg) if not msg.service then if msg.media then if msg.media.caption == 'sticker.webp' then local hash = 'utmsgst:'..msg.from.id..':'..msg.to.id redis:incr(hash) elseif msg.media.type == 'photo' then local hash = 'utmsgph:'..msg.from.id..':'..msg.to.id redis:incr(hash) end else if msg.text then local hash = 'utmsgtex:'..msg.from.id..':'..msg.to.id redis:incr(hash) else local hash = 'utmsgoth:'..msg.from.id..':'..msg.to.id redis:incr(hash) end end end return msg end local function getactivegr(cb_extra, success, result) local maxst = {} local maxph = {} local maxtex = {} local maxoth = {} local maxname = {} local maxuser = {} local maxid = {} local maxstat = {} maxstat[1] = 0 maxstat[2] = 0 maxstat[3] = 0 maxname[1] = '' maxname[2] = '' maxname[3] = '' maxuser[1] = '' maxuser[2] = '' maxuser[3] = '' for k,user in pairs(result.members) do local shash = 'utmsgst:'..user.peer_id..':'..cb_extra local phash = 'utmsgph:'..user.peer_id..':'..cb_extra local thash = 'utmsgtex:'..user.peer_id..':'..cb_extra local ohash = 'utmsgoth:'..user.peer_id..':'..cb_extra if not redis:get(shash) then redis:set(shash,0) end if not redis:get(phash) then redis:set(phash,0) end if not redis:get(thash) then redis:set(thash,0) end if not redis:get(ohash) then redis:set(ohash,0) end if tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[1] then maxname[3] = maxname[2] maxuser[3] = maxuser[2] maxstat[3] = maxstat[2] maxid[3] = maxid[2] maxname[2] = maxname[1] maxuser[2] = maxuser[1] maxstat[2] = maxstat[1] maxid[2] = maxid[1] maxname[1] = user.print_name maxuser[1] = user.username maxid[1] = user.peer_id maxstat[1] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[2] then maxname[3] = maxname[2] maxuser[3] = maxuser[2] maxstat[3] = maxstat[2] maxid[3] = maxid[2] maxname[2] = user.print_name maxuser[2] = user.username maxid[2] = user.peer_id maxstat[2] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[3] then maxname[3] = user.print_name maxuser[3] = user.username maxid[3] = user.peer_id maxstat[3] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) end end maxst[1] = redis:get('utmsgst:'..maxid[1]..':'..cb_extra) maxph[1] = redis:get('utmsgph:'..maxid[1]..':'..cb_extra) maxtex[1] = redis:get('utmsgtex:'..maxid[1]..':'..cb_extra) maxoth[1] = redis:get('utmsgoth:'..maxid[1]..':'..cb_extra) if maxid[2] then maxst[2] = redis:get('utmsgst:'..maxid[2]..':'..cb_extra) maxph[2] = redis:get('utmsgph:'..maxid[2]..':'..cb_extra) maxtex[2] = redis:get('utmsgtex:'..maxid[2]..':'..cb_extra) maxoth[2] = redis:get('utmsgoth:'..maxid[2]..':'..cb_extra) end if maxid[3] then maxst[3] = redis:get('utmsgst:'..maxid[3]..':'..cb_extra) maxph[3] = redis:get('utmsgph:'..maxid[3]..':'..cb_extra) maxtex[3] = redis:get('utmsgtex:'..maxid[3]..':'..cb_extra) maxoth[3] = redis:get('utmsgoth:'..maxid[3]..':'..cb_extra) end if not maxuser[1] or maxuser[1] == '' then maxuser[1] = 'ندارد' else maxuser[1] = '@'..maxuser[1] end if not maxuser[2] or maxuser[2] == '' then maxuser[2] = 'ندارد' else maxuser[2] = '@'..maxuser[2] end if not maxuser[3] or maxuser[3] == '' then maxuser[3] = 'ندارد' else maxuser[3] = '@'..maxuser[3] end local text = '♨️فعالان امروز گروه\n1⃣ '..maxname[1]..'〖'..maxuser[1]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[1] + maxph[1] + maxst[1] + maxoth[1]..'\n\n👾استیکر: '..maxst[1]..'\n\n📷تصویر: '..maxph[1]..'\n\n📃 متن: '..maxtex[1]..'\n\n📦 سایر: '..maxoth[1] if maxid[2] then if not maxid[3] then text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2] else text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2]..'\n\n 3⃣ '..maxname[3]..' 〖'..maxuser[3]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[3] + maxph[3] + maxst[3] + maxoth[3]..'\n\n👾استیکر: '..maxst[3]..'\n\n📷تصویر: '..maxph[3]..'\n\n📃 متن: '..maxtex[3]..'\n\n📦 سایر: '..maxoth[3] end end send_msg('chat#id'..cb_extra, text, ok_cb, true) end local function getactivech(cb_extra, success, result) local maxst = {} local maxph = {} local maxtex = {} local maxoth = {} local maxname = {} local maxuser = {} local maxid = {} local maxstat = {} maxstat[1] = 0 maxstat[2] = 0 maxstat[3] = 0 maxname[1] = '' maxname[2] = '' maxname[3] = '' maxuser[1] = '' maxuser[2] = '' maxuser[3] = '' for k,user in pairs(result) do local shash = 'utmsgst:'..user.peer_id..':'..cb_extra local phash = 'utmsgph:'..user.peer_id..':'..cb_extra local thash = 'utmsgtex:'..user.peer_id..':'..cb_extra local ohash = 'utmsgoth:'..user.peer_id..':'..cb_extra if not redis:get(shash) then redis:set(shash,0) end if not redis:get(phash) then redis:set(phash,0) end if not redis:get(thash) then redis:set(thash,0) end if not redis:get(ohash) then redis:set(ohash,0) end if tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[1] then maxname[3] = maxname[2] maxuser[3] = maxuser[2] maxstat[3] = maxstat[2] maxid[3] = maxid[2] maxname[2] = maxname[1] maxuser[2] = maxuser[1] maxstat[2] = maxstat[1] maxid[2] = maxid[1] maxname[1] = user.print_name maxuser[1] = user.username maxid[1] = user.peer_id maxstat[1] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[2] then maxname[3] = maxname[2] maxuser[3] = maxuser[2] maxstat[3] = maxstat[2] maxid[3] = maxid[2] maxname[2] = user.print_name maxuser[2] = user.username maxid[2] = user.peer_id maxstat[2] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) elseif tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) > maxstat[3] then maxname[3] = user.print_name maxuser[3] = user.username maxid[3] = user.peer_id maxstat[3] = tonumber(redis:get(shash)) + tonumber(redis:get(phash)) + tonumber(redis:get(thash)) + tonumber(redis:get(ohash)) end end maxst[1] = redis:get('utmsgst:'..maxid[1]..':'..cb_extra) maxph[1] = redis:get('utmsgph:'..maxid[1]..':'..cb_extra) maxtex[1] = redis:get('utmsgtex:'..maxid[1]..':'..cb_extra) maxoth[1] = redis:get('utmsgoth:'..maxid[1]..':'..cb_extra) if maxid[2] then maxst[2] = redis:get('utmsgst:'..maxid[2]..':'..cb_extra) maxph[2] = redis:get('utmsgph:'..maxid[2]..':'..cb_extra) maxtex[2] = redis:get('utmsgtex:'..maxid[2]..':'..cb_extra) maxoth[2] = redis:get('utmsgoth:'..maxid[2]..':'..cb_extra) end if maxid[3] then maxst[3] = redis:get('utmsgst:'..maxid[3]..':'..cb_extra) maxph[3] = redis:get('utmsgph:'..maxid[3]..':'..cb_extra) maxtex[3] = redis:get('utmsgtex:'..maxid[3]..':'..cb_extra) maxoth[3] = redis:get('utmsgoth:'..maxid[3]..':'..cb_extra) end if not maxuser[1] or maxuser[1] == '' then maxuser[1] = 'ندارد' else maxuser[1] = '@'..maxuser[1] end if not maxuser[2] or maxuser[2] == '' then maxuser[2] = 'ندارد' else maxuser[2] = '@'..maxuser[2] end if not maxuser[3] or maxuser[3] == '' then maxuser[3] = 'ندارد' else maxuser[3] = '@'..maxuser[3] end local text = '♨️فعالان امروز گروه\n1⃣ '..maxname[1]..'〖'..maxuser[1]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[1] + maxph[1] + maxst[1] + maxoth[1]..'\n\n👾استیکر: '..maxst[1]..'\n\n📷تصویر: '..maxph[1]..'\n\n📃 متن: '..maxtex[1]..'\n\n📦 سایر: '..maxoth[1] if maxid[2] then if not maxid[3] then text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2] else text = text..'\n\n 2⃣ '..maxname[2]..' 〖'..maxuser[2]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[2] + maxph[2] + maxst[2] + maxoth[2]..'\n\n👾استیکر: '..maxst[2]..'\n\n📷تصویر: '..maxph[2]..'\n\n📃 متن: '..maxtex[2]..'\n\n📦 سایر: '..maxoth[2]..'\n\n 3⃣ '..maxname[3]..' 〖'..maxuser[3]..'〗\n\n📨تعداد پیام های ارسالی: '..maxtex[3] + maxph[3] + maxst[3] + maxoth[3]..'\n\n👾استیکر: '..maxst[3]..'\n\n📷تصویر: '..maxph[3]..'\n\n📃 متن: '..maxtex[3]..'\n\n📦 سایر: '..maxoth[3] end end send_msg('channel#id'..cb_extra, text, ok_cb, true) end local function run(msg,matches) if msg.to.type == 'channel' then channel_get_users('channel#id'..msg.to.id, getactivech, msg.to.id) elseif msg.to.type == 'chat' then chat_info('chat#id'..msg.to.id, getactivegr, msg.to.id) end end return { patterns = { "^[!/#]active$", "^active$", }, pre_process = pre_process, cron = cron, run = run }
gpl-2.0
AresTao/darkstar
scripts/zones/Windurst_Walls/npcs/Zayhi-Bauhi.lua
17
5268
----------------------------------- -- Area: Windurst Walls -- Location: X:-91 Y:-9 Z:109 -- NPC: Zayhi-Bauhi -- Working 100% -- Starts and Finishes Quest: To Bee or Not to Bee? ----------------------------------- package.loaded["scripts/zones/Windurst_Walls/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Walls/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(WINDURST,TO_BEE_OR_NOT_TO_BEE) == QUEST_ACCEPTED) then if (trade:hasItemQty(4370,1) and trade:getItemCount() == 1) then local ToBeeOrNotStatus = player:getVar("ToBeeOrNot_var"); if (ToBeeOrNotStatus == 10) then player:startEvent(0x0045); -- After Honey#1: Clearing throat elseif (ToBeeOrNotStatus == 1) then player:startEvent(0x0046); -- After Honey#2: Tries to speak again... coughs elseif (ToBeeOrNotStatus == 2) then player:startEvent(0x0049); -- After Honey#3: Tries to speak again... coughs..asked for more Honey elseif (ToBeeOrNotStatus == 3) then player:startEvent(0x004A); -- After Honey#4: Feels like its getting a lot better but there is still iritaion elseif (ToBeeOrNotStatus == 4) then player:startEvent(0x004B); -- After Honey#5: ToBee quest Finish (tooth hurts from all the Honey end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local ToBee = player:getQuestStatus(WINDURST,TO_BEE_OR_NOT_TO_BEE); local PostmanKOsTwice = player:getQuestStatus(WINDURST,THE_POSTMAN_ALWAYS_KO_S_TWICE); local ToBeeOrNotStatus = player:getVar("ToBeeOrNot_var"); if ((player:getFameLevel(WINDURST) >= 2 and PostmanKOsTwice == QUEST_COMPLETED and ToBee == QUEST_AVAILABLE) or (ToBee == QUEST_ACCEPTED and ToBeeOrNotStatus == 10)) then player:startEvent(0x0040); -- Just Before Quest Start "Too Bee or Not Too Be" (Speech given with lots of coughing) elseif (ToBee == QUEST_ACCEPTED) then if (ToBeeOrNotStatus == 1) then player:startEvent(0x0045); -- After Honey#1: Clearing throat elseif (ToBeeOrNotStatus == 2) then player:startEvent(0x0046); -- After Honey#2: Tries to speak again... coughs elseif (ToBeeOrNotStatus == 3) then player:startEvent(0x0049); -- After Honey#3: Tries to speak again... coughs..asked for more Honey elseif (ToBeeOrNotStatus == 4) then player:startEvent(0x004A); -- After Honey#4: Feels like its getting a lot better but there is still iritaion end elseif (ToBee == QUEST_COMPLETED and player:needToZone()) then player:startEvent(0x004E); -- ToBee After Quest Finish but before zone (tooth still hurts) else player:startEvent(0x012B); -- Normal speech end end; -- Event ID List for NPC -- player:startEvent(0x012B); -- Normal speach -- player:startEvent(0x003D); -- Normal speach -- player:startEvent(0x0040); -- Start quest "Too Bee or Not Too Be" (Speech given with lots of coughing) -- player:startEvent(0x0045); -- After Honey#1: Clearing throat -- player:startEvent(0x0046); -- After Honey#2: Tries to speak again... coughs -- player:startEvent(0x0049); -- After Honey#3: Tries to speak again... coughs..asked for more Honey -- player:startEvent(0x004A); -- After Honey#4: Feels like its getting a lot better but there is still iritaion -- player:startEvent(0x004B); -- After Honey#5: ToBee quest Finish (tooth hurts from all the Honey) -- player:startEvent(0x004E); -- ToBee After Quest Finish but before zone (tooth still hurts) ----------------------------------- -- 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 == 0x0040) then player:setVar("ToBeeOrNot_var",10); elseif (csid == 0x0045) then -- After Honey#1: Clearing throat player:tradeComplete(); player:setVar("ToBeeOrNot_var",1); elseif (csid == 0x0046) then -- After Honey#2: Tries to speak again... coughs player:tradeComplete(); player:setVar("ToBeeOrNot_var",2); elseif (csid == 0x0049) then -- After Honey#3: Tries to speak again... coughs..asked for more Honey player:tradeComplete(); player:setVar("ToBeeOrNot_var",3); elseif (csid == 0x004A) then -- After Honey#4: Feels like its getting a lot better but there is still iritaion player:tradeComplete(); player:setVar("ToBeeOrNot_var",4); elseif (csid == 0x004B) then -- After Honey#5: ToBee quest Finish (tooth hurts from all the Honey) player:tradeComplete(); player:setVar("ToBeeOrNot_var",5); player:addFame(WINDURST,WIN_FAME*30); player:completeQuest(WINDURST,TO_BEE_OR_NOT_TO_BEE); player:needToZone(true); end end;
gpl-3.0
AresTao/darkstar
scripts/globals/items/imperial_omelette.lua
35
2869
----------------------------------------- -- ID: 4331 -- Item: imperial_omelette -- Food Effect: 240Min, All Races ----------------------------------------- -- Non Elvaan Stats -- Strength 5 -- Dexterity 2 -- Intelligence -3 -- Mind 4 -- Attack % 22 -- Attack Cap 70 -- Ranged ATT % 22 -- Ranged ATT Cap 70 ----------------------------------------- -- Elvaan Stats -- Strength 6 -- Health 20 -- Elvaan Stats -- Strength 6 -- Health 20 -- Magic 20 -- Intelligence -2 -- Mind 5 -- Charisma 4 -- Attack % 22 -- Attack Cap 85 -- Ranged ATT % 22 -- Ranged ATT Cap 85 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,4331); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) if (target:getRace() ~= 4) then target:addMod(MOD_STR, 5); target:addMod(MOD_DEX, 2); target:addMod(MOD_INT, -3); target:addMod(MOD_MND, 4); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 70); target:addMod(MOD_FOOD_RATTP, 22); target:addMod(MOD_FOOD_RATT_CAP, 70); else target:addMod(MOD_HP, 20); target:addMod(MOD_MP, 20); target:addMod(MOD_STR, 6); target:addMod(MOD_DEX, 2); target:addMod(MOD_INT, -2); target:addMod(MOD_MND, 5); target:addMod(MOD_CHR, 4); target:addMod(MOD_FOOD_ATTP, 22); target:addMod(MOD_FOOD_ATT_CAP, 85); target:addMod(MOD_FOOD_RATTP, 22); target:addMod(MOD_FOOD_RATT_CAP, 85); end end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) if (target:getRace() ~= 4) then target:delMod(MOD_STR, 5); target:delMod(MOD_DEX, 2); target:delMod(MOD_INT, -3); target:delMod(MOD_MND, 4); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 70); target:delMod(MOD_FOOD_RATTP, 22); target:delMod(MOD_FOOD_RATT_CAP, 70); else target:delMod(MOD_HP, 20); target:delMod(MOD_MP, 20); target:delMod(MOD_STR, 6); target:delMod(MOD_DEX, 2); target:delMod(MOD_INT, -2); target:delMod(MOD_MND, 5); target:delMod(MOD_CHR, 4); target:delMod(MOD_FOOD_ATTP, 22); target:delMod(MOD_FOOD_ATT_CAP, 85); target:delMod(MOD_FOOD_RATTP, 22); target:delMod(MOD_FOOD_RATT_CAP, 85); end end;
gpl-3.0
letoram/arcan-legacy
resources/scripts/textfader.lua
1
2357
-- take one step forward, counting escape sequences and format values. local function utf8forward(src, ofs, steps) while (steps > 0) do if (ofs <= string.len(src)) then repeat ofs = ofs + 1; until (ofs > string.len(src) or utf8kind( string.byte(src, ofs) ) < 2); end steps = steps - 1; end return ofs; end local function formatskip(str, ofs) repeat local ch = string.sub(str, ofs, ofs); local ofs2 = utf8forward(str, ofs, 1); local ch2 = string.sub( str, ofs2, ofs2); if (ch ~= "\\") then break; end -- proper escaping for backslasht if (ch2 == "\\") then break; end -- skip #RRGGBB if (ch2 == "#") then ofs = utf8forward(str, ofs, 8); break; end -- font, scan for , then first non-digit if (ch2 == "f") then ofs = utf8forward(str, ofs, 3); while ( string.sub(str, ofs, ofs) ~= "," ) do ofs = utf8forward(str, ofs, 1); end ofs = utf8forward(str, ofs, 1); while ( tonumber( string.sub(str, ofs, ofs) ) ~= nil ) do ofs = utf8forward(str, ofs, 1); end elseif (ch2 == "!") then ofs = utf8forward(str, ofs, 2); else ofs = utf8forward(str, ofs, 1); end until true; return ofs; end -- Increment one step, skips past escaped portions and handles UTF8 local function textfader_step(self) if (self.cpos == string.len(self.message) and self.clife >= self.mlife) then self.alive = false; end if (self.alive == false) then return; end self.clife = self.clife + 1; -- time to step if (self.clife >= self.mlife ) then -- now we have formatting strings to consider as well self.last = self.cpos; self.cpos = formatskip(self.message, self.cpos) if (self.cpos == self.last) then self.cpos = formatskip(self.message, utf8forward(self.message, self.cpos, 1) ); end self.clife = 0; self.smessage = string.sub(self.message, 1, self.cpos); if (self.rmsg ~= BADID) then delete_image(self.rmsg); end self.rmsg = render_text(self.smessage); move_image(self.rmsg, self.x, self.y, NOW); blend_image(self.rmsg, self.opa, NOW); end end function textfader_create( rawtext, xpos, ypos, opacity, speed ) fdrtbl = { message = rawtext, x = xpos, y = ypos, opa = opacity, mlife = speed, clife = speed, alive = true, rmsg = BADID }; assert(0 < speed); fdrtbl.step = textfader_step; fdrtbl.cpos = 1; return fdrtbl; end
unlicense
AresTao/darkstar
scripts/zones/Temenos/mobs/Beli.lua
16
1188
----------------------------------- -- Area: Temenos N T -- NPC: Beli ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) GetMobByID(16928781):updateEnmity(target); GetMobByID(16928782):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) if (IsMobDead(16928781)==true and IsMobDead(16928782)==true and IsMobDead(16928783)==true ) then GetNPCByID(16928768+19):setPos(200,-82,495); GetNPCByID(16928768+19):setStatus(STATUS_NORMAL); GetNPCByID(16928768+153):setPos(206,-82,495); GetNPCByID(16928768+153):setStatus(STATUS_NORMAL); GetNPCByID(16928768+210):setPos(196,-82,495); GetNPCByID(16928768+210):setStatus(STATUS_NORMAL); end end;
gpl-3.0
ld-test/prosody
tools/migration/migrator/mtools.lua
6
1037
local print = print; local t_insert = table.insert; local t_sort = table.sort; module "mtools" function sorted(params) local reader = params.reader; -- iterator to get items from local sorter = params.sorter; -- sorting function local filter = params.filter; -- filter function local cache = {}; for item in reader do if filter then item = filter(item); end if item then t_insert(cache, item); end end if sorter then t_sort(cache, sorter); end local i = 0; return function() i = i + 1; return cache[i]; end; end function merged(reader, merger) local item1 = reader(); local merged = { item1 }; return function() while true do if not item1 then return nil; end local item2 = reader(); if not item2 then item1 = nil; return merged; end if merger(item1, item2) then --print("merged") item1 = item2; t_insert(merged, item1); else --print("unmerged", merged) item1 = item2; local tmp = merged; merged = { item1 }; return tmp; end end end; end return _M;
mit
AresTao/darkstar
scripts/zones/AlTaieu/mobs/Jailer_of_Love.lua
23
5580
----------------------------------- -- Area: Al'Taieu -- NM: Jailer of Love ----------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob, target) mob:hideName(false); mob:untargetable(false); mob:AnimationSub(2); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob, target) -- Only 9 Qn'xzomit and 9 Qn'hpemde can be summoned. Ru'phuabo (Sharks) are unlimited. local XZOMITS = mob:getLocalVar("JoL_Qn_xzomit_Killed"); local HPEMDES = mob:getLocalVar("JoL_Qn_hpemde_Killed"); -- Increment these by 1 each time they are slain, in that mobs onMobDeath() script. if (mob:getLocalVar("JoL_Regen_Reduction") == 0) then if (mob:getLocalVar("JoL_Qn_xzomit_Killed") == 9 and mob:getLocalVar("JoL_Qn_hpemde_Killed") == 9) then mob:setLocalVar("JoL_Regen_Reduction", 1); mob:addMod(MOD_REGEN, -260) end end local lastPop = mob:getLocalVar("pop_pets"); if (os.time() - lastPop > 150) then local SPAWNS = mob:getLocalVar("SPAWNS"); local phuabo1 = GetMobAction(16912849); local phuabo2 = GetMobAction(16912852); local phuabo3 = GetMobAction(16912855); if (SPAWNS == 0) then -- Spawns first 3 xzomit SpawnMob(16912858, 300):updateEnmity(target); SpawnMob(16912859, 300):updateEnmity(target); SpawnMob(16912860, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); mob:setLocalVar("SPAWNS", 1); elseif (SPAWNS == 1) then -- spawns first 3 hpemde SpawnMob(16912867, 300):updateEnmity(target); SpawnMob(16912868, 300):updateEnmity(target); SpawnMob(16912869, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); mob:setLocalVar("SPAWNS", 2); elseif (SPAWNS == 2) then -- spawns first 3 phuabo SpawnMob(16912849, 300):updateEnmity(target); SpawnMob(16912850, 300):updateEnmity(target); SpawnMob(16912851, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); mob:setLocalVar("SPAWNS", 3); elseif (SPAWNS == 3) then -- Spawns second 3 xzomit SpawnMob(16912861, 300):updateEnmity(target); SpawnMob(16912862, 300):updateEnmity(target); SpawnMob(16912863, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); mob:setLocalVar("SPAWNS", 4); elseif (SPAWNS == 4) then -- spawns second 3 hpemde SpawnMob(16912870, 300):updateEnmity(target); SpawnMob(16912871, 300):updateEnmity(target); SpawnMob(16912872, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); mob:setLocalVar("SPAWNS", 5); elseif (SPAWNS == 5) then -- spawns second 3 phuabo SpawnMob(16912852, 300):updateEnmity(target); SpawnMob(16912853, 300):updateEnmity(target); SpawnMob(16912854, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); mob:setLocalVar("SPAWNS", 6); elseif (SPAWNS == 6) then -- Spawns last 3 xzomit SpawnMob(16912864, 300):updateEnmity(target); SpawnMob(16912865, 300):updateEnmity(target); SpawnMob(16912866, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); mob:setLocalVar("SPAWNS", 7); elseif (SPAWNS == 7) then -- spawns last 3 hpemde SpawnMob(16912873, 300):updateEnmity(target); SpawnMob(16912874, 300):updateEnmity(target); SpawnMob(16912875, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); mob:setLocalVar("SPAWNS", 8); elseif (SPAWNS >= 8) then -- switch to ONLY popping phuabo (still up to 3 at a time) if (phuabo1 == ACTION_NONE or phuabo1 == ACTION_SPAWN) then SpawnMob(16912849, 300):updateEnmity(target); SpawnMob(16912850, 300):updateEnmity(target); SpawnMob(16912851, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); elseif (phuabo2 == ACTION_NONE or phuabo2 == ACTION_SPAWN) then SpawnMob(16912852, 300):updateEnmity(target); SpawnMob(16912853, 300):updateEnmity(target); SpawnMob(16912854, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); elseif (phuabo3 == ACTION_NONE or phuabo3 == ACTION_SPAWN) then SpawnMob(16912855, 300):updateEnmity(target); SpawnMob(16912856, 300):updateEnmity(target); SpawnMob(16912857, 300):updateEnmity(target); mob:setLocalVar("pop_pets", os.time()); end end end end; ----------------------------------- -- onMobDespawn ----------------------------------- function onMobDespawn(mob) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) local AV_CHANCE = 25; if (AV_CHANCE > math.random(0,99)) then SpawnMob(16912876, 180); end end;
gpl-3.0
roboxt/fik
plugins/All.lua
14
4453
do local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_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 table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'Chat stats:\n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end local function get_group_type(target) local data = load_data(_config.moderation.data) local group_type = data[tostring(target)]['group_type'] if not group_type or group_type == nil then return 'No group type available.\nUse /type in the group to set type.' end return group_type end local function get_description(target) local data = load_data(_config.moderation.data) local data_cat = 'description' if not data[tostring(target)][data_cat] then return 'No description available.' end local about = data[tostring(target)][data_cat] return about end local function get_rules(target) local data = load_data(_config.moderation.data) local data_cat = 'rules' if not data[tostring(target)][data_cat] then return 'No rules available.' end local rules = data[tostring(target)][data_cat] return rules end local function modlist(target) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then return 'Group is not added or is Realm.' end if next(data[tostring(target)]['moderators']) == nil then return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators :\n' for k,v in pairs(data[tostring(target)]['moderators']) do message = message ..i..' - @'..v..' [' ..k.. '] \n' i = i + 1 end return message end local function get_link(target) local data = load_data(_config.moderation.data) local group_link = data[tostring(target)]['settings']['set_link'] if not group_link or group_link == nil then return "No link" end return "Group link:\n"..group_link end local function all(msg,target,receiver) local data = load_data(_config.moderation.data) if not data[tostring(target)] then return end local text = "All the things I know about this group\n\n" local group_type = get_group_type(target) text = text.."Group Type: \n"..group_type if group_type == "Group" or group_type == "Realm" then local settings = show_group_settingsmod(msg,target) text = text.."\n\n"..settings elseif group_type == "SuperGroup" then local settings = show_supergroup_settingsmod(msg,target) text = text..'\n\n'..settings end local rules = get_rules(target) text = text.."\n\nRules: \n"..rules local description = get_description(target) text = text.."\n\nAbout: \n"..description local modlist = modlist(target) text = text.."\n\nMods: \n"..modlist local link = get_link(target) text = text.."\n\nLink: \n"..link local stats = chat_stats(target) text = text.."\n\n"..stats local mutes_list = mutes_list(target) text = text.."\n\n"..mutes_list local muted_user_list = muted_user_list(target) text = text.."\n\n"..muted_user_list local ban_list = ban_list(target) text = text.."\n\n"..ban_list local file = io.open("./groups/all/"..target.."all.txt", "w") file:write(text) file:flush() file:close() send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false) return end local function run(msg, matches) if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then local receiver = get_receiver(msg) local target = matches[2] return all(msg,target,receiver) end if not is_owner(msg) then return end if matches[1] == "all" and not matches[2] then local receiver = get_receiver(msg) return all(msg,msg.to.id,receiver) end end return { patterns = { "^[#!/](all)$", "^[#!/](all) (%d+)$" }, run = run } end
gpl-2.0
AresTao/darkstar
scripts/globals/abilities/addendum_white.lua
28
1647
----------------------------------- -- Ability: Addendum: White -- Allows access to additional White Magic spells while using Light Arts. -- Obtained: Scholar Level 10 -- Recast Time: Stratagem Charge -- Duration: 2 hours -- -- Level |Charges |Recharge Time per Charge -- ----- -------- --------------- -- 10 |1 |4:00 minutes -- 30 |2 |2:00 minutes -- 50 |3 |1:20 minutes -- 70 |4 |1:00 minute -- 90 |5 |48 seconds ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if player:hasStatusEffect(EFFECT_ADDENDUM_WHITE) then return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0; end return 0,0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) player:delStatusEffectSilent(EFFECT_DARK_ARTS); player:delStatusEffectSilent(EFFECT_ADDENDUM_BLACK); player:delStatusEffectSilent(EFFECT_LIGHT_ARTS); local skillbonus = player:getMod(MOD_LIGHT_ARTS_SKILL); local effectbonus = player:getMod(MOD_LIGHT_ARTS_EFFECT); local regenbonus = 0; if (player:getMainJob() == JOB_SCH and player:getMainLvl() >= 20) then regenbonus = 3 * math.floor((player:getMainLvl() - 10) / 10); end player:addStatusEffectEx(EFFECT_ADDENDUM_WHITE,EFFECT_ADDENDUM_WHITE,effectbonus,0,7200,0,regenbonus,true); return EFFECT_ADDENDUM_WHITE; end;
gpl-3.0
AresTao/darkstar
scripts/globals/mobskills/Bloody_claw.lua
13
1312
--------------------------------------------- -- Terror Eye -- Family: Gargouille -- Description: Steals an enemy's HP. Additional effect: Reduces a random stat. -- Type: Physical -- Utsusemi/Blink absorb: Ignores shadows -- Range: Melee -- Notes: Despite the attack ignoring Utsusemi, it is physical, and therefore capable of missing entirely. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 3; local accmod = 1; local dmgmod = 0.9; local typeEffect = 136 + math.random(0,6); -- 136 is EFFECT_STR_DOWN; add 0 to 6 for all 7 of the possible attribute reductions local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); if (target:isUndead() == false) then mob:addHP(dmg); end MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 20, 3, 120); return dmg; end;
gpl-3.0
DeinFreund/Zero-K
LuaRules/Gadgets/CAI/astar.lua
9
7268
--------------------------------------------------------------------- --[[ author: quantum GPL v2 or later http://www.policyalmanac.org/games/aStarTutorial.htm http://en.wikipedia.org/wiki/A*_search_algorithm use: override IsBlocked, GetDistance, etc and run aStar.GetPath -- example -------------------------------- local aStar = dofile"astar.lua" aStar.gridHeight = 250 aStar.gridWidth = 250 aStar.IsBlocked = local function(id) return false end function aStar.GetDistanceEstimate(a, b) -- heuristic estimate of distance to goal local x1, y1 = aStar.ToCoords(a) local x2, y2 = aStar.ToCoords(b) return math.max(math.abs(x2-x1), math.abs(y2-y1)) + math.min(math.abs(x2-x1), math.abs(y2-y1))/2*1.001 end function aStar.GetDistance(a, b) -- distance between two directly connected nodes (squares if in a grid) local x1, y1 = aStar.ToCoords(a) local x2, y2 = aStar.ToCoords(b) if x1 == x2 or y1 == y2 then return 1 else return 2^0.5 end end local startID = aStar.ToID{1, 1} local goalID = aStar.ToID{80, 90} local path = aStar.GetPath(startID, goalID) ]] --------------------------------------------------------------------- --------------------------------------------------------------------- local function GetSetCount(set) local count = 0 for _ in pairs(set) do count = count + 1 end return count end local function ReconstructPath(parents, node) local path = {} repeat path[#path + 1] = node node = parents[node] until not node -- reverse it local x, y, temp = 1, #path while x < y do temp = path[x] path[x] = path[y] path[y] = temp x, y = x + 1, y - 1 end return path end local aStar = { -- set grid size gridWidth = 250, gridHeight = 250, } function aStar.NewPriorityQueue() local heap = {} -- binary heap local priorities = {} local heapCount = 0 function heap.Insert(currentKey, currentPriority, currentPosition) if not currentPosition then -- we are inserting a new item, as opposed to changing the f value of an item already in the heap currentPosition = heapCount + 1 heapCount = heapCount + 1 end priorities[currentKey] = currentPriority heap[currentPosition] = currentKey while true do local parentPosition = math.floor(currentPosition/2) if parentPosition == 1 then break end local parentKey = heap[parentPosition] if parentKey and priorities[parentKey] > currentPriority then -- swap parent and current node heap[parentPosition] = currentKey heap[currentPosition] = parentKey currentPosition = parentPosition else break end end end function heap.UpdateNode(currentKey, currentPriority) for position=1, heapCount do local id = heap[position] if id == currentKey then heap.Insert(currentKey, currentPriority, position) break end end end function heap.Pop() local ret = heap[1] if not ret then error "queue is empty" end heap[1] = heap[heapCount] heap[heapCount] = nil heapCount = heapCount - 1 local currentPosition = 1 while true do local currentKey = heap[currentPosition] local currentPriority = priorities[currentKey] local child1Position = currentPosition*2 local child1Key = heap[child1Position] if not child1Key then break end local child2Position = currentPosition*2 + 1 local child2Key = heap[child2Position] if not child2Key then break end local child1F = priorities[child1Key] local child2F = priorities[child2Key] if currentPriority < child1F and currentPriority < child2F then break elseif child1F < child2F then heap[child1Position] = currentKey heap[currentPosition] = child1Key currentPosition = child1Position else heap[child2Position] = currentKey heap[currentPosition] = child2Key currentPosition = child2Position end end return ret, priorities[ret] end return heap end function aStar.ToID(coords) -- override this local function if necessary, converts grid coords to node id local x, y = coords[1], coords[2] return y * aStar.gridWidth + x end function aStar.ToCoords(id) -- override this local function if necessary, converts node id to grid coords return id % aStar.gridWidth, math.floor(id/aStar.gridWidth) end function aStar.GetDistance(a, b) -- override this local function, exact distance beween adjacent nodes a and b error"override this local function" end function aStar.IsBlocked(id) error"override this local function" end function aStar.GetNeighbors(id, goal) -- override this if the nodes are not arranged in a grid local x, y = aStar.ToCoords(id) local nodes = { aStar.ToID{x-1, y}, aStar.ToID{x, y-1}, aStar.ToID{x+1, y}, aStar.ToID{x, y+1}, aStar.ToID{x-1, y-1}, aStar.ToID{x-1, y+1}, aStar.ToID{x+1, y+1}, aStar.ToID{x+1, y-1} } local passable = {} local passableCount = 0 for nodeIndex=1, 8 do local node = nodes[nodeIndex] if not aStar.IsBlocked(node) then passableCount = passableCount + 1 passable[passableCount] = node end end return passable end function aStar.GetDistanceEstimate(a, b) -- heuristic estimate of distance to goal error"override this local function" end function aStar.GetPathsThreaded(startID, goalID, cyclesBeforeYield) cyclesBeforeYield = cyclesBeforeYield or 1000 return coroutine.create(aStar.GetPath) end function aStar.GetPath(startID, goalID, cyclesBeforeYield) local parents = {} local gScores = {} -- distance from start along optimal path local closedSet = {} -- nodes already evaluated local openHeap = aStar.NewPriorityQueue() -- binary heap of nodes by f score gScores[startID] = 0 openHeap.Insert(startID, aStar.GetDistanceEstimate(startID, goalID)) local cyclesFromLastYield = 0 local cycleCounter = 0 while openHeap[1] do -- threading cycleCounter = cycleCounter + 1 if cyclesBeforeYield then cyclesFromLastYield = cyclesFromLastYield + 1 if cyclesFromLastYield > cyclesBeforeYield then cyclesFromLastYield= 0 coroutine.yield(cycleCounter) end end local currentNode = openHeap.Pop() if currentNode == goalID then -- goal reached return ReconstructPath(parents, currentNode), closedSet end closedSet[currentNode] = true for _, neighbor in ipairs(aStar.GetNeighbors(currentNode)) do if not closedSet[neighbor] then local tentativeGScore = gScores[currentNode] + aStar.GetDistance(currentNode, neighbor) if not gScores[neighbor] then parents[neighbor] = currentNode gScores[neighbor] = tentativeGScore openHeap.Insert(neighbor, gScores[neighbor] + aStar.GetDistanceEstimate(neighbor, goalID)) elseif tentativeGScore < gScores[neighbor] then parents[neighbor] = currentNode gScores[neighbor] = tentativeGScore openHeap.UpdateNode(neighbor, gScores[neighbor] + aStar.GetDistanceEstimate(neighbor, goalID)) end end end end return false end return aStar
gpl-2.0
DeinFreund/Zero-K
LuaRules/Gadgets/unit_untargetable.lua
5
1192
-------------------------------------------------------------------------------- -------------------------------------------------------------------------------- if not gadgetHandler:IsSyncedCode() then return end -------------------------------------------------------------------------------- -------------------------------------------------------------------------------- function gadget:GetInfo() return { name = "Disallow unit for command targeting", desc = "Forbid all commands from targeting specific units", author = "Anarchid", date = "1.07.2016", license = "Public domain", layer = 21, enabled = true } end local CMD_INSERT = CMD.INSERT local spValidUnitID = Spring.ValidUnitID local spGetUnitRulesParam = Spring.GetUnitRulesParam function gadget:AllowCommand(unitID, unitDefID, unitTeam, cmdID, cmdParams, cmdOptions, cmdTag, synced) local numParams = #cmdParams if cmdID == CMD.INSERT then numParams = numParams - 3 cmdParams[1] = cmdParams[4] end if numParams ~= 1 then return true end local targetID = cmdParams[1] if not spValidUnitID(targetID) or spGetUnitRulesParam(targetID, "untargetable") ~= 1 then return true end return false end
gpl-2.0
AresTao/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/_5f7.lua
34
1110
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: Leviathan's Gate -- @pos 249 -34 100 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (npc:getAnimation() == 9) then player:messageSpecial(SOLID_STONE); end return 0; 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
prosody-modules/import
mod_client_certs/mod_client_certs.lua
27
13872
-- XEP-0257: Client Certificates Management implementation for Prosody -- Copyright (C) 2012 Thijs Alkemade -- -- This file is MIT/X11 licensed. local st = require "util.stanza"; local jid_bare = require "util.jid".bare; local jid_split = require "util.jid".split; local xmlns_saslcert = "urn:xmpp:saslcert:1"; local dm_load = require "util.datamanager".load; local dm_store = require "util.datamanager".store; local dm_table = "client_certs"; local x509 = require "ssl.x509"; local id_on_xmppAddr = "1.3.6.1.5.5.7.8.5"; local id_ce_subjectAltName = "2.5.29.17"; local digest_algo = "sha1"; local base64 = require "util.encodings".base64; local function get_id_on_xmpp_addrs(cert) local id_on_xmppAddrs = {}; for k,ext in pairs(cert:extensions()) do if k == id_ce_subjectAltName then for e,extv in pairs(ext) do if e == id_on_xmppAddr then for i,v in ipairs(extv) do id_on_xmppAddrs[#id_on_xmppAddrs+1] = v; end end end end end module:log("debug", "Found JIDs: (%d) %s", #id_on_xmppAddrs, table.concat(id_on_xmppAddrs, ", ")); return id_on_xmppAddrs; end local function enable_cert(username, cert, info) -- Check the certificate. Is it not expired? Does it include id-on-xmppAddr? --[[ the method expired doesn't exist in luasec .. yet? if cert:expired() then module:log("debug", "This certificate is already expired."); return nil, "This certificate is expired."; end --]] if not cert:validat(os.time()) then module:log("debug", "This certificate is not valid at this moment."); end local valid_id_on_xmppAddrs; local require_id_on_xmppAddr = true; if require_id_on_xmppAddr then valid_id_on_xmppAddrs = get_id_on_xmpp_addrs(cert); local found = false; for i,k in pairs(valid_id_on_xmppAddrs) do if jid_bare(k) == (username .. "@" .. module.host) then found = true; break; end end if not found then return nil, "This certificate has no valid id-on-xmppAddr field."; end end local certs = dm_load(username, module.host, dm_table) or {}; info.pem = cert:pem(); local digest = cert:digest(digest_algo); info.digest = digest; certs[info.name] = info; dm_store(username, module.host, dm_table, certs); return true end local function disable_cert(username, name, disconnect) local certs = dm_load(username, module.host, dm_table) or {}; local info = certs[name]; if not info then return nil, "item-not-found" end certs[name] = nil; if disconnect then module:log("debug", "%s revoked a certificate! Disconnecting all clients that used it", username); local sessions = hosts[module.host].sessions[username].sessions; local disabled_cert_pem = info.pem; for _, session in pairs(sessions) do if session and session.conn then local cert = session.conn:socket():getpeercertificate(); if cert and cert:pem() == disabled_cert_pem then module:log("debug", "Found a session that should be closed: %s", tostring(session)); session:close{ condition = "not-authorized", text = "This client side certificate has been revoked."}; end end end end dm_store(username, module.host, dm_table, certs); return info; end module:hook("iq/self/"..xmlns_saslcert..":items", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type == "get" then module:log("debug", "%s requested items", origin.full_jid); local reply = st.reply(stanza):tag("items", { xmlns = xmlns_saslcert }); local certs = dm_load(origin.username, module.host, dm_table) or {}; for digest,info in pairs(certs) do reply:tag("item") :tag("name"):text(info.name):up() :tag("x509cert"):text(info.x509cert) :up(); end origin.send(reply); return true end end); module:hook("iq/self/"..xmlns_saslcert..":append", function(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type == "set" then local append = stanza:get_child("append", xmlns_saslcert); local name = append:get_child_text("name", xmlns_saslcert); local x509cert = append:get_child_text("x509cert", xmlns_saslcert); if not x509cert or not name then origin.send(st.error_reply(stanza, "cancel", "bad-request", "Missing fields.")); -- cancel? not modify? return true end local can_manage = append:get_child("no-cert-management", xmlns_saslcert) ~= nil; x509cert = x509cert:gsub("^%s*(.-)%s*$", "%1"); local cert = x509.load( "-----BEGIN CERTIFICATE-----\n" .. x509cert .. "\n-----END CERTIFICATE-----\n"); if not cert then origin.send(st.error_reply(stanza, "modify", "not-acceptable", "Could not parse X.509 certificate")); return true; end local ok, err = enable_cert(origin.username, cert, { name = name, x509cert = x509cert, no_cert_management = can_manage, }); if not ok then origin.send(st.error_reply(stanza, "cancel", "bad-request", err)); return true -- REJECT?! end module:log("debug", "%s added certificate named %s", origin.full_jid, name); origin.send(st.reply(stanza)); return true end end); local function handle_disable(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type == "set" then local disable = stanza.tags[1]; module:log("debug", "%s disabled a certificate", origin.full_jid); local name = disable:get_child_text("name"); if not name then origin.send(st.error_reply(stanza, "cancel", "bad-request", "No key specified.")); return true end disable_cert(origin.username, name, disable.name == "revoke"); origin.send(st.reply(stanza)); return true end end module:hook("iq/self/"..xmlns_saslcert..":disable", handle_disable); module:hook("iq/self/"..xmlns_saslcert..":revoke", handle_disable); -- Ad-hoc command local adhoc_new = module:require "adhoc".new; local dataforms_new = require "util.dataforms".new; local function generate_error_message(errors) local errmsg = {}; for name, err in pairs(errors) do errmsg[#errmsg + 1] = name .. ": " .. err; end return table.concat(errmsg, "\n"); end local choose_subcmd_layout = dataforms_new { title = "Certificate management"; instructions = "What action do you want to perform?"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/certs#subcmd" }; { name = "subcmd", type = "list-single", label = "Actions", required = true, value = { {label = "Add certificate", value = "add"}, {label = "List certificates", value = "list"}, {label = "Disable certificate", value = "disable"}, {label = "Revoke certificate", value = "revoke"}, }; }; }; local add_layout = dataforms_new { title = "Adding a certificate"; instructions = "Enter the certificate in PEM format"; { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/certs#add" }; { name = "name", type = "text-single", label = "Name", required = true }; { name = "cert", type = "text-multi", label = "PEM certificate", required = true }; { name = "manage", type = "boolean", label = "Can manage certificates", value = true }; }; local disable_layout_stub = dataforms_new { { name = "cert", type = "list-single", label = "Certificate", required = true } }; local function adhoc_handler(self, data, state) if data.action == "cancel" then return { status = "canceled" }; end if not state or data.action == "prev" then return { status = "executing", form = choose_subcmd_layout, actions = { "next" } }, {}; end if not state.subcmd then local fields, errors = choose_subcmd_layout:data(data.form); if errors then return { status = "completed", error = { message = generate_error_message(errors) } }; end local subcmd = fields.subcmd if subcmd == "add" then return { status = "executing", form = add_layout, actions = { "prev", "next", "complete" } }, { subcmd = "add" }; elseif subcmd == "list" then local list_layout = dataforms_new { title = "List of certificates"; }; local certs = dm_load(jid_split(data.from), module.host, dm_table) or {}; for digest, info in pairs(certs) do list_layout[#list_layout + 1] = { name = info.name, type = "text-multi", label = info.name, value = info.x509cert }; end return { status = "completed", result = list_layout }; else local layout = dataforms_new { { name = "FORM_TYPE", type = "hidden", value = "http://prosody.im/protocol/certs#" .. subcmd }; { name = "cert", type = "list-single", label = "Certificate", required = true }; }; if subcmd == "disable" then layout.title = "Disabling a certificate"; layout.instructions = "Select the certificate to disable"; elseif subcmd == "revoke" then layout.title = "Revoking a certificate"; layout.instructions = "Select the certificate to revoke"; end local certs = dm_load(jid_split(data.from), module.host, dm_table) or {}; local values = {}; for digest, info in pairs(certs) do values[#values + 1] = { label = info.name, value = info.name }; end return { status = "executing", form = { layout = layout, values = { cert = values } }, actions = { "prev", "next", "complete" } }, { subcmd = subcmd }; end end if state.subcmd == "add" then local fields, errors = add_layout:data(data.form); if errors then return { status = "completed", error = { message = generate_error_message(errors) } }; end local name = fields.name; local x509cert = fields.cert:gsub("^%s*(.-)%s*$", "%1"); local cert = x509.load( "-----BEGIN CERTIFICATE-----\n" .. x509cert .. "\n-----END CERTIFICATE-----\n"); if not cert then return { status = "completed", error = { message = "Could not parse X.509 certificate" } }; end local ok, err = enable_cert(jid_split(data.from), cert, { name = name, x509cert = x509cert, no_cert_management = not fields.manage }); if not ok then return { status = "completed", error = { message = err } }; end module:log("debug", "%s added certificate named %s", data.from, name); return { status = "completed", info = "Successfully added certificate " .. name .. "." }; else local fields, errors = disable_layout_stub:data(data.form); if errors then return { status = "completed", error = { message = generate_error_message(errors) } }; end local info = disable_cert(jid_split(data.from), fields.cert, state.subcmd == "revoke" ); if state.subcmd == "revoke" then return { status = "completed", info = "Revoked certificate " .. info.name .. "." }; else return { status = "completed", info = "Disabled certificate " .. info.name .. "." }; end end end local cmd_desc = adhoc_new("Manage certificates", "http://prosody.im/protocol/certs", adhoc_handler, "user"); module:provides("adhoc", cmd_desc); -- Here comes the SASL EXTERNAL stuff local now = os.time; module:hook("stream-features", function(event) local session, features = event.origin, event.features; if session.secure and session.type == "c2s_unauthed" then local cert = session.conn:socket():getpeercertificate(); if not cert then module:log("error", "No Client Certificate"); return end module:log("info", "Client Certificate: %s", cert:digest(digest_algo)); if not cert:validat(now()) then module:log("debug", "Client has an expired certificate", cert:digest(digest_algo)); return end module:log("debug", "Stream features:\n%s", tostring(features)); local mechs = features:get_child("mechanisms", "urn:ietf:params:xml:ns:xmpp-sasl"); if mechs then mechs:tag("mechanism"):text("EXTERNAL"); end end end, -1); local sm_make_authenticated = require "core.sessionmanager".make_authenticated; module:hook("stanza/urn:ietf:params:xml:ns:xmpp-sasl:auth", function(event) local session, stanza = event.origin, event.stanza; if session.type == "c2s_unauthed" and stanza.attr.mechanism == "EXTERNAL" then if session.secure then local cert = session.conn:socket():getpeercertificate(); local username_data = stanza:get_text(); local username = nil; if username_data == "=" then -- Check for either an id_on_xmppAddr local jids = get_id_on_xmpp_addrs(cert); if not (#jids == 1) then module:log("debug", "Client tried to authenticate as =, but certificate has multiple JIDs."); module:fire_event("authentication-failure", { session = session, condition = "not-authorized" }); session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"not-authorized"); return true; end username = jids[1]; else -- Check the base64 encoded username username = base64.decode(username_data); end local user, host, resource = jid_split(username); module:log("debug", "Inferred username: %s", user or "nil"); if (not username) or (not host == module.host) then module:log("debug", "No valid username found for %s", tostring(session)); module:fire_event("authentication-failure", { session = session, condition = "not-authorized" }); session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"not-authorized"); return true; end local certs = dm_load(user, module.host, dm_table) or {}; local digest = cert:digest(digest_algo); local pem = cert:pem(); for name,info in pairs(certs) do if info.digest == digest and info.pem == pem then sm_make_authenticated(session, user); module:fire_event("authentication-success", { session = session }); session.send(st.stanza("success", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"})); session:reset_stream(); return true; end end module:fire_event("authentication-failure", { session = session, condition = "not-authorized" }); session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"not-authorized"); else session.send(st.stanza("failure", { xmlns="urn:ietf:params:xml:ns:xmpp-sasl"}):tag"encryption-required"); end return true; end end, 1);
mit
AresTao/darkstar
scripts/zones/Chateau_dOraguille/npcs/Curilla.lua
17
5152
----------------------------------- -- Area: Chateau d'Oraguille -- NPC: Curilla -- Starts and Finishes Quest: The General's Secret, Enveloped in Darkness, Peace for the Spirit, Lure of the Wildcat (San d'Oria) -- @pos 27 0.1 0.1 233 ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Chateau_dOraguille/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local mLvL = player:getMainLvl(); local mJob = player:getMainJob(); local theGeneralSecret = player:getQuestStatus(SANDORIA,THE_GENERAL_S_SECRET); local envelopedInDarkness = player:getQuestStatus(SANDORIA,ENVELOPED_IN_DARKNESS); local peaceForTheSpirit = player:getQuestStatus(SANDORIA,PEACE_FOR_THE_SPIRIT); local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,15) == false) then player:startEvent(0x0232); elseif (theGeneralSecret == QUEST_AVAILABLE and player:getFameLevel(SANDORIA) >= 2) then player:startEvent(0x0037); -- Start Quest "The General's Secret" elseif (mJob == 5 and mLvL >= AF2_QUEST_LEVEL and player:getQuestStatus(SANDORIA,THE_CRIMSON_TRIAL) == QUEST_COMPLETED and envelopedInDarkness == QUEST_AVAILABLE) then player:startEvent(0x005E); -- Start Quest "Enveloped in Darkness" elseif (player:hasKeyItem(OLD_POCKET_WATCH) and player:hasKeyItem(OLD_BOOTS) == false) then player:startEvent(0x005D); elseif (player:hasKeyItem(OLD_BOOTS) and player:getVar("needs_crawler_blood") == 0) then player:startEvent(0x0065); elseif (player:getVar("needs_crawler_blood") == 1) then player:startEvent(0x0075); elseif (mJob == 5 and mLvL >= AF2_QUEST_LEVEL and envelopedInDarkness == QUEST_COMPLETED and peaceForTheSpirit == QUEST_AVAILABLE) then player:startEvent(0x006D); -- Start Quest "Peace for the Spirit" elseif (peaceForTheSpirit == QUEST_ACCEPTED) then player:startEvent(0x006C); -- Standard dialog during Peace of the spirit elseif (peaceForTheSpirit == QUEST_ACCEPTED and (player:getVar("peaceForTheSpiritCS") >= 2 and player:getVar("peaceForTheSpiritCS") <= 4)) then player:startEvent(0x0071); elseif (peaceForTheSpirit == QUEST_ACCEPTED and player:getVar("peaceForTheSpiritCS") == 5) then player:startEvent(0x0033); elseif (theGeneralSecret == QUEST_ACCEPTED and player:hasKeyItem(CURILLAS_BOTTLE_EMPTY)) then player:startEvent(0x0035); elseif (theGeneralSecret == QUEST_ACCEPTED and player:hasKeyItem(CURILLAS_BOTTLE_FULL)) then player:startEvent(0x0036); elseif (envelopedInDarkness == QUEST_COMPLETED and peaceForTheSpirit == QUEST_AVAILABLE) then player:startEvent(0x0072); -- Standard dialog after Enveloped in darkness elseif (peaceForTheSpirit == QUEST_COMPLETED) then player:startEvent(0x0034); -- Standard dialog after Peace of the spirit else player:startEvent(0x0212); -- 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 == 0x0037 and option == 1) then player:addQuest(SANDORIA,THE_GENERAL_S_SECRET) player:addKeyItem(CURILLAS_BOTTLE_EMPTY); player:messageSpecial(KEYITEM_OBTAINED,CURILLAS_BOTTLE_EMPTY); elseif (csid == 0x0036) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,16409); -- Lynx Baghnakhs else player:delKeyItem(CURILLAS_BOTTLE_FULL); player:addItem(16409); player:messageSpecial(ITEM_OBTAINED,16409); -- Lynx Baghnakhs player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,THE_GENERAL_S_SECRET); end elseif (csid == 0x005E and option == 1) then player:addQuest(SANDORIA,ENVELOPED_IN_DARKNESS); player:addKeyItem(OLD_POCKET_WATCH); player:messageSpecial(KEYITEM_OBTAINED,OLD_POCKET_WATCH); elseif (csid == 0x006D and option == 1) then player:addQuest(SANDORIA,PEACE_FOR_THE_SPIRIT); player:setVar("needs_crawler_blood",0); elseif (csid == 0x0065) then player:setVar("needs_crawler_blood",1); elseif (csid == 0x0232) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",15,true); end end;
gpl-3.0
resetnow/premake-core
tests/actions/vstudio/vc200x/test_compiler_block.lua
5
13282
-- -- tests/actions/vstudio/vc200x/test_compiler_block.lua -- Validate generation the VCCLCompiler element in Visual Studio 200x C/C++ projects. -- Copyright (c) 2011-2013 Jason Perkins and the Premake project -- local suite = test.declare("vs200x_compiler_block") local vc200x = premake.vstudio.vc200x -- -- Setup/teardown -- local wks, prj function suite.setup() premake.action.set("vs2008") wks, prj = test.createWorkspace() end local function prepare() local cfg = test.getconfig(prj, "Debug") vc200x.VCCLCompilerTool(cfg) end -- -- Verify the basic structure of the compiler block with no flags or settings. -- function suite.looksGood_onDefaultSettings() prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- If include directories are specified, the <AdditionalIncludeDirectories> should be added. -- function suite.additionalIncludeDirs_onIncludeDirs() includedirs { "include/lua", "include/zlib" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="include\lua;include\zlib" ]] end -- -- Ensure macros are not truncated (see issue #63) -- function suite.additionalIncludeDirs_onIncludeDirs_with_vs_macros() includedirs { "$(Macro1)/foo/bar/$(Macro2)/baz" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" AdditionalIncludeDirectories="$(Macro1)\foo\bar\$(Macro2)\baz" ]] end -- -- Verify the handling of the Symbols flag. The format must be set, and the -- debug runtime library must be selected. -- function suite.looksGood_onSymbolsFlag() symbols "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="4" /> ]] end -- -- Verify the handling of the Symbols in conjunction with the Optimize flag. -- The release runtime library must be used. -- function suite.looksGood_onSymbolsAndOptimizeFlags() symbols "On" optimize "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="3" StringPooling="true" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="3" /> ]] end -- -- Verify the handling of the C7 debug information format. -- function suite.looksGood_onC7DebugFormat() symbols "On" debugformat "C7" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="1" /> ]] end --- -- Test precompiled header handling; the header should be treated as -- a plain string value, with no path manipulation applied, since it -- needs to match the value of the #include statement used in the -- project code. --- function suite.compilerBlock_OnPCH() location "build" pchheader "include/common.h" pchsource "source/common.cpp" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="2" PrecompiledHeaderThrough="include/common.h" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Floating point flag tests -- function suite.compilerBlock_OnFpFast() floatingpoint "Fast" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" FloatingPointModel="2" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end function suite.compilerBlock_OnFpStrict() floatingpoint "Strict" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" FloatingPointModel="1" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Check that the "minimal rebuild" flag is applied correctly. -- function suite.minimalRebuildFlagsSet_onMinimalRebuildAndSymbols() flags { "NoMinimalRebuild" } symbols "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="4" /> ]] end -- -- Check that the "no buffer security check" flag is applied correctly. -- function suite.noBufferSecurityFlagSet_onBufferSecurityCheck() flags { "NoBufferSecurityCheck" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" BufferSecurityCheck="false" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Check that the CompileAs value is set correctly for C language projects. -- function suite.compileAsSet_onC() language "C" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" CompileAs="1" /> ]] end -- -- Verify the correct runtime library is used when symbols are enabled. -- function suite.runtimeLibraryIsDebug_onSymbolsNoOptimize() symbols "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="3" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="4" /> ]] end -- -- Verify the correct warnings settings are used when extra warnings are enabled. -- function suite.runtimeLibraryIsDebug_onExtraWarnings() warnings "Extra" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="4" DebugInformationFormat="0" /> ]] end -- -- Verify the correct warnings settings are used when FatalWarnings are enabled. -- function suite.runtimeLibraryIsDebug_onFatalWarnings() flags { "FatalWarnings" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" WarnAsError="true" DebugInformationFormat="0" /> ]] end -- -- Verify the correct warnings settings are used when no warnings are enabled. -- function suite.runtimeLibraryIsDebug_onNoWarnings_whichDisablesAllOtherWarningsFlags() flags { "FatalWarnings" } warnings "Off" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="0" DebugInformationFormat="0" /> ]] end -- -- Verify the correct Detect64BitPortabilityProblems settings are used when _ACTION < "VS2008". -- function suite._64BitPortabilityOn_onVS2005() premake.action.set("vs2005") prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" Detect64BitPortabilityProblems="true" DebugInformationFormat="0" /> ]] end function suite._64BitPortabilityOff_onVS2005_andCLR() premake.action.set("vs2005") clr "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Verify the correct warnings settings are used when no warnings are enabled. -- function suite.runtimeLibraryIsDebug_onVS2005_NoWarnings() premake.action.set("vs2005") warnings "Off" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="0" DebugInformationFormat="0" /> ]] end -- -- Xbox 360 uses the same structure, but changes the element name. -- function suite.looksGood_onXbox360() system "Xbox360" prepare() test.capture [[ <Tool Name="VCCLX360CompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" /> ]] end -- -- Check handling of forced includes. -- function suite.forcedIncludeFiles() forceincludes { "stdafx.h", "include/sys.h" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" ForcedIncludeFiles="stdafx.h;include\sys.h" ]] end function suite.forcedUsingFiles() forceusings { "stdafx.h", "include/sys.h" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" ForcedUsingFiles="stdafx.h;include\sys.h" ]] end -- -- Verify handling of the NoRuntimeChecks flag. -- function suite.onNoRuntimeChecks() flags { "NoRuntimeChecks" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" RuntimeLibrary="2" ]] end -- -- Check handling of the EnableMultiProcessorCompile flag. -- function suite.onMultiProcessorCompile() flags { "MultiProcessorCompile" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" AdditionalOptions="/MP" Optimization="0" BasicRuntimeChecks="3" ]] end -- -- Check handling of the ReleaseRuntime flag; should override the -- default behavior of linking the debug runtime when symbols are -- enabled with no optimizations. -- function suite.releaseRuntime_onFlag() flags { "ReleaseRuntime" } symbols "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="2" ]] end function suite.releaseRuntime_onStaticAndReleaseRuntime() flags { "ReleaseRuntime", "StaticRuntime" } symbols "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" MinimalRebuild="true" BasicRuntimeChecks="3" RuntimeLibrary="0" ]] end -- -- Check the LinkTimeOptimization flag. -- function suite.flags_onLinkTimeOptimization() flags { "LinkTimeOptimization" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" WholeProgramOptimization="true" ]] end -- -- Check the optimization flags. -- function suite.optimization_onOptimize() optimize "On" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="3" StringPooling="true" ]] end function suite.optimization_onOptimizeSize() optimize "Size" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="1" StringPooling="true" ]] end function suite.optimization_onOptimizeSpeed() optimize "Speed" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="2" StringPooling="true" ]] end function suite.optimization_onOptimizeFull() optimize "Full" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="3" StringPooling="true" ]] end function suite.optimization_onOptimizeOff() optimize "Off" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" ]] end function suite.optimization_onOptimizeDebug() optimize "Debug" prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" ]] end -- -- Check handling of the OmitDefaultLibrary flag. -- function suite.onOmitDefaultLibrary() flags { "OmitDefaultLibrary" } prepare() test.capture [[ <Tool Name="VCCLCompilerTool" Optimization="0" BasicRuntimeChecks="3" RuntimeLibrary="2" EnableFunctionLevelLinking="true" UsePrecompiledHeader="0" WarningLevel="3" DebugInformationFormat="0" OmitDefaultLibName="true" ]] end
bsd-3-clause
mortezam1234/kkdfjkfl-
plugins/anti-flood.lua
281
2422
local NUM_MSG_MAX = 5 -- Max number of messages per TIME_CHECK seconds local TIME_CHECK = 5 local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, function (data, success, result) if success ~= 1 then local text = 'I can\'t kick '..data.user..' but should be kicked' send_msg(data.chat, '', ok_cb, nil) end end, {chat=chat, user=user}) end local function run (msg, matches) if msg.to.type ~= 'chat' then return 'Anti-flood works only on channels' else local chat = msg.to.id local hash = 'anti-flood:enabled:'..chat if matches[1] == 'enable' then redis:set(hash, true) return 'Anti-flood enabled on chat' end if matches[1] == 'disable' then redis:del(hash) return 'Anti-flood disabled on chat' end end end local function pre_process (msg) -- Ignore service msg if msg.service then print('Service message') return msg end local hash_enable = 'anti-flood:enabled:'..msg.to.id local enabled = redis:get(hash_enable) if enabled then print('anti-flood enabled') -- Check flood if msg.from.type == 'user' then -- Increase the number of messages from the user on the chat local hash = 'anti-flood:'..msg.from.id..':'..msg.to.id..':msg-num' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then local receiver = get_receiver(msg) local user = msg.from.id local text = 'User '..user..' is flooding' local chat = msg.to.id send_msg(receiver, text, ok_cb, nil) if msg.to.type ~= 'chat' then print("Flood in not a chat group!") elseif user == tostring(our_id) then print('I won\'t kick myself') elseif is_sudo(msg) then print('I won\'t kick an admin!') else -- Ban user -- TODO: Check on this plugin bans local bhash = 'banned:'..msg.to.id..':'..msg.from.id redis:set(bhash, true) kick_user(user, chat) end msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end end return msg end return { description = 'Plugin to kick flooders from group.', usage = {}, patterns = { '^!antiflood (enable)$', '^!antiflood (disable)$' }, run = run, privileged = true, pre_process = pre_process }
gpl-2.0
AresTao/darkstar
scripts/zones/Windurst_Woods/npcs/Meriri.lua
19
1156
----------------------------------- -- Area: Windurst Woods -- NPC: Meriri -- Guild Merchant NPC: Clothcrafting Guild -- @pos -76.471 -3.55 -128.341 241 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Windurst_Woods/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(515,6,21,0)) then player:showText(npc,MERIRI_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0