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
nasomi/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Porter_Moogle.lua
41
1560
----------------------------------- -- Area: Southern San d'Oria [S] -- NPC: Porter Moogle -- Type: Storage Moogle -- @zone 80 -- @pos TODO ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/porter_moogle_util"); local e = { TALK_EVENT_ID = 659, STORE_EVENT_ID = 660, RETRIEVE_EVENT_ID = 661, ALREADY_STORED_ID = 662, MAGIAN_TRIAL_ID = 663 }; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) porterMoogleTrade(player, trade, e); end ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- No idea what the params are, other than event ID and gil. player:startEvent(e.TALK_EVENT_ID, 0x6FFFFF, 0x01, 0x06DD, 0x27, 0x7C7E, 0x15, player:getGil(), 0x03E8); end ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) porterEventUpdate(player, csid, option, e.RETRIEVE_EVENT_ID, RETRIEVE_DIALOG_ID, ITEM_CANNOT_BE_OBTAINED); end ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) porterEventFinish(player, csid, option, e.TALK_EVENT_ID, ITEM_CANNOT_BE_OBTAINED, ITEM_OBTAINED, NOT_HAVE_ENOUGH_GIL); end
gpl-3.0
kaustubhcs/torch-toolbox
Try-model/tryModel.lua
3
3398
-------------------------------------------------------------------------------- -- Routing for testing models.lua -- Alfredo Canziani, Mar 2014 -------------------------------------------------------------------------------- -- Options --------------------------------------------------------------------- lapp = require 'pl.lapp' opt = lapp[[ --width (number) Input pixel side (128, 200) --dataset (string) Training dataset (indoor51|imagenet) --memMB Estimate RAM usage --batchSize (default 128) Batch size --cuda (default true) GPU --dropout (default 0.5 ) Dropout --inputDO (default 0 ) Input dropout ]] opt.ncolors = 3 opt.subsample_name = opt.dataset opt.step = false opt.verbose = true torch.setdefaulttensortype('torch.FloatTensor') -- Requires -------------------------------------------------------------------- require 'nnx' if opt.cuda then if step then io.write('Requiring cunn') io.read() end require 'cunn' end require 'eex' data_folder = eex.datasetsPath() .. 'originalDataset/' -- Requiring models------------------------------------------------------------- package.path = package.path .. ';../../Train/?.lua' if step then io.write('Requiring classes') io.read() end require 'Data/indoor-classes' if step then io.write('Requiring model') io.read() end statFile = io.open('.stat','w+') require 'models' model, loss, dropout, memory = get_model1() io.close(statFile) io.write('\nTemporary files will be deleted now. Press <Return> ') io.read() os.execute('rm .stat .pltStat .pltStatData') print(' > Temporary files removed\n') if opt.memMB then -- Conversion function --------------------------------------------------------- function inMB(mem) mem[0]=mem[0]*4/1024^2 for a,b in pairs(mem.submodel1.val) do mem.submodel1.val[a] = b*4/1024^2 end for a,b in pairs(mem.submodel2.val) do mem.submodel2.val[a] = b*4/1024^2 end mem.parameters = mem.parameters*4/1024^2 end inMB(memory) -- Plotting memory weight ------------------------------------------------------ print(string.format("The network's weights weight %0.2f MB", memory.parameters)) -- Allocating space mem = torch.Tensor(1 + #memory.submodel1.str+1 + #memory.submodel2.str+1) x = torch.linspace(1,mem:size(1),mem:size(1)) -- Serialise <memory> table i=1; labels = '"OH" ' .. i -- OverHead mem[i] = memory[0] i=2; labels = labels .. ', "OH1" ' .. i -- OverHead <submodel1> mem[i] = memory.submodel1.val[0] for a,b in ipairs(memory.submodel1.str) do -- Building xtick labels i = i + 1 labels = labels .. ', "' .. b .. '" ' .. i end mem[{ {3,3+#memory.submodel1.str-1} }] = torch.Tensor(memory.submodel1.val) i = i + 1; labels = labels .. ', "OH2" ' .. i -- OverHead <submodel2> mem[i] = memory.submodel2.val[0] for a,b in ipairs(memory.submodel2.str) do -- Building xtick labels i = i + 1 labels = labels .. ', "' .. b .. '" ' .. i end mem[{ {3+#memory.submodel1.str+1,mem:size(1)} }] = torch.Tensor(memory.submodel2.val) print(string.format('The network training will allocate up to %.2d MB', mem:sum())) -- Plotting gnuplot.plot('Memory usage [MB]', x, mem, '|') gnuplot.raw('set xtics (' .. labels .. ')') gnuplot.axis{0,mem:size(1)+1,0,''} gnuplot.grid(true) end
bsd-3-clause
nasomi/darkstar
scripts/globals/items/serving_of_yellow_curry.lua
35
2067
----------------------------------------- -- ID: 4517 -- Item: serving_of_yellow_curry -- Food Effect: 3hours, All Races ----------------------------------------- -- Health Points 20 -- Strength 5 -- Agility 2 -- Intelligence -4 -- HP Recovered While Healing 2 -- MP Recovered While Healing 1 -- Attack 20% (caps @ 75) -- Ranged Attack 20% (caps @ 75) -- Resist Sleep -- Resist Stun ----------------------------------------- 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,4517); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 5); target:addMod(MOD_AGI, 2); target:addMod(MOD_INT, -4); target:addMod(MOD_HPHEAL, 2); target:addMod(MOD_MPHEAL, 1); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 75); target:addMod(MOD_FOOD_RATTP, 20); target:addMod(MOD_FOOD_RATT_CAP, 75); target:addMod(MOD_SLEEPRES, 7); target:addMod(MOD_STUNRES, 7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 5); target:delMod(MOD_AGI, 2); target:delMod(MOD_INT, -4); target:delMod(MOD_HPHEAL, 2); target:delMod(MOD_MPHEAL, 1); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 75); target:delMod(MOD_FOOD_RATTP, 20); target:delMod(MOD_FOOD_RATT_CAP, 75); target:delMod(MOD_SLEEPRES, 7); target:delMod(MOD_STUNRES, 7); end;
gpl-3.0
shakfu/start-vm
config/base/awesome/vicious/widgets/mboxc.lua
14
1841
--------------------------------------------------- -- Licensed under the GNU General Public License v2 -- * (c) 2010, Adrian C. <anrxc@sysphere.org> --------------------------------------------------- -- {{{ Grab environment local io = { open = io.open } local setmetatable = setmetatable local string = { find = string.find } -- }}} -- Mboxc: provides the count of total, old and new messages in mbox files -- vicious.widgets.mboxc local mboxc = {} -- {{{ Mbox count widget type local function worker(format, warg) if not warg then return end -- Initialize counters local count = { old = 0, total = 0, new = 0 } -- Get data from mbox files for i=1, #warg do local f = io.open(warg[i]) while true do -- Read the mbox line by line, if we are going to read -- some *HUGE* folders then switch to reading chunks local lines = f:read("*line") if not lines then break end -- Find all messages -- * http://www.jwz.org/doc/content-length.html local _, from = string.find(lines, "^From[%s]") if from ~= nil then count.total = count.total + 1 end -- Read messages have the Status header local _, status = string.find(lines, "^Status:[%s]RO$") if status ~= nil then count.old = count.old + 1 end -- Skip the folder internal data local _, int = string.find(lines, "^Subject:[%s].*FOLDER[%s]INTERNAL[%s]DATA") if int ~= nil then count.total = count.total - 1 end end f:close() end -- Substract total from old to get the new count count.new = count.total - count.old return {count.total, count.old, count.new} end -- }}} return setmetatable(mboxc, { __call = function(_, ...) return worker(...) end })
mit
Hello23-Ygopro/ygopro-ds
expansions/script/c27004042.lua
1
1959
--BT4-038 Hirudegarn, the Wanderer local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,CHARACTER_HIRUDEGARN,SPECIAL_TRAIT_PHANTOM_DEMON) ds.AddPlayProcedure(c,COLOR_BLUE,1,1) --to drop ds.AddSingleAutoAttack(c,0,nil,ds.hinttg,ds.DecktopSendtoDropOperation(PLAYER_PLAYER,3)) --play ds.AddActivateMainSkill(c,1,DS_LOCATION_BATTLE,scard.plop,scard.plcost,scard.pltg,DS_EFFECT_FLAG_CARD_CHOOSE) end scard.dragon_ball_super_card=true scard.combo_cost=0 scard.plcost=ds.PaySkillCost(COLOR_COLORLESS,0,3) function scard.plfilter1(c,e,tp) return c:IsCode(CARD_IMPENETRABLE_DEFENSE_HIRUDEGARN) and c:IsCanBePlayed(e,0,tp,false,false) end function scard.plfilter2(c,e) return c:IsCode(CARD_IMPENETRABLE_DEFENSE_HIRUDEGARN) and c:IsCanBeSkillTarget(e) end function scard.pltg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return false end if chk==0 then return Duel.IsExistingTarget(ds.DropAreaFilter(Card.IsCharacter),tp,DS_LOCATION_DROP,0,1,nil,CHARACTER_TAPION) and (Duel.IsExistingTarget(ds.DropAreaFilter(scard.plfilter1),tp,DS_LOCATION_DROP,0,1,nil,e,tp) or Duel.IsExistingTarget(ds.TheWarpFilter(scard.plfilter1),tp,DS_LOCATION_WARP,0,1,nil,e,tp)) end local c=e:GetHandler() Duel.SetTargetCard(c) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TOWARP) local g1=Duel.SelectTarget(tp,ds.DropAreaFilter(Card.IsCharacter),tp,DS_LOCATION_DROP,0,1,1,nil,CHARACTER_TAPION) g1:AddCard(c) Duel.SendtoWarp(g1,REASON_COST) Duel.ClearTargetCard() Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) local g2=Duel.GetMatchingGroup(ds.DropAreaFilter(scard.plfilter2),tp,DS_LOCATION_DROP,0,nil,e) local g3=Duel.GetMatchingGroup(ds.TheWarpFilter(scard.plfilter2),tp,DS_LOCATION_WARP,0,nil,e) g2:Merge(g3) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_PLAY) local sg=g2:Select(tp,1,1,nil) Duel.SetTargetCard(sg) end scard.plop=ds.ChoosePlayOperation(DS_POS_FACEUP_ACTIVE)
gpl-3.0
droogmic/droogmic-domoticz-lua
packages/socket/ltn12.lua
71
8331
----------------------------------------------------------------------------- -- LTN12 - Filters, sources, sinks and pumps. -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module ----------------------------------------------------------------------------- local string = require("string") local table = require("table") local base = _G local _M = {} if module then -- heuristic for exporting a global package table ltn12 = _M end local filter,source,sink,pump = {},{},{},{} _M.filter = filter _M.source = source _M.sink = sink _M.pump = pump -- 2048 seems to be better in windows... _M.BLOCKSIZE = 2048 _M._VERSION = "LTN12 1.0.3" ----------------------------------------------------------------------------- -- Filter stuff ----------------------------------------------------------------------------- -- returns a high level filter that cycles a low-level filter function filter.cycle(low, ctx, extra) base.assert(low) return function(chunk) local ret ret, ctx = low(ctx, chunk, extra) return ret end end -- chains a bunch of filters together -- (thanks to Wim Couwenberg) function filter.chain(...) local arg = {...} local n = select('#',...) local top, index = 1, 1 local retry = "" return function(chunk) retry = chunk and retry while true do if index == top then chunk = arg[index](chunk) if chunk == "" or top == n then return chunk elseif chunk then index = index + 1 else top = top+1 index = top end else chunk = arg[index](chunk or "") if chunk == "" then index = index - 1 chunk = retry elseif chunk then if index == n then return chunk else index = index + 1 end else base.error("filter returned inappropriate nil") end end end end end ----------------------------------------------------------------------------- -- Source stuff ----------------------------------------------------------------------------- -- create an empty source local function empty() return nil end function source.empty() return empty end -- returns a source that just outputs an error function source.error(err) return function() return nil, err end end -- creates a file source function source.file(handle, io_err) if handle then return function() local chunk = handle:read(_M.BLOCKSIZE) if not chunk then handle:close() end return chunk end else return source.error(io_err or "unable to open file") end end -- turns a fancy source into a simple source function source.simplify(src) base.assert(src) return function() local chunk, err_or_new = src() src = err_or_new or src if not chunk then return nil, err_or_new else return chunk end end end -- creates string source function source.string(s) if s then local i = 1 return function() local chunk = string.sub(s, i, i+_M.BLOCKSIZE-1) i = i + _M.BLOCKSIZE if chunk ~= "" then return chunk else return nil end end else return source.empty() end end -- creates rewindable source function source.rewind(src) base.assert(src) local t = {} return function(chunk) if not chunk then chunk = table.remove(t) if not chunk then return src() else return chunk end else table.insert(t, chunk) end end end function source.chain(src, f) base.assert(src and f) local last_in, last_out = "", "" local state = "feeding" local err return function() if not last_out then base.error('source is empty!', 2) end while true do if state == "feeding" then last_in, err = src() if err then return nil, err end last_out = f(last_in) if not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end elseif last_out ~= "" then state = "eating" if last_in then last_in = "" end return last_out end else last_out = f(last_in) if last_out == "" then if last_in == "" then state = "feeding" else base.error('filter returned ""') end elseif not last_out then if last_in then base.error('filter returned inappropriate nil') else return nil end else return last_out end end end end end -- creates a source that produces contents of several sources, one after the -- other, as if they were concatenated -- (thanks to Wim Couwenberg) function source.cat(...) local arg = {...} local src = table.remove(arg, 1) return function() while src do local chunk, err = src() if chunk then return chunk end if err then return nil, err end src = table.remove(arg, 1) end end end ----------------------------------------------------------------------------- -- Sink stuff ----------------------------------------------------------------------------- -- creates a sink that stores into a table function sink.table(t) t = t or {} local f = function(chunk, err) if chunk then table.insert(t, chunk) end return 1 end return f, t end -- turns a fancy sink into a simple sink function sink.simplify(snk) base.assert(snk) return function(chunk, err) local ret, err_or_new = snk(chunk, err) if not ret then return nil, err_or_new end snk = err_or_new or snk return 1 end end -- creates a file sink function sink.file(handle, io_err) if handle then return function(chunk, err) if not chunk then handle:close() return 1 else return handle:write(chunk) end end else return sink.error(io_err or "unable to open file") end end -- creates a sink that discards data local function null() return 1 end function sink.null() return null end -- creates a sink that just returns an error function sink.error(err) return function() return nil, err end end -- chains a sink with a filter function sink.chain(f, snk) base.assert(f and snk) return function(chunk, err) if chunk ~= "" then local filtered = f(chunk) local done = chunk and "" while true do local ret, snkerr = snk(filtered, err) if not ret then return nil, snkerr end if filtered == done then return 1 end filtered = f(done) end else return 1 end end end ----------------------------------------------------------------------------- -- Pump stuff ----------------------------------------------------------------------------- -- pumps one chunk from the source to the sink function pump.step(src, snk) local chunk, src_err = src() local ret, snk_err = snk(chunk, src_err) if chunk and ret then return 1 else return nil, src_err or snk_err end end -- pumps all data from a source to a sink, using a step function function pump.all(src, snk, step) base.assert(src and snk) step = step or pump.step while true do local ret, err = step(src, snk) if not ret then if err then return nil, err else return 1 end end end end return _M
mit
thesabbir/luci
applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/network.lua
53
2738
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. m = Map("luci_statistics", translate("Network Plugin Configuration"), translate( "The network plugin provides network based communication between " .. "different collectd instances. Collectd can operate both in client " .. "and server mode. In client mode locally collected data is " .. "transferred to a collectd server instance, in server mode the " .. "local instance receives data from other hosts." )) -- collectd_network config section s = m:section( NamedSection, "collectd_network", "luci_statistics" ) -- collectd_network.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_network_listen config section (Listen) listen = m:section( TypedSection, "collectd_network_listen", translate("Listener interfaces"), translate( "This section defines on which interfaces collectd will wait " .. "for incoming connections." )) listen.addremove = true listen.anonymous = true -- collectd_network_listen.host listen_host = listen:option( Value, "host", translate("Listen host") ) listen_host.default = "0.0.0.0" -- collectd_network_listen.port listen_port = listen:option( Value, "port", translate("Listen port") ) listen_port.default = 25826 listen_port.isinteger = true listen_port.optional = true -- collectd_network_server config section (Server) server = m:section( TypedSection, "collectd_network_server", translate("server interfaces"), translate( "This section defines to which servers the locally collected " .. "data is sent to." )) server.addremove = true server.anonymous = true -- collectd_network_server.host server_host = server:option( Value, "host", translate("Server host") ) server_host.default = "0.0.0.0" -- collectd_network_server.port server_port = server:option( Value, "port", translate("Server port") ) server_port.default = 25826 server_port.isinteger = true server_port.optional = true -- collectd_network.timetolive (TimeToLive) ttl = s:option( Value, "TimeToLive", translate("TTL for network packets") ) ttl.default = 128 ttl.isinteger = true ttl.optional = true ttl:depends( "enable", 1 ) -- collectd_network.forward (Forward) forward = s:option( Flag, "Forward", translate("Forwarding between listen and server addresses") ) forward.default = 0 forward.optional = true forward:depends( "enable", 1 ) -- collectd_network.cacheflush (CacheFlush) cacheflush = s:option( Value, "CacheFlush", translate("Cache flush interval"), translate("Seconds") ) cacheflush.default = 86400 cacheflush.isinteger = true cacheflush.optional = true cacheflush:depends( "enable", 1 ) return m
apache-2.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/electric_rapier.meta.lua
2
3585
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 80, light_colors = { "0 234 255 255", "196 250 255 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = -17, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = -11, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = { 2, 3, 4, 2, 4, 8, 9, 10, 2, 4, 4, 5, 6, 7, 8, 4, 11, 0, 1, 10, 11, 10, 1, 2, 10 }, original_poly = { { x = -20, y = -4 }, { x = -16, y = -2 }, { x = -8, y = -3 }, { x = -9.4399995803833008, y = -8.0200004577636719 }, { x = -5, y = -3.7799999713897705 }, { x = 13, y = -4 }, { x = 20.049999237060547, y = 0.64999997615814209 }, { x = 11, y = 4 }, { x = -4, y = 4 }, { x = -8.2399997711181641, y = 8.3099994659423828 }, { x = -9, y = 2 }, { x = -20, y = 5 } } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
nasomi/darkstar
scripts/globals/items/serving_of_patriarch_sautee.lua
36
1253
----------------------------------------- -- ID: 5677 -- Item: Serving of Patriarch Sautee -- Food Effect: 4Hrs, All Races ----------------------------------------- -- MP 60 -- Mind 7 -- MP Recovered While Healing 7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5677); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 60); target:addMod(MOD_MND, 7); target:addMod(MOD_MPHEAL, 7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 60); target:delMod(MOD_MND, 7); target:delMod(MOD_MPHEAL, 7); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Bastok_Mines/npcs/Odoba.lua
19
1145
----------------------------------- -- Area: Bastok Mines -- NPC: Odoba -- Guild Merchant NPC: Alchemy Guild -- @pos 108.473 5.017 1.089 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:sendGuild(526,8,23,6)) then player:showText(npc, ODOBA_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Hello23-Ygopro/ygopro-ds
expansions/script/c27001101.lua
1
1252
--BT1-086_SPR Golden Frieza, Resurrected Terror local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_FRIEZAS_ARMY,CHARACTER_FRIEZA,SPECIAL_TRAIT_FRIEZA_CLAN) ds.AddPlayProcedure(c,COLOR_YELLOW,3,4) --evolve ds.EnableEvolve(c,aux.FilterBoolFunction(Card.IsCharacter,CHARACTER_FRIEZA),COLOR_YELLOW,2,4) --triple strike ds.EnableTripleStrike(c) --to drop ds.AddSingleAutoPlay(c,0,nil,ds.hinttg,scard.tgop,DS_EFFECT_FLAG_CARD_CHOOSE,ds.evoplcon) end scard.dragon_ball_super_card=true scard.combo_cost=1 function scard.posfilter(c,e) return c:IsActive() and c:IsCanBeSkillTarget(e) end function scard.tgop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local g1=Duel.GetMatchingGroup(ds.BattleAreaFilter(Card.IsRest),tp,DS_LOCATION_BATTLE,DS_LOCATION_BATTLE,c) Duel.SendtoDrop(g1,DS_REASON_SKILL) local g2=Duel.GetMatchingGroup(ds.BattleAreaFilter(scard.posfilter),tp,DS_LOCATION_BATTLE,DS_LOCATION_BATTLE,c,e) local ct=g2:GetCount() if ct==0 then return end Duel.BreakEffect() Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TOREST) local sg=g2:Select(tp,ct,ct,nil) Duel.SetTargetCard(sg) Duel.SwitchPosition(sg,DS_POS_FACEUP_REST) end
gpl-3.0
nasomi/darkstar
scripts/zones/Port_Bastok/npcs/Styi_Palneh.lua
17
4043
----------------------------------- -- Area: Port Bastok -- NPC: Styi Palneh -- Title Change NPC -- @pos 28 4 -15 236 ----------------------------------- require("scripts/globals/titles"); local title2 = { NEW_ADVENTURER , BASTOK_WELCOMING_COMMITTEE , BUCKET_FISHER , PURSUER_OF_THE_PAST , MOMMYS_HELPER , HOT_DOG , STAMPEDER , RINGBEARER , ZERUHN_SWEEPER , TEARJERKER , CRAB_CRUSHER , BRYGIDAPPROVED , GUSTABERG_TOURIST , MOGS_MASTER , CERULEAN_SOLDIER , DISCERNING_INDIVIDUAL , VERY_DISCERNING_INDIVIDUAL , EXTREMELY_DISCERNING_INDIVIDUAL , APOSTATE_FOR_HIRE , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { SHELL_OUTER , PURSUER_OF_THE_TRUTH , QIJIS_FRIEND , TREASURE_SCAVENGER , SAND_BLASTER , DRACHENFALL_ASCETIC , ASSASSIN_REJECT , CERTIFIED_ADVENTURER , QIJIS_RIVAL , CONTEST_RIGGER , KULATZ_BRIDGE_COMPANION , AVENGER , AIRSHIP_DENOUNCER , STAR_OF_IFRIT , PURPLE_BELT , MOGS_KIND_MASTER , TRASH_COLLECTOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { BEADEAUX_SURVEYOR , PILGRIM_TO_DEM , BLACK_DEATH , DARK_SIDER , SHADOW_WALKER , SORROW_DROWNER , STEAMING_SHEEP_REGULAR , SHADOW_BANISHER , MOGS_EXCEPTIONALLY_KIND_MASTER , HYPER_ULTRA_SONIC_ADVENTURER , GOBLIN_IN_DISGUISE , BASTOKS_SECOND_BEST_DRESSED , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { PARAGON_OF_WARRIOR_EXCELLENCE , PARAGON_OF_MONK_EXCELLENCE , PARAGON_OF_DARK_KNIGHT_EXCELLENCE , HEIR_OF_THE_GREAT_EARTH , MOGS_LOVING_MASTER , HERO_AMONG_HEROES , DYNAMISBASTOK_INTERLOPER , MASTER_OF_MANIPULATION , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { LEGIONNAIRE , DECURION , CENTURION , JUNIOR_MUSKETEER , SENIOR_MUSKETEER , MUSKETEER_COMMANDER , GOLD_MUSKETEER , PRAEFECTUS , SENIOR_GOLD_MUSKETEER , PRAEFECTUS_CASTRORUM , ANVIL_ADVOCATE , FORGE_FANATIC , ACCOMPLISHED_BLACKSMITH , ARMORY_OWNER , TRINKET_TURNER , SILVER_SMELTER , ACCOMPLISHED_GOLDSMITH , JEWELRY_STORE_OWNER , FORMULA_FIDDLER , POTION_POTENTATE , ACCOMPLISHED_ALCHEMIST , APOTHECARY_OWNER , 0 , 0 , 0 , 0 , 0 , 0 } local title7 = { MOG_HOUSE_HANDYPERSON , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00C8,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==0x00C8) then if (option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title5[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(500)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(600)) then player:setTitle( title6[option - 1024] ) end elseif (option > 1280 and option < 1309) then if (player:delGil(700)) then player:setTitle( title7[option - 1280]) end end end end;
gpl-3.0
hqren/Atlas
lib/proxy/balance.lua
41
2807
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2008, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] module("proxy.balance", package.seeall) function idle_failsafe_rw() local backend_ndx = 0 for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local conns = s.pool.users[proxy.connection.client.username] if conns.cur_idle_connections > 0 and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and s.type == proxy.BACKEND_TYPE_RW then backend_ndx = i break end end return backend_ndx end function idle_ro() local max_conns = -1 local max_conns_ndx = 0 for i = 1, #proxy.global.backends do local s = proxy.global.backends[i] local conns = s.pool.users[proxy.connection.client.username] -- pick a slave which has some idling connections if s.type == proxy.BACKEND_TYPE_RO and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and conns.cur_idle_connections > 0 then if max_conns == -1 or s.connected_clients < max_conns then max_conns = s.connected_clients max_conns_ndx = i end end end return max_conns_ndx end function cycle_read_ro() local backends = proxy.global.backends local rwsplit = proxy.global.config.rwsplit local max_weight = rwsplit.max_weight local cur_weight = rwsplit.cur_weight local next_ndx = rwsplit.next_ndx local ndx_num = rwsplit.ndx_num local ndx = 0 for i = 1, ndx_num do --ÿ¸öquery×î¶àÂÖѯndx_num´Î local s = backends[next_ndx] if s.type == proxy.BACKEND_TYPE_RO and s.weight >= cur_weight and s.state ~= proxy.BACKEND_STATE_DOWN and s.state ~= proxy.BACKEND_STATE_OFFLINE and s.pool.users[proxy.connection.client.username].cur_idle_connections > 0 then ndx = next_ndx end if next_ndx == ndx_num then --ÂÖѯÍêÁË×îºóÒ»¸öndx£¬È¨Öµ¼õÒ» cur_weight = cur_weight - 1 if cur_weight == 0 then cur_weight = max_weight end next_ndx = 1 else --·ñÔòÖ¸Ïòϸöndx next_ndx = next_ndx + 1 end if ndx ~= 0 then break end end rwsplit.cur_weight = cur_weight rwsplit.next_ndx = next_ndx return ndx end
gpl-2.0
nasomi/darkstar
scripts/zones/Zeruhn_Mines/npcs/Zelman.lua
34
1737
----------------------------------- -- Area: Zeruhn Mines -- NPC: Zelman -- Involved In Quest: Groceries ----------------------------------- package.loaded["scripts/zones/Zeruhn_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Zeruhn_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local GroceriesVar = player:getVar("Groceries"); local GroceriesViewedNote = player:getVar("GroceriesViewedNote"); if (GroceriesVar == 2) then player:showText(npc,7279); elseif (GroceriesVar == 1) then ViewedNote = player:seenKeyItem(TAMIS_NOTE); if (ViewedNote == true) then player:startEvent(0x00a2); else player:startEvent(0x00a1); end else player:startEvent(0x00a0); 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 == 0x00a1) then player:setVar("Groceries",2); player:delKeyItem(TAMIS_NOTE); elseif (csid == 0x00a2) then player:setVar("GroceriesViewedNote",1); player:delKeyItem(TAMIS_NOTE); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/spells/dokumori_ichi.lua
18
1202
----------------------------------------- -- Spell: Dokumori: Ichi ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local effect = EFFECT_POISON; -- Base Stats local dINT = (caster:getStat(MOD_INT) - target:getStat(MOD_INT)); --Duration Calculation local duration = 60 * applyResistance(caster,spell,target,dINT,NINJUTSU_SKILL,0); local power = 3; --Calculates resist chanve from Reist Blind if (target:hasStatusEffect(effect)) then spell:setMsg(75); -- no effect return effect; end if (math.random(0,100) >= target:getMod(MOD_POISONRES)) then if (duration >= 30) then if (target:addStatusEffect(effect,power,3,duration)) then spell:setMsg(236); else spell:setMsg(75); end else spell:setMsg(85); end else spell:setMsg(284); end return effect; end;
gpl-3.0
mlem/wesnoth
data/ai/micro_ais/cas/ca_lurkers.lua
25
3877
local LS = wesnoth.require "lua/location_set.lua" local AH = wesnoth.require "ai/lua/ai_helper.lua" local H = wesnoth.require "lua/helper.lua" local function get_lurker(cfg) -- We simply pick the first of the lurkers, they have no strategy local lurker = AH.get_units_with_moves { side = wesnoth.current.side, { "and", cfg.filter } }[1] return lurker end local ca_lurkers = {} function ca_lurkers:evaluation(ai, cfg) if get_lurker(cfg) then return cfg.ca_score end return 0 end function ca_lurkers:execution(ai, cfg) local lurker = get_lurker(cfg) local targets = AH.get_live_units { { "filter_side", { { "enemy_of", { side = wesnoth.current.side } } } } } -- Sort targets by hitpoints (lurkers choose lowest HP target) table.sort(targets, function(a, b) return (a.hitpoints < b.hitpoints) end) local reach = LS.of_pairs(wesnoth.find_reach(lurker.x, lurker.y)) local reachable_attack_terrain = LS.of_pairs(wesnoth.get_locations { { "and", { x = lurker.x, y = lurker.y, radius = lurker.moves } }, { "and", cfg.filter_location } }) reachable_attack_terrain:inter(reach) -- Need to restrict that to reachable and not occupied by an ally (except own position) local reachable_attack_terrain = reachable_attack_terrain:filter(function(x, y, v) local occ_hex = wesnoth.get_units { x = x, y = y, { "not", { x = lurker.x, y = lurker.y } } }[1] return not occ_hex end) -- Attack the weakest reachable enemy for _,target in ipairs(targets) do -- Get reachable attack terrain next to target unit local reachable_attack_terrrain_adj_target = LS.of_pairs( wesnoth.get_locations { x = target.x, y = target.y, radius = 1 } ) reachable_attack_terrrain_adj_target:inter(reachable_attack_terrain) -- Since enemies are sorted by hitpoints, we can simply attack the first enemy found if reachable_attack_terrrain_adj_target:size() > 0 then local rand = math.random(1, reachable_attack_terrrain_adj_target:size()) local dst = reachable_attack_terrrain_adj_target:to_stable_pairs() AH.movefull_stopunit(ai, lurker, dst[rand]) if (not lurker) or (not lurker.valid) then return end if (not target) or (not target.valid) then return end if (H.distance_between(lurker.x, lurker.y, target.x, target.y) ~= 1) then return end AH.checked_attack(ai, lurker, target) return end end -- If we got here, unit did not attack: go to random wander terrain hex if (lurker.moves > 0) and (not cfg.stationary) then local reachable_wander_terrain = LS.of_pairs( wesnoth.get_locations { { "and", { x = lurker.x, y = lurker.y, radius = lurker.moves } }, { "and", (cfg.filter_location_wander or cfg.filter_location) } }) reachable_wander_terrain:inter(reach) -- Need to restrict that to reachable and not occupied by an ally (except own position) local reachable_wander_terrain = reachable_wander_terrain:filter(function(x, y, v) local occ_hex = wesnoth.get_units { x = x, y = y, { "not", { x = lurker.x, y = lurker.y } } }[1] return not occ_hex end) if (reachable_wander_terrain:size() > 0) then local dst = reachable_wander_terrain:to_stable_pairs() local rand = math.random(1, reachable_wander_terrain:size()) AH.movefull_stopunit(ai, lurker, dst[rand]) return end end -- If the unit has moves or attacks left at this point, take them away AH.checked_stopunit_all(ai, lurker) end return ca_lurkers
gpl-2.0
nasomi/darkstar
scripts/zones/Dynamis-Tavnazia/bcnms/dynamis_Tavnazia.lua
16
1139
----------------------------------- -- Area: dynamis_Tavnazia -- Name: dynamis_Tavnazia ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[DynaTavnazia]UniqueID",player:getDynamisUniqueID(1289)); SetServerVariable("[DynaTavnazia]Boss_Trigger",0); SetServerVariable("[DynaTavnazia]Already_Received",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("DynamisID",GetServerVariable("[DynaTavnazia]UniqueID")); local realDay = os.time(); local dynaWaitxDay = player:getVar("dynaWaitxDay"); if ((dynaWaitxDay + (BETWEEN_2DYNA_WAIT_TIME * 24 * 60 * 60)) < realDay) then player:setVar("dynaWaitxDay",realDay); end end; -- Leaving the Dynamis by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then SetServerVariable("[DynaTavnazia]UniqueID",0); end end;
gpl-3.0
Hello23-Ygopro/ygopro-ds
expansions/script/c27002126.lua
1
1599
--BT2-111 Secret Evolution Cooler --Note: Keep "give skill" appropriately synchronized with Auxiliary.EnableEvolve local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_FRIEZA_CLAN,CHARACTER_COOLER) ds.AddPlayProcedure(c,COLOR_YELLOW,2,1) --give skill local e1=Effect.CreateEffect(c) e1:SetDescription(DS_DESC_EVOLVE) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_FREE_CHAIN) e1:SetRange(LOCATION_HAND) e1:SetHintTiming(DS_TIMING_MAIN,0) e1:SetCondition(ds.EvolveCondition) e1:SetCost(ds.EvolveCost(aux.FilterBoolFunction(Card.IsCharacter,CHARACTER_COOLER),COLOR_YELLOW,3,0)) e1:SetTarget(ds.EvolveTarget) e1:SetOperation(ds.EvolveOperation) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_GRANT) e2:SetRange(DS_LOCATION_BATTLE) e2:SetTargetRange(LOCATION_HAND,0) e2:SetTarget(aux.TargetBoolFunction(Card.IsCharacter,CHARACTER_COOLER)) e2:SetCondition(scard.skcon) e2:SetLabelObject(e1) c:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetCode(DS_SKILL_EVOLVE) e3:SetRange(DS_LOCATION_BATTLE) e3:SetTargetRange(LOCATION_HAND,0) e3:SetTarget(aux.TargetBoolFunction(Card.IsCharacter,CHARACTER_COOLER)) e3:SetCondition(scard.skcon) c:RegisterEffect(e3) end scard.dragon_ball_super_card=true scard.combo_cost=0 function scard.skcon(e) return Duel.IsExistingMatchingCard(ds.DropAreaFilter(Card.IsSpecialTrait),e:GetHandlerPlayer(),DS_LOCATION_DROP,0,3,nil,SPECIAL_TRAIT_COOLERS_ARMORED_SQUADRON) end
gpl-3.0
akornatskyy/lucid
src/http/request_key.lua
1
2997
local assert, format, concat = assert, string.format, table.concat local load = loadstring or load local unpack = unpack or table.unpack local function var_method() return nil, 'req.method' end local function var_path() return nil, 'req.path' end local function var_query(name) return 'local q = req.query or req:parse_query()', '(q["' .. name .. '"] or "")' end local function var_headers(name) name = name:gsub('_', '-') return 'local h = req.headers or req:parse_headers()', '(h["' .. name .. '"] or "")' end local function var_cookies(name) return 'local c = req.cookies or req:parse_cookie()', '(c["' .. name .. '"] or "")' end local function var_gzip() return 'local h = req.headers', '((h["accept-encoding"] or ""):find("gzip", 1, true) and "z" or "")' end local variables = { method = var_method, m = var_method, path = var_path, p = var_path, query = var_query, q = var_query, headers = var_headers, header = var_headers, h = var_headers, cookie = var_cookies, c = var_cookies, gzip = var_gzip, gz = var_gzip } local function keys(t) local r = {} for k in pairs(t) do r[#r+1] = k end return r end local function parse_parts(s) local parts = {} local b = 1 local e local pe = 1 while true do b, e = s:find('%$%w+', b) if not b then parts[#parts+1] = s:sub(pe) break end parts[#parts+1] = s:sub(pe, b - 1) local name = s:sub(b + 1, e) e = e + 1 b, pe = s:find('^_[%w_]+', e) if b then parts[#parts+1] = {name, s:sub(b + 1, pe)} pe = pe + 1 else parts[#parts+1] = {name} pe = e end b = e end return parts end local function build(parts) local locals = {} local chunks = {} for i = 1, #parts do if i % 2 == 1 then local s = parts[i] if #s > 0 then chunks[#chunks+1] = format('%q', s) end else local name, param = unpack(parts[i]) local v = variables[name] if not v then return error('unknown variable "' .. name .. '"') end local l, c = v(param) if l and #l > 0 then locals[l] = true end chunks[#chunks+1] = c end end locals = concat(keys(locals), '\n ') chunks = concat(chunks, ' ..\n ') return format([[ return function(req) %s return %s end]], locals, chunks) end local function new(s) if type(s) ~= 'string' or #s == 0 then return error('bad argument #1 to \'new\' (non empty string expected)') end local source = build(parse_parts(s)) -- print(source) return assert(load(source))() end return { new = new, variables = variables }
mit
nasomi/darkstar
scripts/zones/Davoi/npcs/_45g.lua
19
2043
----------------------------------- -- Area: Davoi -- NPC: Groaning Pond -- Used In Quest: Whence Blows the Wind -- @pos 101 0.1 60 149 ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0032); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0032 and player:getVar("miniQuestForORB_CS") == 1) then local c = player:getVar("countRedPoolForORB"); if (c == 0) then player:setVar("countRedPoolForORB", c + 8); player:delKeyItem(WHITE_ORB); player:addKeyItem(PINK_ORB); player:messageSpecial(KEYITEM_OBTAINED, PINK_ORB); elseif (c == 1 or c == 2 or c == 4) then player:setVar("countRedPoolForORB", c + 8); player:delKeyItem(PINK_ORB); player:addKeyItem(RED_ORB); player:messageSpecial(KEYITEM_OBTAINED, RED_ORB); elseif (c == 3 or c == 5 or c == 6) then player:setVar("countRedPoolForORB", c + 8); player:delKeyItem(RED_ORB); player:addKeyItem(BLOOD_ORB); player:messageSpecial(KEYITEM_OBTAINED, BLOOD_ORB); elseif (c == 7) then player:setVar("countRedPoolForORB", c + 8); player:delKeyItem(BLOOD_ORB); player:addKeyItem(CURSED_ORB); player:messageSpecial(KEYITEM_OBTAINED, CURSED_ORB); player:addStatusEffect(EFFECT_PLAGUE,0,0,900); end end end;
gpl-3.0
freem/freemlib-neogeo
tools/sailorvrom/lua/svrom.lua
1
17182
-- Sailor VROM (Lua version) by freem -- Use of this tool (e.g. using the exported files) is free. -- License is still undecided, but leaning towards public domain/unlicense/CC0. --============================================================================-- local verNum = 0.20 local pcmbSeparator = "|" local sizeWarnString = "(needs padding)" local errorString = "" local sampleListTypes = { ["vasm"] = { Directive="word", Format="0x%04X" }, ["tniasm"] = { Directive="dw", Format="$%04X" }, -- could also use 0x%04X ["wla"] = { Directive=".dw", Format="$%04X" }, } --============================================================================-- -- Program startup (banner, basic argument check) local args = {...} print("Sailor VROM - Neo-Geo V ROM/.PCM File Builder (Lua version)"); print(string.format("v%.02f by freem",verNum)) print("==========================================================="); -- check arguments if not args or not args[1] then print("No arguments found.") print("usage: lua svrom.lua (options)") print("==========================================================="); print("Available options:") print(" --pcma=path path/filename of ADPCM-A sample list file") print(" --pcmb=path path/filename of ADPCM-B sample list file") print(" --outname=path path/filename of sound data output") print(" --samplelist=path path/filename of sample list output") print(" --samplestart=addr starting address for sample list output") print(" --mode=mode 'cd' or 'cart', without the quotes") print(" --slformat=format 'vasm', 'tniasm', or 'wla', all without quotes") return end --============================================================================-- -- parse command line parameters local pcmaListFile, pcmbListFile -- adpcm-a and adpcm-b sample list input files local outSoundFile, outSampleFile -- sound data and sample list output files local pcmaListFN, pcmbListFN, outSoundFN, outSampleFN -- filenames for the above local modeType = "cart" local sampListType = "vasm" local outSampleStart = 0 local possibleParams = { ["pcma"] = function(input) pcmaListFN = input end, ["pcmb"] = function(input) pcmbListFN = input end, ["outname"] = function(input) outSoundFN = input end, ["samplelist"] = function(input) outSampleFN = input end, ["samplestart"] = function(input) local _start,_end if string.find(input,"0x") then -- hex format 1 _start,_end = string.find(input,"0x") outSampleStart = tonumber(string.sub(input,_end+1,-1),16) elseif string.find(input,"$") then -- hex format 2 _start,_end = string.find(input,"$") outSampleStart = tonumber(string.sub(input,2,-1),16) elseif tonumber(input) then -- decimal outSampleStart = tonumber(input) else error("Invalid input for samplestart: "..input) end end, ["mode"] = function(input) input = string.lower(input) if input ~= "cart" and input ~="cd" then error("Mode option must be 'cart' or 'cd'!") end modeType = input end, ["slformat"] = function(input) local foundFormat = false input = string.lower(input) for t,f in pairs(sampleListTypes) do if not foundFormat then if input == t then sampListType = t foundFormat = true end end end if not foundFormat then print(string.format("Unknown slformat type '%s', using vasm instead.",input)) end end, } local startDash, endDash, startEquals for k,v in pairs(args) do -- search for "--" at the beginning of a string startDash,endDash = string.find(v,"--",1,true) if not startDash then print(string.format("Unrecognized option '%s'.",v)) return end -- look for a "=" inside of it startEquals = string.find(v,"=",3,true) if not startEquals then print(string.format("Did not find equals to assign data in '%s'.",v)) return end -- decode command and value local command = string.sub(v,endDash+1,startEquals-1) local value = string.sub(v,startEquals+1,-1) -- look for command in table local didCommand = false for c,f in pairs(possibleParams) do if c == command then f(value) didCommand = true end end if not didCommand then print(string.format("Sailor VROM doesn't recognize the command '%s'.",command)) end end --============================================================================-- -- By this point, the commands are parsed. We should have values in the proper -- variables if the user decided to actually enter some data. Of course, some -- parameters are optional, so we also handle the fallback filenames here. print(string.format("Output Mode Type: %s",modeType)) if pcmaListFN then print(string.format("ADPCM-A sample list file: '%s'",pcmaListFN)) end -- if ADPCM-B is attempted to be used on a CD system, we need to ignore it. if pcmbListFN and modeType == "cd" then print("Neo-Geo CD does not support ADPCM-B playback. (Yes, we've tried.)") print("Ignoring ADPCM-B samples...") pcmbListFN = nil end if pcmbListFN then print(string.format("ADPCM-B sample list file: '%s'",pcmbListFN)) end -- outSoundFN is not mandatory. (defaults to "output.v" or "output.pcm") if not outSoundFN then outSoundFN = "output."..(modeType=="cd" and "pcm" or "v") print(string.format("Sound data output filename omitted, using '%s'.",outSoundFN)) else print(string.format("Sound data output: %s",outSoundFN)) end -- outSampleFN is not mandatory either. (defaults to "samples.inc") if not outSampleFN then outSampleFN = "samples.inc" print(string.format("Sample address output filename omitted, using '%s'.",outSampleFN)) else print(string.format("Sample address output: %s",outSampleFN)) end print(string.format("sample list address start: %s",outSampleStart)) print(string.format("sample list type: %s",sampListType)) print("") --============================================================================-- -- Whew. That's a lot of checking. We're still not done yet, though, because if -- those list files turn out to not exist, then I'm gonna get really mad! if pcmaListFN then pcmaListFile,errorString = io.open(pcmaListFN,"r") if not pcmaListFile then print(string.format("Error attempting to open ADPCM-A list %s",errorString)) return end end --[[ Generic List Parsing Variables ]]-- local tempFile, tempLen, tempData local padMe = false --[[ ADPCM-A List Parsing ]]-- local pcmaFiles = {} local pcmaCount = 1 if pcmaListFN then print("") print("==[ADPCM-A Input Sample List]==") for l in pcmaListFile:lines() do -- try loading file tempFile,errorString = io.open(l,"rb") if not tempFile then print(string.format("Error attempting to load ADPCM-A sample %s",errorString)) return end -- get file length tempLen,errorString = tempFile:seek("end") if not tempLen then print(string.format("Error attempting to get length of ADPCM-A sample %s",errorString)) return end tempFile:seek("set") padMe = false if tempLen % 256 ~= 0 then sizeWarn = sizeWarnString padMe = true else sizeWarn = "" end tempData = tempFile:read(tempLen) tempFile:close() print(string.format("(PCMA %03i) %s %s",pcmaCount,l,sizeWarn)) if tempLen > (1024*1024) then print(string.format("WARNING: PCMA sample %03i is too large! (>1MB)",pcmaCount)) end if padMe then -- pad the sample with 0x80 local padBytes = 256-(tempLen%256) for i=1,padBytes do tempData = tempData .. string.char(128) end tempLen = tempLen + padBytes if tempLen > (1024*1024) then print(string.format("WARNING: PCMA sample %03i is too large after padding! (>1MB)",pcmaCount)) end end table.insert(pcmaFiles,pcmaCount,{ID=pcmaCount,File=l,Length=tempLen,Data=tempData}) pcmaCount = pcmaCount + 1 end pcmaListFile:close() end --============================================================================-- -- Time for ADPCM-B, but only if we have it. --[[ ADPCM-B List Parsing ]]-- local pcmbFiles = {} local pcmbCount = 0 local tempRate, tempRealFileName if pcmbListFN then pcmbCount = 1 print("") print("==[ADPCM-B Input Sample List]==") -- try opening list file pcmbListFile,errorString = io.open(pcmbListFN,"r") if not pcmbListFile then print(string.format("Error attempting to open ADPCM-B list %s",errorString)) return end for l in pcmbListFile:lines() do -- look for rate splitter character local rateSplitter = string.find(l,pcmbSeparator) if not rateSplitter then print(string.format("ADPCM-B sample %03i does not have a sample rate defined.",pcmbCount)) return end -- get actual filename tempRealFileName = string.sub(l,1,rateSplitter-1) -- get sample rate tempRate = tonumber(string.sub(l,rateSplitter+1)) if not tempRate then print(string.format("Error decoding sample rate from string '%s'",string.sub(l,rateSplitter+1))) end if tempRate < 1800 or tempRate > 55500 then print(string.format("ADPCM-B sample %s has invalid sampling rate %dHz, must be between 1800Hz and 55500Hz",tempRealFileName,tempRate)) return end -- try loading file tempFile,errorString = io.open(tempRealFileName,"rb") if not tempFile then print(string.format("Error attempting to load ADPCM-B sample %s",errorString)) return end -- get file length tempLen,errorString = tempFile:seek("end") if not tempLen then print(string.format("Error attempting to get length of ADPCM-B sample %s",errorString)) return end tempFile:seek("set") padMe = false if tempLen % 256 ~= 0 then sizeWarn = sizeWarnString padMe = true else sizeWarn = "" end tempData = tempFile:read(tempLen) tempFile:close() print(string.format("(PCMB %03i) %s (rate %d) %s",pcmbCount,tempRealFileName,tempRate,sizeWarn)) if padMe then -- pad the sample with 0x80 local padBytes = 256-(tempLen%256) for i=1,padBytes do tempData = tempData .. string.char(128) end tempLen = tempLen + padBytes end table.insert(pcmbFiles,pcmbCount,{ID=pcmbCount,File=tempRealFileName,Length=tempLen,Rate=tempRate,Data=tempData}) pcmbCount = pcmbCount + 1 end pcmbListFile:close() end print("") --============================================================================-- -- Determine sample bank layouts (a.k.a. try to avoid crossing 1MB boundaries) local curBankSize = 0 local curBankNum = 1 local curIndex = 1 local banksA = {} local banksB = {} -- handle ADPCM-A first if pcmaListFN then for k,v in pairs(pcmaFiles) do if not banksA[curBankNum] then table.insert(banksA,curBankNum,{}) end -- check if adding current file to bank would cause overflow if (v.Length + curBankSize) > 1024*1024 then print("------------------------------------------------") print(string.format("PCMA bank %d: add %s (overflow from bank %d)",curBankNum+1,v.File,curBankNum)) -- needs to go to next bank curBankNum = curBankNum + 1 curBankSize = v.Length curIndex = 1 if not banksA[curBankNum] then table.insert(banksA,curBankNum,{}) end table.insert(banksA[curBankNum],curIndex,v) curIndex = curIndex + 1 else -- add to current bank print(string.format("PCMA bank %d: add %s",curBankNum,v.File)) curBankSize = curBankSize + v.Length table.insert(banksA[curBankNum],curIndex,v) curIndex = curIndex + 1 end end end -- handle ADPCM-B next (if applicable) if pcmbListFN then curBankSize = 0 curIndex = 1 curBankNum = 1 for k,v in pairs(pcmbFiles) do if not banksB[curBankNum] then table.insert(banksB,curBankNum,{}) end -- ADPCM-B has no restrictions on sample sizes, according to datasheet -- add to current bank print(string.format("PCMB bank %d: add %s",curBankNum,v.File)) curBankSize = curBankSize + v.Length table.insert(banksB[curBankNum],curIndex,v) curIndex = curIndex + 1 end end print("") --============================================================================-- -- Read bank layouts and figure out required padding. local paddingA = {} if pcmaListFN then print("Reading ADPCM-A bank layouts...") curBankSize = 0 for k,v in pairs(banksA) do for i,d in pairs(v) do curBankSize = curBankSize + d.Length end print(string.format("size of ADPCM-A bank %d: %d bytes",k,curBankSize)) if curBankSize < 1024*1024 and k ~= #banksA then local diff = (1024*1024) - curBankSize print(string.format("Padding required: %d bytes",diff)) table.insert(paddingA,k,diff) end print("------------------------------------------------") curBankSize = 0 end end if pcmbListFN then print("Reading ADPCM-B bank layouts...") curBankSize = 0 for k,v in pairs(banksB) do for i,d in pairs(v) do curBankSize = curBankSize + d.Length end print(string.format("size of ADPCM-B bank %d: %d bytes",k,curBankSize)) print("------------------------------------------------") curBankSize = 0 end end print("") --============================================================================-- -- Create the combined sample rom using bank layout print("Creating combined sample data...") outSoundFile,errorString = io.open(outSoundFN,"w+b") if not outSoundFile then print(string.format("Error attempting to create output file %s",errorString)) return end -- ADPCM-A if pcmaListFN then for k,v in pairs(banksA) do -- write sounds in this bank print(string.format("Writing ADPCM-A bank %d...",k)) for i,d in pairs(v) do outSoundFile:write(d.Data) end if paddingA[k] and k ~= #banksA then print(string.format("Writing %d bytes of padding...",paddingA[k])) -- write padding for this bank for i=1,paddingA[k] do outSoundFile:write(string.char(128)) end end print("------------------------------------------------") end end if pcmbListFN then for k,v in pairs(banksB) do -- write sounds in this bank print("Writing ADPCM-B bank...") for i,d in pairs(v) do outSoundFile:write(d.Data) end print("------------------------------------------------") end end outSoundFile:close() print("") --============================================================================-- -- Get sample addresses (using banks to account for padding) local sampleStart = 0 if outSampleStart then sampleStart = outSampleStart end if pcmaListFN then print("Calculating ADPCM-A sample addresses...") -- ADPCM-A samples for k,v in pairs(banksA) do for i,d in pairs(v) do local fixedLen = (d.Length/256) d.Start = sampleStart d.End = (sampleStart+fixedLen)-1 sampleStart = sampleStart + fixedLen end if paddingA[k] and k ~= #banksA then sampleStart = sampleStart + (paddingA[k]/256) end end end -- ADPCM-B samples if pcmbListFN then print("Calculating ADPCM-B sample addresses...") for k,v in pairs(banksB) do for i,d in pairs(v) do local fixedLen = (d.Length/256) d.Start = sampleStart d.End = (sampleStart+fixedLen)-1 d.DeltaN = (d.Rate/55500)*65536 sampleStart = sampleStart + fixedLen end end end print("") --============================================================================-- -- create the sample address list print("Creating sample address list...") outSampleFile,errorString = io.open(outSampleFN,"w+") if not outSampleFile then print(string.format("Error attempting to create sample list file %s",errorString)) return end local direc = sampleListTypes[sampListType].Directive local valFormat = sampleListTypes[sampListType].Format -- write header outSampleFile:write("; Sample address list generated by Sailor VROM\n") outSampleFile:write(";==============================================;\n") outSampleFile:write("\n") -- write ADPCM-A if pcmaListFN then outSampleFile:write("; [ADPCM-A Samples]\n") outSampleFile:write("samples_PCMA:\n") for k,v in pairs(pcmaFiles) do outSampleFile:write(string.format("\t%s\t"..valFormat..","..valFormat.."\t; PCMA Sample #%i (%s)\n",direc,v.Start,v.End,v.ID,v.File)) end outSampleFile:write("\n") end -- write ADPCM-B, if applicable if pcmbListFN then outSampleFile:write("; [ADPCM-B Samples]\n") outSampleFile:write("samples_PCMB:\n") for k,v in pairs(pcmbFiles) do outSampleFile:write(string.format("\t%s\t"..valFormat..","..valFormat.."\t; PCMB Sample #%i (%s, %dHz)\n",direc,v.Start,v.End,v.ID,v.File,v.Rate)) end outSampleFile:write("\n") outSampleFile:write("; [ADPCM-B Default Sample Rates]\n") outSampleFile:write("rates_PCMB:\n") for k,v in pairs(pcmbFiles) do outSampleFile:write(string.format("\t%s\t"..valFormat.."\t; PCMB Sample #%i (%s, %dHz)\n",direc,v.DeltaN,v.ID,v.File,v.Rate)) end outSampleFile:write("\n") end outSampleFile:close() --============================================================================-- print("") print("Build successful.")
isc
nasomi/darkstar
scripts/zones/Ranguemont_Pass/npcs/Perchond.lua
19
1579
----------------------------------- -- Area: Ranguemont Pass -- NPC: Perchond -- @pos -182.844 4 -164.948 166 ----------------------------------- package.loaded["scripts/zones/Ranguemont_Pass/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1107,1) and trade:getItemCount() == 1) then -- glitter sand local SinHunting = player:getVar("sinHunting"); -- RNG AF1 if (SinHunting == 2) then player:startEvent(0x0005); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local SinHunting = player:getVar("sinHunting"); -- RNG AF1 if (SinHunting == 1) then player:startEvent(0x0003, 0, 1107); else player:startEvent(0x0002); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 3) then player:setVar("sinHunting",2); elseif (csid == 5) then player:tradeComplete(); player:addKeyItem(PERCHONDS_ENVELOPE); player:messageSpecial(KEYITEM_OBTAINED,PERCHONDS_ENVELOPE); player:setVar("sinHunting",3); end end;
gpl-3.0
nasomi/darkstar
scripts/zones/The_Garden_of_RuHmet/mobs/Jailer_of_Faith.lua
24
1296
----------------------------------- -- Area: The Garden of Ru'Hmet -- NPC: Jailer_of_Faith ----------------------------------- ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) -- Give it two hour mob:setMod(MOBMOD_MAIN_2HOUR, 1); -- Change animation to open mob:AnimationSub(2); end; ----------------------------------- -- onMobFight Action -- Randomly change forms ----------------------------------- function onMobFight(mob) -- Forms: 0 = Closed 1 = Closed 2 = Open 3 = Closed local randomTime = math.random(45,180); local changeTime = mob:getLocalVar("changeTime"); if (mob:getBattleTime() - changeTime > randomTime) then -- Change close to open. if (mob:AnimationSub() == 1) then mob:AnimationSub(2); else -- Change from open to close mob:AnimationSub(1); end mob:setLocalVar("changeTime", mob:getBattleTime()); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer, npc) local qm3 = GetNPCByID(Jailer_of_Faith_QM); qm3:hideNPC(900); local qm3position = math.random(1,5); qm3:setPos(Jailer_of_Faith_QM_POS[qm3position][1], Jailer_of_Faith_QM_POS[qm3position][2], Jailer_of_Faith_QM_POS[qm3position][3]); end;
gpl-3.0
luanorlandi/SwiftSpaceBattle
src/menu/data.lua
2
9031
require "menu/languageArray" local languageArray = getLanguageArraySorted() MenuData = {} MenuData.__index = MenuData function MenuData:new() local M = {} setmetatable(M, MenuData) M.active = true M.textBoxPos = {} M.textBoxSelected = 0 M.pageLimit = 8 M.menuFunction = {} M.resolutionsAvailable = readResolutionsFile() return M end function MenuData:checkSelection() local selection = false local i = 1 if MOAIEnvironment.osBrand ~= "Android" or input.pointerPressed then -- search in each label box which one is selected while i <= #self.textBoxPos and not selection do if self.textBoxPos[i]:pointInside(input.pointerPos) then if i ~= self.textBoxSelected then if self.textBoxSelected ~= 0 then interface.textTable[self.textBoxSelected]:removeSelection() end self.textBoxSelected = i interface.textTable[self.textBoxSelected]:selection() end selection = true else i = i + 1 end end end if not selection and self.textBoxSelected ~= 0 then interface.textTable[self.textBoxSelected]:removeSelection() self.textBoxSelected = 0 end end function MenuData:checkPressed() -- check if any click/tap happened if input.pointerReleased then input.pointerReleased = false -- check if there is something selected if self.textBoxSelected ~= 0 then -- make the menu function selected self.menuFunction[self.textBoxSelected](self) end end end function MenuData:createMainMenu() -- clear previous menu, if any self:clearMenu() if(MOAIEnvironment.osBrand == "Windows") then local texts = {} -- has the menu strings table.insert(texts, strings.menu.play) table.insert(texts, strings.menu.score) table.insert(texts, strings.menu.options) table.insert(texts, strings.menu.about) table.insert(texts, strings.menu.quit) -- create a new menu interface:createMenu(texts) -- create the label boxes to allow selection self:createBoxesMenu(5) -- define what each menu item will do table.insert(self.menuFunction, function() self:newGame() end) table.insert(self.menuFunction, function() self:createScoreMenu() end) table.insert(self.menuFunction, function() self:createOptionsMenu() end) table.insert(self.menuFunction, function() os.execute("start " .. strings.url) end) table.insert(self.menuFunction, function() self:exitGame() end) elseif(MOAIEnvironment.osBrand == "Android") then local texts = {} -- has the menu strings table.insert(texts, strings.menu.play) table.insert(texts, strings.menu.score) table.insert(texts, strings.menu.options) table.insert(texts, strings.menu.about) table.insert(texts, strings.menu.quit) -- create a new menu interface:createMenu(texts) -- create the label boxes to allow selection self:createBoxesMenu(5) -- define what each menu item will do table.insert(self.menuFunction, function() self:newGame() end) table.insert(self.menuFunction, function() self:createScoreMenu() end) table.insert(self.menuFunction, function() self:createOptionsMenu() end) table.insert(self.menuFunction, function() if(MOAIBrowserAndroid.canOpenURL(strings.url)) then MOAIBrowserAndroid.openURL(strings.url) end end) table.insert(self.menuFunction, function() self:exitGame() end) else -- probably html host local texts = {} -- has the menu strings table.insert(texts, strings.menu.play) table.insert(texts, strings.menu.score) table.insert(texts, strings.menu.options) -- create a new menu interface:createMenu(texts) -- create the label boxes to allow selection self:createBoxesMenu(3) -- define what each menu item will do table.insert(self.menuFunction, function() self:newGame() end) table.insert(self.menuFunction, function() self:createScoreMenu() end) table.insert(self.menuFunction, function() self:createOptionsMenu() end) end end function MenuData:createScoreMenu() self:clearMenu() local score = readScoreFile() local texts = {} table.insert(texts, score) table.insert(texts, strings.menu.back) interface:createMenu(texts) interface.textTable[1].selectable = false self:createBoxesMenu(2) table.insert(self.menuFunction, function() end) table.insert(self.menuFunction, function() self:createMainMenu() end) end function MenuData:createOptionsMenu() self:clearMenu() if MOAIEnvironment.osBrand == "Windows" then local width = math.floor(window.width) local height = math.floor(window.height) local texts = {} table.insert(texts, strings.menu.resolution .. " (" .. width .. "x" .. height .. ")") table.insert(texts, strings.menu.language) table.insert(texts, strings.menu.back) interface:createMenu(texts) self:createBoxesMenu(3) table.insert(self.menuFunction, function() self:createResolutionsMenu() end) table.insert(self.menuFunction, function() self:createLanguagesMenu(1, 1) end) table.insert(self.menuFunction, function() self:createMainMenu() end) else local texts = {} table.insert(texts, strings.menu.language) table.insert(texts, strings.menu.back) interface:createMenu(texts) self:createBoxesMenu(2) table.insert(self.menuFunction, function() self:createLanguagesMenu(1, 1) end) table.insert(self.menuFunction, function() self:createMainMenu() end) end end function MenuData:createResolutionsMenu() self:clearMenu() -- table with all label that appears in the menu local resolutionsTexts = {} -- label with no action table.insert(self.menuFunction, function() end) table.insert(resolutionsTexts, strings.menu.restart) for i = 1, #self.resolutionsAvailable, 1 do table.insert(self.menuFunction, function() writeResolutionFile(self.resolutionsAvailable[i]) self:createOptionsMenu() end) local width = math.floor(self.resolutionsAvailable[i].x) local height = math.floor(self.resolutionsAvailable[i].y) table.insert(resolutionsTexts, width .. "x" .. height) end -- include the back button at the end table.insert(self.menuFunction, function() self:createOptionsMenu() end) table.insert(resolutionsTexts, strings.menu.back) -- add 1 for the initial label of restart note self:createBoxesMenu(1 + #resolutionsTexts) interface:createMenu(resolutionsTexts) -- set the initial label of restart note to not be selectable interface.textTable[1].selectable = false end function MenuData:createLanguagesMenu(page, firstText) self:clearMenu() -- table with all label that appears in the menu local languagesTexts = {} lastText = math.min(firstText + self.pageLimit - 3, #languageArray) -- check to insert up button if firstText > 1 then local previousPageLastText if(firstText - self.pageLimit + 2 > 1 ) then -- count up button previousPageLastText = firstText - self.pageLimit + 3 else previousPageLastText = firstText - self.pageLimit + 2 end table.insert(self.menuFunction, function() self:createLanguagesMenu(page - 1, previousPageLastText) end) table.insert(languagesTexts, strings.button.up) lastText = lastText - 1 end -- insert language change buttons for i = firstText, lastText do local ISO = languageArray[i].ISO local text = language[ISO].name table.insert(self.menuFunction, function() writeLanguageFile(ISO) -- save ISO changeLanguage(ISO) self:createOptionsMenu() end) table.insert(languagesTexts, language[ISO].name) end -- check to insert down button if(firstText + self.pageLimit - 2 < #languageArray) then table.insert(self.menuFunction, function() self:createLanguagesMenu(page + 1, lastText + 1) end) table.insert(languagesTexts, strings.button.down) end -- include the back button at the end table.insert(self.menuFunction, function() self:createOptionsMenu() end) table.insert(languagesTexts, strings.menu.back) self:createBoxesMenu(#languagesTexts) interface:createMenu(languagesTexts) end function MenuData:createBoxesMenu(n) -- create 'n' label boxes to selection for i = 1, n, 1 do local center = Vector:new(0, interface.textStart - (i - 1) * interface.textGap) local box = Rectangle:new(center, Vector:new(window.width / 2, interface.textSize / 2)) table.insert(self.textBoxPos, box) end end function MenuData:createBoxesMenuCustomStart(start, n) -- create 'n' label boxes to selection -- starting at 'start' for i = 1, n, 1 do local center = Vector:new(0, start - (i - 1) * interface.textGap) local box = Rectangle:new(center, Vector:new(window.width / 2, interface.textSize / 2)) table.insert(self.textBoxPos, box) end end function MenuData:newGame() self.active = false interface:clear() local gameThread = MOAICoroutine.new() gameThread:run(gameLoop) end function MenuData:exitGame() os.exit(0) end function MenuData:clearMenu() interface:clearMenu() self.textBoxSelected = 0 for i = 1, #self.textBoxPos, 1 do table.remove(self.textBoxPos, 1) end for i = 1, #self.menuFunction, 1 do table.remove(self.menuFunction, 1) end end
gpl-3.0
nasomi/darkstar
scripts/globals/items/truelove_chocolate.lua
35
1232
----------------------------------------- -- ID: 5231 -- Item: truelove_chocolate -- Food Effect: 4Hrs, All Races ----------------------------------------- -- MP 10 -- MP Recovered While Healing 4 ----------------------------------------- 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,5231); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 10); target:addMod(MOD_MPHEAL, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 10); target:delMod(MOD_MPHEAL, 4); end;
gpl-3.0
Peixinho/Pyros3D
otherplatforms/raspberry-pi/premake4.lua
1
6190
------------------------------------------------------------------ -- premake 4 Pyros3D solution ------------------------------------------------------------------ solution "Pyros3D" newoption { trigger = "shared", description = "Ouput Shared Library" } newoption { trigger = "static", description = "Ouput Static Library - Default Option" } newoption { trigger = "examples", description = "Build Demos Examples" } newoption { trigger = "log", value = "OUTPUT", description = "Log Output", allowed = { { "none", "No log - Default" }, { "console", "Log to Console"}, { "file", "Log to File"} } } framework = "_SDL2"; libsToLink = { "SDL2", "SDL2_mixer" } excludes { "**/SFML/**", "**/SDL/**" } buildArch = "native" libsToLinkGL = { "GLESv2" } ------------------------------------------------------------------ -- setup common settings ------------------------------------------------------------------ configurations { "Debug", "Release" } platforms { buildArch } location "build" rootdir = "../../" libName = "PyrosEngine" project "PyrosEngine" targetdir "../../libs" if _OPTIONS["shared"] then kind "SharedLib" else kind "StaticLib" end language "C++" files { "../../src/**.h", "../../src/**.cpp", "../../include/Pyros3D/**.h" } includedirs { "../../include/", "/usr/local/include/SDL2", "/opt/vc/include/", "/usr/include/freetype2", "/usr/include/bullet" } defines({"GLES2", "UNICODE", "LODEPNG", framework }) if _OPTIONS["log"]=="console" then defines({"LOG_TO_CONSOLE"}) else if _OPTIONS["log"]=="file" then defines({"LOG_TO_FILE"}) else defines({"LOG_DISABLE"}) end end configuration "Debug" targetname(libName.."d") defines({"_DEBUG"}) flags { "Symbols" } configuration "Release" flags { "Optimize" } targetname(libName) project "AssimpImporter" targetdir "../../bin/tools" kind "ConsoleApp" language "C++" files { "../../tools/AssimpImporter/src/**.h", "../../tools/AssimpImporter/src/**.cpp" } includedirs { "../../include/", "/usr/local/include/SDL2", "/opt/vc/include/", "/usr/include/freetype2", "/usr/include/bullet" } defines({"UNICODE"}) defines({"LOG_DISABLE"}) configuration "Debug" defines({"_DEBUG"}) targetdir ("../../bin/tools/") links { libName.."d", libsToLinkGL, libsToLink, "assimp", "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "z" } linkoptions { "-L../libs -L/opt/vc/lib -L/usr/local/lib -Wl,-rpath,../../../../libs" } flags { "Symbols" } configuration "Release" targetdir ("../../bin/tools/") links { libName, libsToLinkGL, libsToLink, "assimp", "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "pthread", "z" } linkoptions { "-L../libs -L/opt/vc/lib -L/usr/local/lib -Wl,-rpath,../../../../libs" } flags { "Optimize" } function BuildDemo(demoPath, demoName) project (demoName) kind "ConsoleApp" language "C++" files { "../../"..demoPath.."/**.h", "../../"..demoPath.."/**.cpp", "../../"..demoPath.."/../WindowManagers/SDL2/**.cpp", "../../"..demoPath.."/../WindowManagers/**.h", "../../"..demoPath.."/../MainProgram.cpp" } includedirs { "../../include/", "/usr/local/include/SDL2", "/opt/vc/include/", "/usr/include/freetype2", "/usr/include/bullet" } defines({framework, "GLES2", "DEMO_NAME="..demoName, "_"..demoName, "UNICODE"}) configuration "Debug" defines({"_DEBUG"}) targetdir ("../../bin/") links { libName.."d", libsToLinkGL, libsToLink, "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "z" } linkoptions { "-L../../libs -L/opt/vc/lib -L/usr/local/lib -Wl,-rpath,../../../../libs" } flags { "Symbols" } configuration "Release" targetdir ("../../bin/") links { libName, libsToLinkGL, libsToLink, "BulletDynamics", "BulletCollision", "LinearMath", "freetype", "pthread", "z" } linkoptions { "-L../../libs -L/opt/vc/lib -L/usr/local/lib -Wl,-rpath,../../../../libs" } flags { "Optimize" } end; if _OPTIONS["examples"] then BuildDemo("examples/RotatingCube", "RotatingCube"); BuildDemo("examples/RotatingTexturedCube", "RotatingTexturedCube"); BuildDemo("examples/RotatingTextureAnimatedCube", "RotatingTextureAnimatedCube"); BuildDemo("examples/RotatingCubeWithLighting", "RotatingCubeWithLighting"); BuildDemo("examples/RotatingCubeWithLightingAndShadow", "RotatingCubeWithLightingAndShadow"); BuildDemo("examples/SimplePhysics", "SimplePhysics"); BuildDemo("examples/TextRendering", "TextRendering"); BuildDemo("examples/CustomMaterial", "CustomMaterial"); BuildDemo("examples/PickingPainterMethod", "PickingPainterMethod"); BuildDemo("examples/SkeletonAnimationExample", "SkeletonAnimationExample"); BuildDemo("examples/DepthOfField", "DepthOfField"); BuildDemo("examples/SSAOExample", "SSAOExample"); BuildDemo("examples/DeferredRendering", "DeferredRendering"); BuildDemo("examples/LOD_example", "LOD_example"); BuildDemo("examples/Decals", "Decals"); BuildDemo("examples/IslandDemo", "IslandDemo"); BuildDemo("examples/ParallaxMapping", "ParallaxMapping"); --BuildDemo("examples/MotionBlur", "MotionBlur"); if _OPTIONS["lua"] then BuildDemo("examples/LuaScripting", "LuaScripting"); end -- ImGui Example only works with SFML for now if framework ~= "SDL" or not "SDL2" then BuildDemo("examples/RacingGame", "RacingGame"); BuildDemo("examples/ImGuiExample", "ImGuiExample"); end end
mit
PolyCement/dotfiles
awesome/monitors/volmon.lua
1
1785
-- volmon.lua -- an awesome wm plugin that uses pactl subscribe to watch for changes to the default sink state -- this allows the volume widget to update as volume changes instead of relying on a timer local awful = require("awful") -- tracking for registered widgets local registered_widgets = {} local volmon = {} -- get the volume info, then run the callback local cmd = "DEFAULT_SINK=$(pactl get-default-sink); " .. "pactl get-sink-mute $DEFAULT_SINK; pactl get-sink-volume $DEFAULT_SINK" local with_volume_info = function (callback) awful.spawn.easy_async_with_shell(cmd, function(stdout, stderr, reason, exit_code) local mute, vol = stdout:match("Mute: (%a+).*%s(%d+)%%.*") callback(tonumber(vol), mute == "yes") end) end local update_all_widgets = function () with_volume_info(function (mute, vol) for widget, format in pairs(registered_widgets) do widget:set_text(format(mute, vol)) end end) end -- register a widget to be updated by volmon volmon.register = function (w, format) registered_widgets[w] = format or "%s" end -- call this to start listening volmon.start = function () -- monitor pactl for change events and update whenever one happens awful.spawn.with_line_callback("pactl subscribe", { stdout = function (line) -- this will trigger on change events for *any* sink, -- but checking it's the default one requires an extra call so i'd rather not if not (line:find("Event 'change' on sink #") == nil) then update_all_widgets() end end }) -- gotta run it one time to set its initial value with_volume_info(function (mute, vol) update_all_widgets() end) end return volmon
mit
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/resistance_torso_knife_prim_return_3.meta.lua
2
2801
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.40000000596046448, amplification = 100, light_colors = { "223 113 38 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = 2, y = 13 }, rotation = -114.44395446777344 }, head = { pos = { x = 0, y = -1 }, rotation = -40.855377197265625 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = -25, y = -24 }, rotation = -25 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 14, y = -15 }, rotation = 71.565048217773438 }, shoulder = { pos = { x = -21, y = 3 }, rotation = 71.565048217773438 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
RhenaudTheLukark/CreateYourFrisk
Assets/Mods/Examples/Lua/Libraries/randomvoice.lua
2
2133
-- A library to add random voices to every letter in a dialogue. -- First, we make a new table for our random voices and our module. local voices = {} -- This will contain the voices we're going to use. Only accessible from within this library. local randomvoicer = {} -- The actual module. -- You can change your voices from your own scripts with this. See the actual encounter for usage. function randomvoicer.setvoices(table) voices = table end -- This randomizes all lines in a table. function randomvoicer.randomizetable(table) for i=1,#table do table[i] = randomvoicer.randomizeline(table[i]) end return table end -- This function will take care of inserting a random voice in front of every letter. function randomvoicer.randomizeline(text) local skipping = false -- We will use this variable to stop inserting voices when we find [ and continue when we find ], otherwise we'll screw up commands. -- First, we can just skip the whole thing if there aren't any voices. if #voices == 0 then return text end -- Now we can go over every letter in the text, and add a voice to it. local temptext = "" for i=1,#text do local nextletter = text:sub(i,i) -- Get the next letter. if nextletter == "[" then -- Start skipping text when we encounter a command. skipping = true elseif nextletter == "]" then -- We can stop skipping again when the command is over. skipping = false elseif skipping == false then -- If we aren't skipping, we can insert random voices. temptext = temptext .. randomvoicer.voice() -- Adds a random voice to the temporary string. end temptext = temptext .. nextletter -- In all cases, we should include the next letter of the string. end return temptext -- Don't forget to return the modified text. end -- This returns a random voice command depending on what voices you have set here. function randomvoicer.voice() if #voices == 0 then return "" end return "[voice:" .. voices[math.random(#voices)] .. "]" end return randomvoicer
gpl-3.0
mpub/mp_lightroom
mp.lrplugin/dkjson.lua
17
25626
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.3* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.3"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local concat = table.concat local json = { version = "dkjson 2.3" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = tostring (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = tonumber (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") local pegmatch = g.match local P, S, R, V = g.P, g.S, g.R, g.V local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/tonumber local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
mit
shangjiyu/luci-with-extra
modules/luci-mod-rpc/luasrc/controller/rpc.lua
37
4466
-- 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. local require = require local pairs = pairs local print = print local pcall = pcall local table = table module "luci.controller.rpc" function index() local function authenticator(validator, accs) local auth = luci.http.formvalue("auth", true) if auth then -- if authentication token was given local sdat = (luci.util.ubus("session", "get", { ubus_rpc_session = auth }) or { }).values if sdat then -- if given token is valid if sdat.user and luci.util.contains(accs, sdat.user) then return sdat.user, auth end end end luci.http.status(403, "Forbidden") end local rpc = node("rpc") rpc.sysauth = "root" rpc.sysauth_authenticator = authenticator rpc.notemplate = true entry({"rpc", "uci"}, call("rpc_uci")) entry({"rpc", "fs"}, call("rpc_fs")) entry({"rpc", "sys"}, call("rpc_sys")) entry({"rpc", "ipkg"}, call("rpc_ipkg")) entry({"rpc", "auth"}, call("rpc_auth")).sysauth = false end function rpc_auth() local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local sys = require "luci.sys" local ltn12 = require "luci.ltn12" local util = require "luci.util" local loginstat local server = {} server.challenge = function(user, pass) local sid, token, secret local config = require "luci.config" if sys.user.checkpasswd(user, pass) then local sdat = util.ubus("session", "create", { timeout = config.sauth.sessiontime }) if sdat then sid = sdat.ubus_rpc_session token = sys.uniqueid(16) secret = sys.uniqueid(16) http.header("Set-Cookie", "sysauth="..sid.."; path=/") util.ubus("session", "set", { ubus_rpc_session = sid, values = { user = user, token = token, secret = secret } }) end end return sid and {sid=sid, token=token, secret=secret} end server.login = function(...) local challenge = server.challenge(...) return challenge and challenge.sid end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(server, http.source()), http.write) end function rpc_uci() if not pcall(require, "luci.model.uci") then luci.http.status(404, "Not Found") return nil end local uci = require "luci.jsonrpcbind.uci" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(uci, http.source()), http.write) end function rpc_fs() local util = require "luci.util" local io = require "io" local fs2 = util.clone(require "nixio.fs") local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" function fs2.readfile(filename) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local fp = io.open(filename) if not fp then return nil end local output = {} local sink = ltn12.sink.table(output) local source = ltn12.source.chain(ltn12.source.file(fp), mime.encode("base64")) return ltn12.pump.all(source, sink) and table.concat(output) end function fs2.writefile(filename, data) local stat, mime = pcall(require, "mime") if not stat then error("Base64 support not available. Please install LuaSocket.") end local file = io.open(filename, "w") local sink = file and ltn12.sink.chain(mime.decode("base64"), ltn12.sink.file(file)) return sink and ltn12.pump.all(ltn12.source.string(data), sink) or false end http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(fs2, http.source()), http.write) end function rpc_sys() local sys = require "luci.sys" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(sys, http.source()), http.write) end function rpc_ipkg() if not pcall(require, "luci.model.ipkg") then luci.http.status(404, "Not Found") return nil end local ipkg = require "luci.model.ipkg" local jsonrpc = require "luci.jsonrpc" local http = require "luci.http" local ltn12 = require "luci.ltn12" http.prepare_content("application/json") ltn12.pump.all(jsonrpc.handle(ipkg, http.source()), http.write) end
apache-2.0
OpenPrograms/payonel-Programs
psh/etc/rc.d/pshd.lua
1
2686
local term = require("term") local daemon = require("psh.daemon") local psh = require("psh") local vtcolors = { black = 30, red = 31, green = 32, yellow = 33, blue = 34, magenta = 35, cyan = 36, white = 37 } local function mkcolor(color) if io.stdout.tty and term.isAvailable() then return string.format("\27[%dm", color) else return "" end end local function serviceStatusPrint(startColor, msg, callback, statusMsgOk, statusMsgFail, ...) local spacem = ' ' io.write(spacem) io.write(mkcolor(startColor)) io.write('*') io.write(mkcolor(vtcolors.white)) io.write(spacem) io.write(msg) local bCallbackResult = callback local additionalMessages = {} if type(callback) == "boolean" then bCallbackResult = callback elseif callback then local result = table.pack(callback(...)) bCallbackResult = table.remove(result, 1) additionalMessages = result end if bCallbackResult and not statusMsgOk then print() return end if not bCallbackResult and not statusMsgFail then print() return end local statusColor = mkcolor(bCallbackResult and vtcolors.green or vtcolors.red) local statusMsg = bCallbackResult and statusMsgOk or statusMsgFail local startMsgLen = spacem:len() * 2 + 1 + msg:len() local openm = '[' .. spacem local closem = spacem .. '] ' local slen = openm:len() + statusMsg:len() + closem:len() local screenWidth = io.stdout.tty and term.isAvailable() and term.getViewport() or 0 local numSpaces = math.max(1, screenWidth - startMsgLen - slen) io.write(string.rep(' ', numSpaces)) io.write(mkcolor(vtcolors.blue)) io.write(openm) io.write(statusColor) io.write(statusMsg) io.write(mkcolor(vtcolors.blue)) io.write(closem) io.write(mkcolor(vtcolors.white)) print() -- if additional messages were returned by the callback for _,m in ipairs(additionalMessages) do serviceStatusPrint(vtcolors.red, m, true) end end local function checkDaemon() return daemon.status() == "running" end --luacheck: globals status function status() serviceStatusPrint(vtcolors.green, "pshd", checkDaemon, "started", "stopped") end --luacheck: globals start function start() if checkDaemon() then serviceStatusPrint(vtcolors.yellow, "WARNING: pshd has already been started") else serviceStatusPrint(vtcolors.green, "Starting pshd ...", daemon.start, "ok", "failed", psh.port) end end --luacheck: globals stop function stop() if not checkDaemon() then serviceStatusPrint(vtcolors.yellow, "WARNING: pshd is already stopped") else serviceStatusPrint(vtcolors.green, "Stopping pshd ...", daemon.stop, "ok", "failed") end end
mit
shakfu/start-vm
config/base/awesome/vicious/widgets/bat.lua
11
2922
--------------------------------------------------- -- Licensed under the GNU General Public License v2 -- * (c) 2010, Adrian C. <anrxc@sysphere.org> -- * (c) 2013, NormalRa <normalrawr@gmail.com> --------------------------------------------------- -- {{{ Grab environment local tonumber = tonumber local setmetatable = setmetatable local string = { format = string.format } local helpers = require("vicious.helpers") local math = { min = math.min, floor = math.floor } -- }}} -- Bat: provides state, charge, remaining time, and wear for a requested battery -- vicious.widgets.bat local bat = {} -- {{{ Battery widget type local function worker(format, warg) if not warg then return end local battery = helpers.pathtotable("/sys/class/power_supply/"..warg) local battery_state = { ["Full\n"] = "↯", ["Unknown\n"] = "⌁", ["Charged\n"] = "↯", ["Charging\n"] = "+", ["Discharging\n"] = "−" } -- Check if the battery is present if battery.present ~= "1\n" then return {battery_state["Unknown\n"], 0, "N/A", 0} end -- Get state information local state = battery_state[battery.status] or battery_state["Unknown\n"] -- Get capacity information if battery.charge_now then remaining, capacity = battery.charge_now, battery.charge_full capacity_design = battery.charge_full_design or capacity elseif battery.energy_now then remaining, capacity = battery.energy_now, battery.energy_full capacity_design = battery.energy_full_design or capacity else return {battery_state["Unknown\n"], 0, "N/A", 0} end -- Calculate capacity and wear percentage (but work around broken BAT/ACPI implementations) local percent = math.min(math.floor(remaining / capacity * 100), 100) local wear = math.floor(100 - capacity / capacity_design * 100) -- Get charge information if battery.current_now then rate = tonumber(battery.current_now) elseif battery.power_now then rate = tonumber(battery.power_now) else return {state, percent, "N/A", wear} end -- Calculate remaining (charging or discharging) time local time = "N/A" if rate ~= nil and rate ~= 0 then if state == "+" then timeleft = (tonumber(capacity) - tonumber(remaining)) / tonumber(rate) elseif state == "−" then timeleft = tonumber(remaining) / tonumber(rate) else return {state, percent, time, wear} end -- Calculate time local hoursleft = math.floor(timeleft) local minutesleft = math.floor((timeleft - hoursleft) * 60 ) time = string.format("%02d:%02d", hoursleft, minutesleft) end return {state, percent, time, wear} end -- }}} return setmetatable(bat, { __call = function(_, ...) return worker(...) end })
mit
Hello23-Ygopro/ygopro-ds
expansions/script/c27001058.lua
1
1091
--BT1-051 Result of Training local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) --give skill ds.AddActivateMainSkill(c,0,LOCATION_HAND,scard.skop,scard.skcost,ds.hinttg,DS_EFFECT_FLAG_CARD_CHOOSE) end scard.dragon_ball_super_card=true scard.skcost=ds.PayEnergyCost(COLOR_BLUE,2,3) function scard.posfilter(c,e) return c:IsRest() and c:IsCanBeSkillTarget(e) end function scard.skop(e,tp,eg,ep,ev,re,r,rp) --ignore awaken condition local e1=Effect.CreateEffect(e:GetHandler()) e1:SetDescription(aux.Stringid(sid,1)) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(DS_SKILL_IGNORE_AWAKEN_CONDITION) e1:SetProperty(EFFECT_FLAG_PLAYER_TARGET+EFFECT_FLAG_CLIENT_HINT) e1:SetTargetRange(1,0) e1:SetReset(RESET_PHASE+PHASE_END) Duel.RegisterEffect(e1,tp) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TOACTIVE) local g=Duel.SelectMatchingCard(tp,ds.EnergyAreaFilter(scard.posfilter),tp,DS_LOCATION_ENERGY,0,0,4,nil,e) if g:GetCount()==0 then return end Duel.BreakEffect() Duel.SetTargetCard(g) Duel.SwitchPosition(g,DS_POS_FACEUP_ACTIVE) end
gpl-3.0
nasomi/darkstar
scripts/zones/Mount_Zhayolm/npcs/qm2.lua
16
1161
----------------------------------- -- Area: Mount Zhayolm -- NPC: ??? (Spawn Claret(ZNM T1)) -- @pos 497 -9 52 61 ----------------------------------- package.loaded["scripts/zones/Mount_Zhayolm/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mount_Zhayolm/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(2591,1) and trade:getItemCount() == 1) then -- Trade Pectin player:tradeComplete(); SpawnMob(17027472,180):updateClaim(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Port_Windurst/npcs/Erabu-Fumulubu.lua
53
1835
----------------------------------- -- Area: Port Windurst -- NPC: Erabu-Fumulubu -- Type: Fishing Synthesis Image Support -- @pos -178.900 -2.789 76.200 240 ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,5); local SkillCap = getCraftSkillCap(player,SKILL_FISHING); local SkillLevel = player:getSkillLevel(SKILL_FISHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_FISHING_IMAGERY) == false) then player:startEvent(0x271C,SkillCap,SkillLevel,1,239,player:getGil(),0,0,0); -- p1 = skill level else player:startEvent(0x271C,SkillCap,SkillLevel,1,239,player:getGil(),19194,4031,0); end else player:startEvent(0x271C); -- Standard Dialogue 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 == 0x271C and option == 1) then player:messageSpecial(FISHING_SUPPORT,0,0,1); player:addStatusEffect(EFFECT_FISHING_IMAGERY,1,0,3600); end end;
gpl-3.0
rosejn/torch-datasets
dataset/TableDataset.lua
2
11696
require 'fn' require 'fn/seq' require 'util/arg' require 'dataset' require 'dataset/pipeline' require 'dataset/whitening' require 'pprint' local arg = util.arg local TableDataset = torch.class("dataset.TableDataset") -- Wraps a table containing a dataset to make it easy to transform the dataset -- and then sample from. Each property in the data table must have a tensor or -- table value, and then each sample will be retrieved by indexing these values -- and returning a single instance from each one. -- -- e.g. -- -- -- a 'dataset' of random samples with random class labels -- data_table = { -- data = torch.Tensor(10, 20, 20), -- classes = torch.randperm(10) -- } -- metadata = { name = 'random', classes = {1,2,3,4,5,6,7,8,9,10} } -- dataset = TableDataset(data_table, metadata) -- function TableDataset:__init(data_table, global_metadata) self.dataset = data_table global_metadata = global_metadata or {} self._name = global_metadata.name self._classes = global_metadata.classes or {} end -- Returns the number of samples in the dataset. function TableDataset:size() return self.dataset.data:size(1) end -- Returns the dimensions of a single sample as a table. -- e.g. -- mnist => {1, 28, 28} -- natural images => {3, 64, 64} function TableDataset:dimensions() local dims = self.dataset.data:size():totable() table.remove(dims, 1) return dims end -- Returns the total number of dimensions of a sample. -- e.g. -- mnist => 1*28*28 => 784 function TableDataset:n_dimensions() return fn.reduce(fn.mul, 1, self:dimensions()) end -- Returns the classes represented in this dataset (if available). function TableDataset:classes() return self._classes end -- Returns the string name of this dataset. function TableDataset:name() return self._name end -- Returns the specified sample (a table) by index. -- -- sample = dataset:sample(100) function TableDataset:sample(i) local sample = {} for key, v in pairs(self.dataset) do sample[key] = v[i] end return sample end local function animate(options, samples) local rotation = options.rotation or {} local translation = options.translation or {} local zoom = options.zoom or {} local frames = options.frames or 10 local scratch_a = torch.Tensor() local scratch_b = torch.Tensor() local function animate_sample(sample) local transformers = {} if (#rotation > 0) then local rot_start, rot_finish = dataset.rand_pair(rotation[1], rotation[2]) rot_start = rot_start * math.pi / 180 rot_finish = rot_finish * math.pi / 180 local rot_delta = (rot_finish - rot_start) / frames table.insert(transformers, dataset.rotator(rot_start, rot_delta)) end if (#translation > 0) then local xmin_tx, xmax_tx = dataset.rand_pair(translation[1], translation[2]) local ymin_tx, ymax_tx = dataset.rand_pair(translation[3], translation[4]) local dx = (xmax_tx - xmin_tx) / frames local dy = (ymax_tx - ymin_tx) / frames table.insert(transformers, dataset.translator(xmin_tx, ymin_tx, dx, dy)) end if (#zoom > 0) then local zoom_start, zoom_finish = dataset.rand_pair(zoom[1], zoom[2]) local zoom_delta = (zoom_finish - zoom_start) / frames table.insert(transformers, dataset.zoomer(zoom_start, zoom_delta)) end local original = sample.data scratch_a:resizeAs(sample.data) scratch_b:resizeAs(sample.data) return seq.repeatedly(frames, function() scratch_a:zero() local a = original local b = scratch_b for _, transform in ipairs(transformers) do transform(a, b) a = b if a == scratch_a then b = scratch_b else b = scratch_a end end sample.data = a return sample end) end return seq.mapcat(animate_sample, samples) end -- Returns an infinite sequence of data samples. By default they -- are shuffled samples, but you can turn shuffling off. -- -- for sample in seq.take(1000, dataset:sampler()) do -- net:forward(sample.data) -- end -- -- -- turn off shuffling -- sampler = dataset:sampler({shuffled = false}) -- -- -- generate animations over 10 frames for each sample, which will -- -- randomly rotate, translate, and/or zoom within the ranges passed. -- local anim_options = { -- frames = 10, -- rotation = {-20, 20}, -- translation = {-5, 5, -5, 5}, -- zoom = {0.6, 1.4} -- } -- s = dataset:sampler({animate = anim_options}) -- -- -- pass a custom pipeline for post-processing samples -- s = dataset:sampler({pipeline = my_pipeline}) -- function TableDataset:sampler(options) options = options or {} local shuffled = arg.optional(options, 'shuffled', true) local indices local size = self:size() local pipeline, pipe_size = pipe.construct_pipeline(options) local function make_sampler() if shuffled then indices = torch.randperm(size) else indices = seq.range(size) end local sample_seq = seq.map(fn.partial(self.sample, self), indices) if options.animate then sample_seq = animate(options.animate, sample_seq) end if pipe_size > 0 then sample_seq = seq.map(pipeline, sample_seq) end if options.pipeline then sample_seq = seq.map(options.pipeline, sample_seq) end return sample_seq end return seq.flatten(seq.cycle(seq.repeatedly(make_sampler))) end -- Returns the mini batch starting at the i-th example. -- Use options.size to specify the mini batch size. -- -- local batch = dataset:mini_batch(1) -- -- -- or use directly -- net:forward(dataset:mini_batch(1).data) -- -- -- set the batch size using an options table -- local batch = dataset:mini_batch(1, {size = 100}) -- -- -- or get batch as a sequence of samples, rather than a full tensor -- for sample in dataset:mini_batch(1, {sequence = true}) do -- net:forward(sample.data) -- end function TableDataset:mini_batch(i, options) options = options or {} local batch_size = arg.optional(options, 'size', 10) local as_seq = arg.optional(options, 'sequence', false) local batch = {} if as_seq then return seq.map(fn.partial(self.sample, self), seq.range(i, i + batch_size-1)) else for key, v in pairs(self.dataset) do batch[key] = v:narrow(1, i, batch_size) end return batch end end -- Returns a random mini batch consisting of a table of tensors. -- -- local batch = dataset:random_mini_batch() -- -- -- or use directly -- net:forward(dataset:random_mini_batch().data) -- -- -- set the batch size using an options table -- local batch = dataset:random_mini_batch({size = 100}) -- -- -- or get batch as a sequence of samples, rather than a full tensor -- for sample in dataset:random_mini_batch({sequence = true}) do -- net:forward(sample.data) -- end function TableDataset:random_mini_batch(options) options = options or {} local batch_size = arg.optional(options, 'size', 10) -- sequence option handled in TableDataset:mini_batch return self:mini_batch(torch.random(1, self:size() - batch_size + 1), options) end -- Returns a finite sequence of mini batches. -- The sequence provides each non-overlapping mini batch once. -- -- -- default options returns contiguous tensors of batch size 10 -- for batch in dataset:mini_batches() do -- net:forward(batch.data) -- end -- -- -- It's also possible to set the size, and/or get the batch as a sequence of -- -- individual samples. -- for batch in (seq.take(N_BATCHES, dataset:mini_batches({size = 100, sequence=true})) do -- for sample in batch do -- net:forward(sample.data) -- end -- end -- function TableDataset:mini_batches(options) options = options or {} local shuffled = arg.optional(options, 'shuffled', true) local mb_size = arg.optional(options, 'size', 10) local indices local size = self:size() if shuffled then indices = torch.randperm(size / mb_size) else indices = seq.range(size / mb_size) end return seq.map(function(i) return self:mini_batch((i-1) * mb_size + 1, options) end, indices) end -- Returns the sequence of frames corresponding to a specific sample's animation. -- -- for frame,label in m:animation(1) do -- local img = frame:unfold(1,28,28) -- win = image.display({win=win, image=img, zoom=10}) -- util.sleep(1 / 24) -- end -- function TableDataset:animation(i) local start = ((i-1) * self.frames) + 1 return self:mini_batch(start, self.frames, {sequence = true}) end -- Returns a sequence of animations, where each animation is a sequence of -- samples. -- -- for anim in m:animations() do -- for frame,label in anim do -- local img = frame:unfold(1,28,28) -- win = image.display({win=win, image=img, zoom=10}) -- util.sleep(1 / 24) -- end -- end -- function TableDataset:animations(options) options = options or {} local shuffled = arg.optional(options, 'shuffled', true) local indices if shuffled then indices = torch.randperm(self.base_size) else indices = seq.range(self.base_size) end return seq.map(function(i) return self:animation(i) end, indices) end -- Return a pipeline source (i.e. a sequence of samples). function TableDataset:pipeline_source() return self:sampler({shuffled = false}) end local function channels(...) channels = {...} if #channels == 0 then for i = 1,self.dataset.data:size(2) do table.insert(channels, i) end end return channels end -- Binarize the dataset: set to 0 any pixel strictly below the threshold, set to 1 those -- above or equal to the threshold. -- -- The argument specifies the threshold value for 0. function TableDataset:binarize(threshold) local function binarize(x, threshold) x[x:lt(threshold)] = 0; x[x:ge(threshold)] = 1; return x end binarize(self.dataset.data, threshold) end -- Globally normalise the dataset (subtract mean and divide by std) -- -- The optional arguments specify the indices of the channels that should be -- normalized. If no channels are specified normalize across all channels. function TableDataset:normalize_globally(...) local function normalize(d) local mean = d:mean() local std = d:std() d:add(-mean):div(std) end local channels = {...} if #channels == 0 then dataset.normalize(self.dataset.data) else for _,c in ipairs(channels) do normalize(self.dataset.data[{ {}, c, {}, {} }]) end end end -- Apply ZCA whitening to dataset (one or more channels) -- -- The optional arguments specify the indices of the channels that should be -- normalized. If no channels are specified all channels are jointly whitened. function TableDataset:zca_whiten(...) local channels = {...} local P = {} local invP = {} if #channels == 0 then self.dataset.data, P, invP = dataset.zca_whiten(self.dataset.data) else for _,c in ipairs(channels) do self.dataset.data[{ {}, c, {}, {} }], P[c], invP[c] = dataset.zca_whiten(self.dataset.data[{ {}, c, {}, {} }]) end end return P, invP end
bsd-3-clause
nasomi/darkstar
scripts/globals/spells/stoneskin.lua
13
1358
----------------------------------------- -- Spell: Stoneskin ----------------------------------------- -- http://wiki.ffxiclopedia.org/wiki/Stoneskin -- Max 350 damage absorbed require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local pMod = (caster:getSkillLevel(ENHANCING_MAGIC_SKILL)/3)+caster:getStat(MOD_MND); local pAbs = 0; local pEquipMods = (caster:getMod(MOD_STONESKIN_BONUS_HP)); local duration = 300; if (pMod < 80) then pAbs = pMod; elseif (pMod <= 130) then pAbs = 2*pMod - 60; elseif (pMod > 130) then pAbs = 3*pMod - 190; end -- hard cap of 350 from natural power -- pAbs = utils.clamp(1, STONESKIN_CAP); This just always sets it to 350, let's use the actual value, shall we? pAbs = utils.clamp(pAbs, 1, STONESKIN_CAP); if (caster:hasStatusEffect(EFFECT_COMPOSURE) == true and caster:getID() == target:getID()) then duration = duration * 3; end local final = pAbs + pEquipMods; if (target:addStatusEffect(EFFECT_STONESKIN,final,0,duration)) then spell:setMsg(230); else spell:setMsg(MMSG_BUFF_FAIL); end return EFFECT_STONESKIN; end;
gpl-3.0
m13790115/eset
bot/seedbot.lua
1
11276
package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua' ..';.luarocks/share/lua/5.2/?/init.lua' package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so' require("./bot/utils") VERSION = '2' -- This function is called when tg receive a msg function on_msg_receive (msg) if not started then return end local receiver = get_receiver(msg) print (receiver) --vardump(msg) msg = pre_process_service_msg(msg) if msg_valid(msg) then msg = pre_process_msg(msg) if msg then match_plugins(msg) if redis:get("bot:markread") then if redis:get("bot:markread") == "on" then mark_read(receiver, ok_cb, false) end end end end end function ok_cb(extra, success, result) end function on_binlog_replay_end() started = true postpone (cron_plugins, false, 60*5.0) _config = load_config() -- load plugins plugins = {} load_plugins() end function msg_valid(msg) -- Don't process outgoing messages if msg.out then print('\27[36mNot valid: msg from us\27[39m') return false end -- Before bot was started if msg.date < now then print('\27[36mNot valid: old msg\27[39m') return false end if msg.unread == 0 then print('\27[36mNot valid: readed\27[39m') return false end if not msg.to.id then print('\27[36mNot valid: To id not provided\27[39m') return false end if not msg.from.id then print('\27[36mNot valid: From id not provided\27[39m') return false end if msg.from.id == our_id then print('\27[36mNot valid: Msg from our id\27[39m') return false end if msg.to.type == 'encr_chat' then print('\27[36mNot valid: Encrypted chat\27[39m') return false end if msg.from.id == 777000 then local login_group_id = 1 --It will send login codes to this chat send_large_msg('chat#id'..login_group_id, msg.text) end return true end -- function pre_process_service_msg(msg) if msg.service then local action = msg.action or {type=""} -- Double ! to discriminate of normal actions msg.text = "!!tgservice " .. action.type -- wipe the data to allow the bot to read service messages if msg.out then msg.out = false end if msg.from.id == our_id then msg.from.id = 0 end end return msg end -- Apply plugin.pre_process function function pre_process_msg(msg) for name,plugin in pairs(plugins) do if plugin.pre_process and msg then print('Preprocess', name) msg = plugin.pre_process(msg) end end return msg end -- Go over enabled plugins patterns. function match_plugins(msg) for name, plugin in pairs(plugins) do match_plugin(plugin, name, msg) end end -- Check if plugin is on _config.disabled_plugin_on_chat table local function is_plugin_disabled_on_chat(plugin_name, receiver) local disabled_chats = _config.disabled_plugin_on_chat -- Table exists and chat has disabled plugins if disabled_chats and disabled_chats[receiver] then -- Checks if plugin is disabled on this chat for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do if disabled_plugin == plugin_name and disabled then local warning = 'Plugin '..disabled_plugin..' is disabled on this chat' print(warning) send_msg(receiver, warning, ok_cb, false) return true end end end return false end function match_plugin(plugin, plugin_name, msg) local receiver = get_receiver(msg) -- Go over patterns. If one matches it's enough. for k, pattern in pairs(plugin.patterns) do local matches = match_pattern(pattern, msg.text) if matches then print("msg matches: ", pattern) if is_plugin_disabled_on_chat(plugin_name, receiver) then return nil end -- Function exists if plugin.run then -- If plugin is for privileged users only if not warns_user_not_allowed(plugin, msg) then local result = plugin.run(msg, matches) if result then send_large_msg(receiver, result) end end end -- One patterns matches return end end end -- DEPRECATED, use send_large_msg(destination, text) function _send_msg(destination, text) send_large_msg(destination, text) end -- Save the content of _config to config.lua function save_config( ) serialize_to_file(_config, './data/config.lua') print ('saved config into ./data/config.lua') end -- Returns the config from config.lua file. -- If file doesn't exist, create it. function load_config( ) local f = io.open('./data/config.lua', "r") -- If config.lua doesn't exist if not f then print ("Created new config file: data/config.lua") create_config() else f:close() end local config = loadfile ("./data/config.lua")() for v,user in pairs(config.sudo_users) do print("Allowed user: " .. user) end return config end -- Create a basic config.json file and saves it. function create_config( ) -- A simple config with basic plugins and ourselves as privileged user config = { enabled_plugins = { "onservice", "lockchat", "info", "pluginns", "inrealm", "ingroup", "inpm", "banhammer", "stats", "anti_spam", "owners", "feedback", "calc", "joke", "sms", "servise", "arabic_lock", "set", "get", "broadcast", "download_media", "invite", "leave_ban", "admin", "antilink", "antitag", "linkpv", "share", "poker", "add_plug", "lock_english", "tagall", "all", "music", "block", "time", "webshot", "spam", "location", "fosh", "google", "left", "support", }, sudo_users = {184111248},--Sudo users disabled_channels = {}, moderation = {data = 'data/moderation.json'}, about_text = [[ https://github.com/m13790115/eset.git ]], help_text_realm = [[ Realm Commands: !creategroup [Name] Create a group !createrealm [Name] Create a realm !setname [Name] Set realm name !setabout [GroupID] [Text] Set a group's about text !setrules [GroupID] [Text] Set a group's rules !lock [GroupID] [setting] Lock a group's setting !unlock [GroupID] [setting] Unock a group's setting !wholist Get a list of members in group/realm !who Get a file of members in group/realm !type Get group type !kill chat [GroupID] Kick all memebers and delete group !kill realm [RealmID] Kick all members and delete realm !addadmin [id|username] Promote an admin by id OR username *Sudo only !removeadmin [id|username] Demote an admin by id OR username *Sudo only !list groups Get a list of all groups !list realms Get a list of all realms !log Grt a logfile of current group or realm !broadcast [text] !broadcast Hello ! Send text to all groups Only sudo users can run this command !bc [group_id] [text] !bc 123456789 Hello ! This command will send text to [group_id] ]], help_text = [[ @AVENGERRS Commands list : 1-banhammer list ^ !kick [username|id] (کیک کردن شخص (حتی با ریپلی) !ban [ username|id] (بن کردن افراد (حتی با ریپلی) !unban [id] (انبن کردن افراد (همراه ایدی) !kickme خروج از گروه 2-Statistics list ^ !who لیست+ایدی همه اعضا !stats امار کلی گروه !modlist لیست مدیران گروه !banlist لیست اعضا بن شده 3-Rate Member ^ !setowner [id] (id ایجاد مدیر جدید (همراه !promote [username] (ایجاد ادمین جدید (همراه ریپلی) !demote [username] (برکنار کردن ادمین (همراه ریپلی) 4-General changes ^ !setname [name] ایجاد اسم جدید برای گروه !setphoto ایجاد عکس جدید برای پروفایل گروه !set rules <text> ایجاد قانون جدید برای گروه !set about <text> ایجاد درباره گروه !setflood [value] حساسیت به اسپم در گروه 5-View details ^ !about درباره گروه !rules قوانین گروه !settings دیدن تنظیمات فعلی گروه !help لیست دستورات ربات 6-Security Group ^ !lock member قفل ورود اعضا جدید !lock name قفل اسم گروه !lock bots قفل ورود ربات ها !lock leave قفل خروج=بن گروه !lock link قفل تبلیغات و لینک در گروه !lock tag قفل استفاده از # و @ در گروه !lock arabic قفل چت ممنوع گروه !unlock [member*name*bots*leave] [link*tag*arabic] باز کردن دستورات قفل شده 7-Fun time ^ !time country city ساعت کشور مورد نظر !loc country city مشخصات کشور و شهر مورد نظر !google سرچ مطلب مورد نظر از گوگل 8-Service Provider ^ !newlink ایجاد لینک جدید !link نمایش لینک گروه !linkpv فرستادن لینک گروه تو پیوی (حتما شماره ربات را سیو کنید) !invite username اضافه کردن شخص تو گروه (حتما شماره ربات را سیو کرده باشد) 9-Member Profile and Group ^ !owner مدیر گروه !id ایدی شخص مورد نظر !res [username] در اوردن ایدی شخص مورد نظر !settings تنظیمات فعلی گروه 10-bot number & support ^ !share دریافت شماره ربات !join 103661224 وصل شدن به ساپورت you can use both "/" and "!" شما میتوانید از ! و / استفاده کنید Developer: @RM13790115 توسعه دهنده اگه هم ریپورتی از طریق بات بچت @RM13790115bot channel: @AVENGERRSS کانال ما G00D LUCK ^_^ ]] } serialize_to_file(config, './data/config.lua') print('saved config into ./data/config.lua') end function on_our_id (id) our_id = id end function on_user_update (user, what) --vardump (user) end function on_chat_update (chat, what) end function on_secret_chat_update (schat, what) --vardump (schat) end function on_get_difference_end () end -- Enable plugins in config.json function load_plugins() for k, v in pairs(_config.enabled_plugins) do print("Loading plugin", v) local ok, err = pcall(function() local t = loadfile("plugins/"..v..'.lua')() plugins[v] = t end) if not ok then print('\27[31mError loading plugin '..v..'\27[39m') print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all'))) print('\27[31m'..err..'\27[39m') end end end -- custom add function load_data(filename) local f = io.open(filename) if not f then return {} end local s = f:read('*all') f:close() local data = JSON.decode(s) return data end function save_data(filename, data) local s = JSON.encode(data) local f = io.open(filename, 'w') f:write(s) f:close() end -- Call and postpone execution for cron plugins function cron_plugins() for name, plugin in pairs(plugins) do -- Only plugins with cron function if plugin.cron ~= nil then plugin.cron() end end -- Called again in 2 mins postpone (cron_plugins, false, 120) end -- Start and load values our_id = 0 now = os.time() math.randomseed(now) started = false
gpl-2.0
appaquet/torch-android
src/3rdparty/luasocket-2.0.2/samples/cddb.lua
56
1415
local socket = require("socket") local http = require("socket.http") if not arg or not arg[1] or not arg[2] then print("luasocket cddb.lua <category> <disc-id> [<server>]") os.exit(1) end local server = arg[3] or "http://freedb.freedb.org/~cddb/cddb.cgi" function parse(body) local lines = string.gfind(body, "(.-)\r\n") local status = lines() local code, message = socket.skip(2, string.find(status, "(%d%d%d) (.*)")) if tonumber(code) ~= 210 then return nil, code, message end local data = {} for l in lines do local c = string.sub(l, 1, 1) if c ~= '#' and c ~= '.' then local key, value = socket.skip(2, string.find(l, "(.-)=(.*)")) value = string.gsub(value, "\\n", "\n") value = string.gsub(value, "\\\\", "\\") value = string.gsub(value, "\\t", "\t") data[key] = value end end return data, code, message end local host = socket.dns.gethostname() local query = "%s?cmd=cddb+read+%s+%s&hello=LuaSocket+%s+LuaSocket+2.0&proto=6" local url = string.format(query, server, arg[1], arg[2], host) local body, headers, code = http.get(url) if code == 200 then local data, code, error = parse(body) if not data then print(error or code) else for i,v in pairs(data) do io.write(i, ': ', v, '\n') end end else print(error) end
bsd-3-clause
MatthewDwyer/botman
mudlet/profiles/newbot/scripts/chat/gmsg_hotspots.lua
1
27499
--[[ Botman - A collection of scripts for managing 7 Days to Die servers Copyright (C) 2020 Matthew Dwyer This copyright applies to the Lua source code in this Mudlet profile. Email mdwyer@snap.net.nz URL http://botman.nz Source https://bitbucket.org/mhdwyer/botman --]] local idx, size, hotspotmsg, nextidx, debug, result, pid, help, tmp local shortHelp = false local skipHelp = false debug = false -- should be false unless testing -- public functions function RemoveInvalidHotspots(steam) local dist, size, delete -- abort if staff member if accessLevel(steam) < 3 then return end cursor,errorString = conn:execute("select * from hotspots where owner = " .. steam) row = cursor:fetch({}, "a") while row do delete = true dist = distancexz(row.x, row.z, players[steam].homeX, players[steam].homeZ) size = tonumber(players[steam].protectSize) if (dist < tonumber(size + 16)) then delete = false end if math.abs(players[steam].home2X) > 0 and math.abs(players[steam].home2Z) > 0 then dist = distancexz(row.x, row.z, players[steam].home2X, players[steam].home2Z) size = tonumber(players[steam].protect2Size) if (dist < tonumber(size + 16)) then delete = false end end if delete then -- remove this hotspot hotspots[row.idx] = nil conn:execute("DELETE FROM hotspots WHERE idx = " .. row.idx) end row = cursor:fetch(row, "a") end end function gmsg_hotspots() calledFunction = "gmsg_hotspots" size = nil result = false tmp = {} if botman.debugAll then debug = true -- this should be true end -- ################## hotspot command functions ################## local function cmd_ResizeHotspot() if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}resize hotspot {hotspot number from list} size {size}" help[2] = "Change a hotspot's radius to a max of 10 (no max size for admins).\n" help[2] = help[2] .. "eg. {#}resize hotspot 3 size 5. See {#}hotspots to get the list of hotspots." tmp.command = help[1] tmp.keywords = "hot,spot,size,set" tmp.accessLevel = 99 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "hots") or string.find(chatvars.command, "size") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end if (chatvars.words[1] == "resize" and chatvars.words[2] == "hotspot" and chatvars.words[3] ~= nil) then if chatvars.accessLevel == 99 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]New players are not allowed to play with hotspots.[-]") botman.faultyChat = false return true end if (chatvars.words[3] == nil) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Change a hotspot's radius to a max of 10 (unlimited for admins).[-]") message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]eg. " .. server.commandPrefix .. "resize hotspot 3 size 5[-]") message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Type " .. server.commandPrefix .. "hotspots for a list of your hotspots[-]") botman.faultyChat = false return true end idx = tonumber(chatvars.words[3]) if idx == nil then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Number required for hotspot.[-]") message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]eg. " .. server.commandPrefix .. "resize hotspot 3 size 5[-]") message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Type " .. server.commandPrefix .. "hotspots for a list of your hotspots[-]") botman.faultyChat = false return true end if chatvars.words[5] ~= nil then size = math.abs(tonumber(chatvars.words[5])) + 1 if chatvars.accessLevel < 3 then if size == nil or size == 1 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Number required for size greater than 0.[-]") botman.faultyChat = false return true end else if size == nil or size > 11 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Number required for size in the range 1 to 10.[-]") botman.faultyChat = false return true end size = math.floor(size) - 1 end end hotspots[idx].size = size if botman.dbConnected then conn:execute("UPDATE hotspots SET size = " .. size .. " WHERE idx = " .. idx) end message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Hotspot: " .. hotspots[idx].hotspot .. " now covers " .. size * 2 .. " metres[-]") botman.faultyChat = false return true end end local function cmd_MoveHotspot() if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}move hotspot {hotspot number from list}" help[2] = "Move a hotspot to your current position." tmp.command = help[1] tmp.keywords = "hot,spot,move" tmp.accessLevel = 99 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "hots") or string.find(chatvars.command, "move") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end if (chatvars.words[1] == "move" and chatvars.words[2] == "hotspot" and chatvars.words[3] ~= nil) then if chatvars.accessLevel == 99 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]New players are not allowed to play with hotspots. (risk of swallowing small parts)[-]") botman.faultyChat = false return true end if (chatvars.number == nil) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Hotspot number required eg. " .. server.commandPrefix .. "move hotspot 25.[-]") botman.faultyChat = false return true end if chatvars.accessLevel > 2 then if not players[chatvars.playerid].atHome then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Your hotspots may be no further than " .. tonumber(server.baseSize) .. " metres from your first or second bot protected base.[-]") botman.faultyChat = false return true end end if chatvars.accessLevel < 4 then if hotspots[chatvars.number] then if botman.dbConnected then conn:execute("UPDATE hotspots SET x = " .. chatvars.intX .. ", y = " .. chatvars.intY .. ", z = " .. chatvars.intZ .. " WHERE idx = " .. chatvars.number) end message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You moved the hotspot: " .. hotspots[chatvars.number].hotspot .. "[-]") hotspots[chatvars.number].x = chatvars.intX hotspots[chatvars.number].y = chatvars.intY hotspots[chatvars.number].z = chatvars.intZ botman.faultyChat = false return true else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]There is no hotspot #" .. chatvars.number .. ".[-]") botman.faultyChat = false return true end else cursor,errorString = conn:execute("select * from hotspots where idx = " .. chatvars.number) rows = cursor:numrows() if rows > 0 then row = cursor:fetch({}, "a") if row.owner ~= chatvars.playerid then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You don't own this hotspot.[-]") botman.faultyChat = false return true else if hotspots[chatvars.number] then conn:execute("UPDATE hotspots SET x = " .. chatvars.intX .. ", y = " .. chatvars.intY .. ", z = " .. chatvars.intZ .. " WHERE idx = " .. chatvars.number) message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You moved the hotspot: " .. hotspots[chatvars.number].hotspot .. "[-]") hotspots[chatvars.number].x = chatvars.intX hotspots[chatvars.number].y = chatvars.intY hotspots[chatvars.number].z = chatvars.intZ botman.faultyChat = false return true else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]There is no hotspot #" .. chatvars.number .. ".[-]") botman.faultyChat = false return true end end end end end end local function cmd_DeleteHotspots() local playerName if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}delete hotspots {player name}" help[2] = "Players can only delete their own hotspots but admins can add a player name or id to delete the player's hotspots." tmp.command = help[1] tmp.keywords = "hot,spot,del,remo" tmp.accessLevel = 99 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "hots") or string.find(chatvars.command, "del") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end if ((chatvars.words[1] == "delete" or chatvars.words[1] == "remove") and chatvars.words[2] == "hotspots") then if chatvars.accessLevel == 99 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]New players are not allowed to play with hotspots. (cancer risk)[-]") botman.faultyChat = false return true end if chatvars.accessLevel < 3 then pid = chatvars.playerid if chatvars.words[3] ~= nil then pname = string.sub(chatvars.command, string.find(chatvars.command, "hotspots ") + 10) pname = string.trim(pname) pid = LookupPlayer(pname) if pid == 0 then pid = LookupArchivedPlayer(pname) if not (pid == 0) then playerName = playersArchived[pid].name else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]No player found called " .. pname .. ".[-]") botman.faultyChat = false return true end else playerName = players[pid].name end end if botman.dbConnected then conn:execute("DELETE FROM hotspots WHERE owner = " .. pid) end message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You deleted the hotspots belonging to " .. playerName .. "[-]") -- reload the hotspots lua table loadHotspots() else if botman.dbConnected then conn:execute("DELETE FROM hotspots WHERE owner = " .. chatvars.playerid) end message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Your hotspots have been deleted.[-]") -- reload the hotspots lua table loadHotspots() end botman.faultyChat = false return true end end local function cmd_DeleteHotspot() if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}delete hotspot {hotspot number from list}" help[2] = "Delete a hotspot by its number in a list." tmp.command = help[1] tmp.keywords = "hot,spot,del,remo" tmp.accessLevel = 99 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "hots") or string.find(chatvars.command, "del") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end if (chatvars.words[1] == "delete" and chatvars.words[2] == "hotspot") then if chatvars.accessLevel == 99 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]New players are not allowed to play with hotspots. (This is why we can't have nice things!)[-]") botman.faultyChat = false return true end if chatvars.number == nil then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Hotspot number required eg. " .. server.commandPrefix .. "delete hotspot 25.[-]") botman.faultyChat = false return true end if chatvars.accessLevel < 3 then if hotspots[chatvars.number] then if botman.dbConnected then conn:execute("DELETE FROM hotspots WHERE idx = " .. chatvars.number) end message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You deleted the hotspot: " .. hotspots[chatvars.number].hotspot .. "[-]") hotspots[chatvars.number] = nil else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]There is no hotspot #" .. chatvars.number .. ".[-]") botman.faultyChat = false return true end else cursor,errorString = conn:execute("select * from hotspots where idx = " .. chatvars.number) rows = cursor:numrows() if rows > 0 then row = cursor:fetch({}, "a") if row.owner ~= chatvars.playerid then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You don't own this hotspot.[-]") botman.faultyChat = false return true else if hotspots[chatvars.number] then conn:execute("DELETE FROM hotspots WHERE idx = " .. chatvars.number) message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You deleted the hotspot: " .. hotspots[chatvars.number].hotspot .. "[-]") hotspots[chatvars.number] = nil else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]There is no hotspot #" .. chatvars.number .. ".[-]") botman.faultyChat = false return true end end end end botman.faultyChat = false return true end end local function cmd_CreateHotspot() if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}hotspot {message}" help[2] = "Create a hotspot at your current position with a message." tmp.command = help[1] tmp.keywords = "hot,spot,crea,add,set,make" tmp.accessLevel = 99 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "hots") or string.find(chatvars.command, "add") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end if (chatvars.words[1] == "hotspot") then if chatvars.accessLevel == 99 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]New players are not allowed to play with hotspots. (that's you)[-]") botman.faultyChat = false return true end if chatvars.words[2] == nil then botman.faultyChat = commandHelp("hotspots") return true end if chatvars.words[3] == nil and chatvars.number ~= nil then if chatvars.accessLevel < 3 then -- teleport the admin to the coords of the numbered hotspot cursor,errorString = conn:execute("select * from hotspots where idx = " .. chatvars.number) rows = cursor:numrows() if rows > 0 then row = cursor:fetch({}, "a") -- first record the players current position savePosition(chatvars.playerid) cmd = "tele " .. chatvars.playerid .. " " .. row.x .. " " .. row.y .. " " .. row.z teleport(cmd, chatvars.playerid) else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]There is no hotspot #" .. chatvars.number .. ".[-]") end botman.faultyChat = false return true else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Only admins can teleport to a hotspot.[-]") botman.faultyChat = false return true end end if (chatvars.number == nil) then if chatvars.accessLevel > 2 and not players[chatvars.playerid].atHome then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You can only create hotspots in and around your base.[-]") botman.faultyChat = false return true end hotspotmsg = string.sub(chatvars.commandOld, string.find(chatvars.command, "hotspot ") + 8) hotspotmsg = string.trim(hotspotmsg) cursor,errorString = conn:execute("select max(idx) as max_idx from hotspots") row = cursor:fetch({}, "a") if row.max_idx ~= nil then nextidx = tonumber(row.max_idx) + 1 else nextidx = 1 end hotspots[nextidx] = {} hotspots[nextidx].hotspot = hotspotmsg hotspots[nextidx].owner = chatvars.playerid hotspots[nextidx].size = 2 hotspots[nextidx].x = chatvars.intX hotspots[nextidx].y = chatvars.intY hotspots[nextidx].z = chatvars.intZ conn:execute("INSERT INTO hotspots (idx, hotspot, x, y, z, owner) VALUES (" .. nextidx .. ",'" .. escape(hotspotmsg) .. "'," .. chatvars.intX .. "," .. chatvars.intY .. "," .. chatvars.intZ .. "," .. chatvars.playerid .. ")") message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You made a hotspot with the message " .. hotspotmsg .. "[-]") end botman.faultyChat = false return true end end local function cmd_ListHotspots() if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}hotspots {player name}" help[2] = "List your own hotspots. Admins can list another player's hotspots." tmp.command = help[1] tmp.keywords = "hot,spot,view,list" tmp.accessLevel = 99 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "hots") or string.find(chatvars.command, "list") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end if (chatvars.words[1] == "hotspots") then pid = chatvars.playerid if chatvars.accessLevel == 99 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]New players are not allowed to play with hotspots. (You have none, nil, zip, zero, nadda)[-]") botman.faultyChat = false return true end if (chatvars.number == nil) then if (chatvars.accessLevel < 3) then if chatvars.words[2] ~= nil then pname = string.sub(chatvars.command, string.find(chatvars.command, "hotspots ") + 10) pname = string.trim(pname) pid = LookupPlayer(pname) if pid == 0 then pid = LookupArchivedPlayer(pname) end else chatvars.number = 20 end else pid = chatvars.playerid end if (pid == 0 and chatvars.number == nil) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]No player found with that name.[-]") botman.faultyChat = false return true end if (pid ~= 0) then cursor,errorString = conn:execute("select * from hotspots where owner = " .. pid) row = cursor:fetch({}, "a") while row do message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]#" .. row.idx .. " " .. row.hotspot .. "[-]") row = cursor:fetch(row, "a") end botman.faultyChat = false return true end end if (chatvars.number ~= nil) then if (chatvars.accessLevel > 2) then chatvars.number = 20 cursor,errorString = conn:execute("select * from hotspots where owner = " .. chatvars.playerid .. " and abs(x - " .. chatvars.intX .. ") <= " .. chatvars.number .. " and abs(y - " .. chatvars.intY .. ") <= " .. chatvars.number .. " and abs(z - " .. chatvars.intZ .. ") <= " .. chatvars.number) else if (chatvars.number == nil) then chatvars.number = 20 end cursor,errorString = conn:execute("select * from hotspots where abs(x - " .. chatvars.intX .. ") <= " .. chatvars.number .. " and abs(y - " .. chatvars.intY .. ") <= " .. chatvars.number .. " and abs(z - " .. chatvars.intZ .. ") <= " .. chatvars.number) end message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]The following hotspots are within " .. chatvars.number .. " metres of you[-]") row = cursor:fetch({}, "a") while row do if chatvars.accessLevel < 3 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]#" .. row.idx .. " " .. players[row.owner].name .. " size " .. row.size * 2 .. "m " .. row.hotspot .. "[-]") else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]#" .. row.idx .. " size " .. row.size * 2 .. "m " .. row.hotspot .. "[-]") end row = cursor:fetch(row, "a") end botman.faultyChat = false return true end end end local function cmd_SetHotspotAction() if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}hotspot {hotspot number from list} action {action from list: pm, tele, drop, spawn}" help[2] = "NOTE: This command is not finished. Setting it won't do anything yet.\n" help[2] = help[2] .. "Change a hotspot's action. The deafault is to just pm the player but it can also teleport them somewhere, spawn something or buff/debuff the player.\n" help[2] = help[2] .. "eg. {#}hotspot {number of hotspot} action {pm/tele/drop/spawn} {location name/spawn list}\n" help[2] = help[2] .. "If spawning items or entities use the format item name,quantity|item name,quantity|etc or entity id, entity id, entity id, etc" tmp.command = help[1] tmp.keywords = "hot,spot,view,list" tmp.accessLevel = 1 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "hots") or string.find(chatvars.command, "action") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end if (chatvars.words[1] == "hotspot" and chatvars.words[3] == "action" and chatvars.words[4] ~= nil) then if (chatvars.playername ~= "Server") then if (chatvars.accessLevel > 1) then message(string.format("pm %s [%s]" .. restrictedCommandMessage(), chatvars.playerid, server.chatColour)) botman.faultyChat = false return true end end message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]This command is unfinished :([-]") botman.faultyChat = false return true end end -- ################## End of command functions ################## if botman.registerHelp then irc_chat(chatvars.ircAlias, "==== Registering help - hotspot commands ====") if debug then dbug("Registering help - hotspot commands") end tmp.topicDescription = "Hotspots are proximity triggered PM's that say something to an individual player. Additional functions are being added and admins will be able to queue multiple actions when a specific hotspot is triggered." cursor,errorString = conn:execute("SELECT * FROM helpTopics WHERE topic = 'hotspots'") rows = cursor:numrows() if rows == 0 then cursor,errorString = conn:execute("SHOW TABLE STATUS LIKE 'helpTopics'") row = cursor:fetch(row, "a") tmp.topicID = row.Auto_increment conn:execute("INSERT INTO helpTopics (topic, description) VALUES ('hotspots', '" .. escape(tmp.topicDescription) .. "')") end end -- don't proceed if there is no leading slash if (string.sub(chatvars.command, 1, 1) ~= server.commandPrefix and server.commandPrefix ~= "") then botman.faultyChat = false return false end if chatvars.showHelp then if chatvars.words[3] then if not string.find(chatvars.command, "hots") then skipHelp = true end end if chatvars.words[1] == "help" then skipHelp = false end if chatvars.words[1] == "list" then shortHelp = true end end if chatvars.showHelp and not skipHelp and chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, ".") irc_chat(chatvars.ircAlias, "Hotspot Commands (in-game only):") irc_chat(chatvars.ircAlias, "================================") irc_chat(chatvars.ircAlias, ".") end if chatvars.showHelpSections then irc_chat(chatvars.ircAlias, "hotspots") end -- ################### do not run remote commands beyond this point unless displaying command help ################ if chatvars.playerid == 0 and not (chatvars.showHelp or botman.registerHelp) then botman.faultyChat = false return false end -- ################### do not run remote commands beyond this point unless displaying command help ################ if (debug) then dbug("debug hotspots line " .. debugger.getinfo(1).currentline) end result = cmd_CreateHotspot() if result then if debug then dbug("debug cmd_CreateHotspot triggered") end return result end if (debug) then dbug("debug hotspots line " .. debugger.getinfo(1).currentline) end result = cmd_DeleteHotspot() if result then if debug then dbug("debug cmd_DeleteHotspot triggered") end return result end if (debug) then dbug("debug hotspots line " .. debugger.getinfo(1).currentline) end result = cmd_DeleteHotspots() if result then if debug then dbug("debug cmd_DeleteHotspots triggered") end return result end if (debug) then dbug("debug hotspots line " .. debugger.getinfo(1).currentline) end result = cmd_ListHotspots() if result then if debug then dbug("debug cmd_ListHotspots triggered") end return result end if (debug) then dbug("debug hotspots line " .. debugger.getinfo(1).currentline) end result = cmd_MoveHotspot() if result then if debug then dbug("debug cmd_MoveHotspot triggered") end return result end if (debug) then dbug("debug hotspots line " .. debugger.getinfo(1).currentline) end result = cmd_ResizeHotspot() if result then if debug then dbug("debug cmd_ResizeHotspot triggered") end return result end if (debug) then dbug("debug hotspots line " .. debugger.getinfo(1).currentline) end result = cmd_SetHotspotAction() if result then if debug then dbug("debug cmd_SetHotspotAction triggered") end return result end if botman.registerHelp then irc_chat(chatvars.ircAlias, "**** Hotspot commands help registered ****") if debug then dbug("Hotspot commands help registered") end topicID = topicID + 1 end if debug then dbug("debug hotspots end") end -- can't touch dis if true then return result end end
gpl-3.0
nasomi/darkstar
scripts/zones/Castle_Oztroja/npcs/_47m.lua
17
1571
----------------------------------- -- Area: Castle Oztroja -- NPC: _47m (Torch Stand) -- Notes: Opens door _471 near password #3 -- @pos -45.230 -17.832 17.668 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() - 4; local DoorA = GetNPCByID(DoorID):getAnimation(); local TorchStandA = npc:getAnimation(); local Torch2 = npc:getID(); local Torch1 = npc:getID() - 1; if (DoorA == 9 and TorchStandA == 9) then player:startEvent(0x000a); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) local Torch2 = GetNPCByID(17396174):getID(); local Torch1 = GetNPCByID(Torch2):getID() - 1; local DoorID = GetNPCByID(Torch2):getID() - 4; if (option == 1) then GetNPCByID(Torch1):openDoor(10); -- Torch Lighting GetNPCByID(Torch2):openDoor(10); -- Torch Lighting GetNPCByID(DoorID):openDoor(6); end end; --printf("CSID: %u",csid); --printf("RESULT: %u",option);
gpl-3.0
nasomi/darkstar
scripts/zones/Wajaom_Woodlands/npcs/qm4.lua
16
1176
----------------------------------- -- Area: Wajaom Woodlands -- NPC: ??? (Spawn Tinnin(ZNM T4)) -- @pos 278 0 -703 51 ----------------------------------- package.loaded["scripts/zones/Wajaom_Woodlands/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Wajaom_Woodlands/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(2573,1) and trade:getItemCount() == 1) then -- Trade Monkey wine player:tradeComplete(); SpawnMob(16986431,180):updateClaim(player); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_HAPPENS); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
OpenPrograms/payonel-Programs
payo-lib/usr/lib/payo-lib/argutil.lua
1
8187
-- instead of using =, this parses --type f as 'f' as a value for 'type' local ser = require("serialization"); local argutil = {}; -- pack is a table.pack(...) for the script parameters -- returns an array of meta data about each param -- each param consists of: -- name, the value given in the parameter -- dashes, the # of dashes preceding the parameter name -- value, the value following the parameter if specified using = local function buildDataMeta(pack, singleDashOptions) if (not pack or not pack.n) then return nil, "arguments, even if empty, must be packed as an array" end local meta = {}; local longNames = {} if (singleDashOptions) then for i,opC in ipairs(singleDashOptions) do if (opC.name:len() > 1) then longNames[#longNames + 1] = opC.name; end end end -- split args with =, give them a value already at this point for _,a in ipairs(pack) do if (type(a) ~= type("")) then return nil, "All arguments must be passed as strings"; end local def = {} a, def.dashes = a:gsub("^-+", ""); local eIndex = a:find("=") local expanded = false; if (eIndex) then if (def.dashes == 0) then return nil, string.format("Error parsing '%s', unexpected =. Arguments cannot have values. use options instead", a) end def.name = a:sub(1, eIndex - 1) def.value = a:sub(eIndex + 1, a:len()); else def.name = a if (def.dashes == 1) then -- attempt reasonable expansion -- expand if long form not found local bFound = false; for _,name in ipairs(longNames) do if (name == a) then bFound = true; end end if (not bFound) then -- expand! expanded = true; for _=1,#a do local s = a:sub(_,_) local sdef = {} sdef.dashes = def.dashes; sdef.name = s sdef.value = nil -- none can have a value yet meta[#meta + 1] = sdef; end end end end if (not expanded) then meta[#meta + 1] = def; end end return meta; end function argutil.getArraySize(ar) local indexCount = 0; local largestIndex = 0; for k,v in pairs(ar) do if (type(k) ~= type(0)) then return nil, "table is not an array: non numeric key: " .. tostring(k) end if (largestIndex < k) then largestIndex = k; end if (largestIndex < 1) then return nil, "table is not an array: invalid index: " .. tostring(k) end indexCount = indexCount + 1 end if (indexCount ~= largestIndex) then return nil, "table is not an array: nonsequential array" end return largestIndex end -- array, index is dash count -- each dash group: array -- eash dash group item: {dashes=number, name=string, assign=boolean} local function buildOptionMeta(pack) if (not pack) then return {} end local meta = {} -- expand first single group if (pack[1] and pack[1][1] and pack[1][1]:len() > 1) then local opC = pack[1] local single_names = opC[1] table.remove(opC, 1) for _=1,#single_names do local name = single_names:sub(_,_) table.insert(opC, 1, name) end end local _, reason = argutil.getArraySize(pack); if (not _) then return nil, reason end -- now we can safely iterate from 1 to opConfigSize for dashes,g in ipairs(pack) do local assign = false dgroup = {} local _, reason = argutil.getArraySize(g); if (not _) then return nil, reason end for _,n in ipairs(g) do if (n == " " or n == "=") then assign = true --continue elseif (n:find('=')) then return nil, string.format("Error parsing '%s'. option names cannot contain =", n) else local def = {} def.dashes = dashes; def.name = n def.assign = assign dgroup[#dgroup + 1] = def; end end meta[dashes] = dgroup end return meta; end -- returns currentMetaOption, and reason for failure local function optionLookup(opMeta, argMeta) if (not argMeta or argMeta.dashes < 1) then return nil, string.format("FAILURE: %s is not an option", argMeta.name); end if (not opMeta or not opMeta[argMeta.dashes]) then -- all is allowed local adhoc = {} adhoc.name = argMeta.name adhoc.assign = not not argMeta.value; adhoc.dashes = argMeta.dashes return adhoc; end for _,def in ipairs(opMeta[argMeta.dashes]) do if (argMeta.name == def.name) then return def; end end return nil, "unexpected option: " .. argMeta.name; end --[[ opConfig structure index array where index is the dash count e.g. [1] represents configurations for single dash options, e.g. -a each value is a table [1] is for single dashed options [2] is for double dashed options [1] = the first index is for singles and is split, all remaining names are not split e.g. "abc", "def", "ghi" => "a", "b", "c", "def", "ghi" [2] = array of long option names anywhere in the chain of names when a '=' or ' ' is listed, the subsequent names are expected to have values e.g. [1] = "abc d" a, b, and c are enabled options (true|false) d takes a value, separated by a space, such as -d value [2] = "foo", "=", "bar" foo is an option that is enabled bar takes a value, given after an =, such as -bar=zoopa = is always allowed to give option values if ' ' is specified, both are allowed e.g. [1] = " d" -d 1 d is 1 -d=1 d is 1 extra white space is never allowed around an assignment operator e.g. (do not do this) -a = foobar That would be a parse error: unexpected = An assignment operator doesn't have to have a value following it e.g. -a= foobar In this case, a="", and foobar is an argument The default behavior (that is, no opConfig) puts makes all naked options enabled (true|false) The default behavior is to assign an option a value after = the option config can be nil or an empty table for default behavior each index that corresponds to a number of dashes must be nil for default behavior to be used. That is, [1]={} will not allow any single dash options, but [1]=nil will implicitly allow all ]] -- returns arg table, option table, and reason string function argutil.parse(pack, opConfig) -- the config entries can be nil, but opConfig can't opConfig = opConfig or {}; local opMeta, reason = buildOptionMeta(opConfig) if (not opMeta) then return nil, nil, reason end local metaPack, reason = buildDataMeta(pack, opMeta[1]); if (not metaPack) then return nil, nil, reason; end local args = {}; local options = {}; local pending = nil; for i,meta in ipairs(metaPack) do local bOp = meta.dashes > 0; if (bOp) then if (pending) then return nil, nil, string.format("%s missing value", pending); else local currentOpMeta, reason = optionLookup(opMeta, meta); if (not currentOpMeta) then return nil, nil, reason; end local key = currentOpMeta.name; if (options[key]) then return nil, nil, string.format("option %s defined more than once", key); end options[key] = nil -- does this option expect a value? if (currentOpMeta.assign) then if (not meta.value) then pending = meta.name else options[key] = meta.value; end else -- enabled if (meta.value) then return nil, nil, string.format("unexpected = after %s; it does not take a value", key) end options[key] = true; end end elseif (pending) then if (meta.value) then return nil, nil, string.format("unexpected = in value for %s: %s", pending, meta.name .. '=' .. meta.value) end options[pending] = meta.name; pending = nil; else args[#args + 1] = meta.name; end end if (pending) then return nil, nil, string.format("%s missing value", pending); end return args, options; end return argutil;
mit
Maxsteam/99998888
plugins/stats.lua
458
4098
-- Saves the number of messages from a user -- Can check the number of messages with !stats do local NUM_MSG_MAX = 5 local TIME_CHECK = 4 -- seconds local function user_print_name(user) if user.print_name then return user.print_name end local text = '' if user.first_name then text = user.last_name..' ' end if user.lastname then text = text..user.last_name end return text end -- 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 = '' 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 pre_process(msg) -- Ignore service msg if msg.service then print('Service message') return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) if msgs > NUM_MSG_MAX then print('User '..msg.from.id..'is flooding '..msgs) msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end 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..'\nChats: '..r return text end local function run(msg, matches) if matches[1]:lower() == "stats" then if not matches[2] then if msg.to.type == 'chat' then local chat_id = msg.to.id return chat_stats(chat_id) else return 'Stats works only on chats' end end if matches[2] == "bot" then if not is_sudo(msg) then return "Bot stats requires privileged user" else return bot_stats() end end if matches[2] == "chat" then if not is_sudo(msg) then return "This command requires privileged user" else return chat_stats(matches[3]) end end end end return { description = "Plugin to update user stats.", usage = { "!stats: Returns a list of Username [telegram_id]: msg_num", "!stats chat <chat_id>: Show stats for chat_id", "!stats bot: Shows bot stats (sudo users)" }, patterns = { "^!([Ss]tats)$", "^!([Ss]tats) (chat) (%d+)", "^!([Ss]tats) (bot)" }, run = run, pre_process = pre_process } end
gpl-2.0
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Achantere_TK.lua
28
4907
----------------------------------- -- Area: Northern San d'Oria -- NPC: Achatere, T.K. -- X Grant Signet -- X Recharge Emperor Band, Empress Band, or Chariot Band -- X Accepts traded Crystals to fill up the Rank bar to open new Missions. -- X Sells items in exchange for Conquest Points -- X Start Supply Run Missions and offers a list of already-delivered supplies. -- Start an Expeditionary Force by giving an E.F. region insignia to you. ------------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ------------------------------------- require("scripts/globals/conquest"); require("scripts/globals/common"); require("scripts/zones/Northern_San_dOria/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, JEUNO local guardtype = 1; -- 1: city, 2: foreign, 3: outpost, 4: border local size = table.getn(SandInv); local inventory = SandInv; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getNation() == guardnation and player:getVar("supplyQuest_started") > 0 and supplyRunFresh(player) == 0) then player:showText(npc,CONQUEST + 40); -- "We will dispose of those unusable supplies." local region = player:getVar("supplyQuest_region"); player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1,getSupplyKey(region)); player:setVar("supplyQuest_started",0); player:setVar("supplyQuest_region",0); player:setVar("supplyQuest_fresh",0); else local Menu1 = getArg1(guardnation,player); local Menu2 = getExForceAvailable(guardnation,player); local Menu3 = conquestRanking(); local Menu4 = getSupplyAvailable(guardnation,player); local Menu5 = player:getNationTeleport(guardnation); local Menu6 = getArg6(player); local Menu7 = player:getCP(); local Menu8 = getRewardExForce(guardnation,player); player:startEvent(0x7ffa,Menu1,Menu2,Menu3,Menu4,Menu5,Menu6,Menu7,Menu8); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("onUpdateCSID: %u",csid); -- printf("onUpdateOPTION: %u",option); if (option >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then CPVerify = 1; if (player:getCP() >= inventory[Item + 1]) then CPVerify = 0; end; player:updateEvent(2,CPVerify,inventory[Item + 2]); break; end; end; end; end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("onFinishCSID: %u",csid); -- printf("onFinishOPTION: %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 >= 32768 and option <= 32944) then for Item = 1,size,3 do if (option == inventory[Item]) then if (player:getFreeSlotsCount() >= 1) then -- Logic to impose limits on exp bands if (option >= 32933 and option <= 32935) then if (checkConquestRing(player) > 0) then player:messageSpecial(CONQUEST+60,0,0,inventory[Item+2]); break; else player:setVar("CONQUEST_RING_TIMER",getConquestTally()); end end if (player:getNation() == guardnation) then itemCP = inventory[Item + 1]; else if (inventory[Item + 1] <= 8000) then itemCP = inventory[Item + 1] * 2; else itemCP = inventory[Item + 1] + 8000; end; end; if (player:hasItem(inventory[Item + 2]) == false) then player:delCP(itemCP); player:addItem(inventory[Item + 2],1); player:messageSpecial(ITEM_OBTAINED,inventory[Item + 2]); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end; else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,inventory[Item + 2]); end; break; end; end; elseif (option >= 65541 and option <= 65565) then -- player chose supply quest. local region = option - 65541; player:addKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED,getSupplyKey(region)); player:setVar("supplyQuest_started",vanaDay()); player:setVar("supplyQuest_region",region); player:setVar("supplyQuest_fresh",getConquestTally()); end; end;
gpl-3.0
thesabbir/luci
modules/luci-base/luasrc/cbi.lua
17
40212
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Licensed to the public under the Apache License 2.0. module("luci.cbi", package.seeall) require("luci.template") local util = require("luci.util") require("luci.http") --local event = require "luci.sys.event" local fs = require("nixio.fs") local uci = require("luci.model.uci") local datatypes = require("luci.cbi.datatypes") local dispatcher = require("luci.dispatcher") local class = util.class local instanceof = util.instanceof FORM_NODATA = 0 FORM_PROCEED = 0 FORM_VALID = 1 FORM_DONE = 1 FORM_INVALID = -1 FORM_CHANGED = 2 FORM_SKIP = 4 AUTO = true CREATE_PREFIX = "cbi.cts." REMOVE_PREFIX = "cbi.rts." RESORT_PREFIX = "cbi.sts." FEXIST_PREFIX = "cbi.cbe." -- Loads a CBI map from given file, creating an environment and returns it function load(cbimap, ...) local fs = require "nixio.fs" local i18n = require "luci.i18n" require("luci.config") require("luci.util") local upldir = "/lib/uci/upload/" local cbidir = luci.util.libpath() .. "/model/cbi/" local func, err if fs.access(cbidir..cbimap..".lua") then func, err = loadfile(cbidir..cbimap..".lua") elseif fs.access(cbimap) then func, err = loadfile(cbimap) else func, err = nil, "Model '" .. cbimap .. "' not found!" end assert(func, err) local env = { translate=i18n.translate, translatef=i18n.translatef, arg={...} } setfenv(func, setmetatable(env, {__index = function(tbl, key) return rawget(tbl, key) or _M[key] or _G[key] end})) local maps = { func() } local uploads = { } local has_upload = false for i, map in ipairs(maps) do if not instanceof(map, Node) then error("CBI map returns no valid map object!") return nil else map:prepare() if map.upload_fields then has_upload = true for _, field in ipairs(map.upload_fields) do uploads[ field.config .. '.' .. (field.section.sectiontype or '1') .. '.' .. field.option ] = true end end end end if has_upload then local uci = luci.model.uci.cursor() local prm = luci.http.context.request.message.params local fd, cbid luci.http.setfilehandler( function( field, chunk, eof ) if not field then return end if field.name and not cbid then local c, s, o = field.name:gmatch( "cbid%.([^%.]+)%.([^%.]+)%.([^%.]+)" )() if c and s and o then local t = uci:get( c, s ) or s if uploads[c.."."..t.."."..o] then local path = upldir .. field.name fd = io.open(path, "w") if fd then cbid = field.name prm[cbid] = path end end end end if field.name == cbid and fd then fd:write(chunk) end if eof and fd then fd:close() fd = nil cbid = nil end end ) end return maps end -- -- Compile a datatype specification into a parse tree for evaluation later on -- local cdt_cache = { } function compile_datatype(code) local i local pos = 0 local esc = false local depth = 0 local stack = { } for i = 1, #code+1 do local byte = code:byte(i) or 44 if esc then esc = false elseif byte == 92 then esc = true elseif byte == 40 or byte == 44 then if depth <= 0 then if pos < i then local label = code:sub(pos, i-1) :gsub("\\(.)", "%1") :gsub("^%s+", "") :gsub("%s+$", "") if #label > 0 and tonumber(label) then stack[#stack+1] = tonumber(label) elseif label:match("^'.*'$") or label:match('^".*"$') then stack[#stack+1] = label:gsub("[\"'](.*)[\"']", "%1") elseif type(datatypes[label]) == "function" then stack[#stack+1] = datatypes[label] stack[#stack+1] = { } else error("Datatype error, bad token %q" % label) end end pos = i + 1 end depth = depth + (byte == 40 and 1 or 0) elseif byte == 41 then depth = depth - 1 if depth <= 0 then if type(stack[#stack-1]) ~= "function" then error("Datatype error, argument list follows non-function") end stack[#stack] = compile_datatype(code:sub(pos, i-1)) pos = i + 1 end end end return stack end function verify_datatype(dt, value) if dt and #dt > 0 then if not cdt_cache[dt] then local c = compile_datatype(dt) if c and type(c[1]) == "function" then cdt_cache[dt] = c else error("Datatype error, not a function expression") end end if cdt_cache[dt] then return cdt_cache[dt][1](value, unpack(cdt_cache[dt][2])) end end return true end -- Node pseudo abstract class Node = class() function Node.__init__(self, title, description) self.children = {} self.title = title or "" self.description = description or "" self.template = "cbi/node" end -- hook helper function Node._run_hook(self, hook) if type(self[hook]) == "function" then return self[hook](self) end end function Node._run_hooks(self, ...) local f local r = false for _, f in ipairs(arg) do if type(self[f]) == "function" then self[f](self) r = true end end return r end -- Prepare nodes function Node.prepare(self, ...) for k, child in ipairs(self.children) do child:prepare(...) end end -- Append child nodes function Node.append(self, obj) table.insert(self.children, obj) end -- Parse this node and its children function Node.parse(self, ...) for k, child in ipairs(self.children) do child:parse(...) end end -- Render this node function Node.render(self, scope) scope = scope or {} scope.self = self luci.template.render(self.template, scope) end -- Render the children function Node.render_children(self, ...) local k, node for k, node in ipairs(self.children) do node.last_child = (k == #self.children) node:render(...) end end --[[ A simple template element ]]-- Template = class(Node) function Template.__init__(self, template) Node.__init__(self) self.template = template end function Template.render(self) luci.template.render(self.template, {self=self}) end function Template.parse(self, readinput) self.readinput = (readinput ~= false) return Map.formvalue(self, "cbi.submit") and FORM_DONE or FORM_NODATA end --[[ Map - A map describing a configuration file ]]-- Map = class(Node) function Map.__init__(self, config, ...) Node.__init__(self, ...) self.config = config self.parsechain = {self.config} self.template = "cbi/map" self.apply_on_parse = nil self.readinput = true self.proceed = false self.flow = {} self.uci = uci.cursor() self.save = true self.changed = false local path = "%s/%s" %{ self.uci:get_confdir(), self.config } if fs.stat(path, "type") ~= "reg" then fs.writefile(path, "") end local ok, err = self.uci:load(self.config) if not ok then local url = dispatcher.build_url(unpack(dispatcher.context.request)) local source = self:formvalue("cbi.source") if type(source) == "string" then fs.writefile(path, source:gsub("\r\n", "\n")) ok, err = self.uci:load(self.config) if ok then luci.http.redirect(url) end end self.save = false end if not ok then self.template = "cbi/error" self.error = err self.source = fs.readfile(path) or "" self.pageaction = false end end function Map.formvalue(self, key) return self.readinput and luci.http.formvalue(key) end function Map.formvaluetable(self, key) return self.readinput and luci.http.formvaluetable(key) or {} end function Map.get_scheme(self, sectiontype, option) if not option then return self.scheme and self.scheme.sections[sectiontype] else return self.scheme and self.scheme.variables[sectiontype] and self.scheme.variables[sectiontype][option] end end function Map.submitstate(self) return self:formvalue("cbi.submit") end -- Chain foreign config function Map.chain(self, config) table.insert(self.parsechain, config) end function Map.state_handler(self, state) return state end -- Use optimized UCI writing function Map.parse(self, readinput, ...) self.readinput = (readinput ~= false) self:_run_hooks("on_parse") if self:formvalue("cbi.skip") then self.state = FORM_SKIP return self:state_handler(self.state) end Node.parse(self, ...) if self.save then self:_run_hooks("on_save", "on_before_save") for i, config in ipairs(self.parsechain) do self.uci:save(config) end self:_run_hooks("on_after_save") if self:submitstate() and ((not self.proceed and self.flow.autoapply) or luci.http.formvalue("cbi.apply")) then self:_run_hooks("on_before_commit") for i, config in ipairs(self.parsechain) do self.uci:commit(config) -- Refresh data because commit changes section names self.uci:load(config) end self:_run_hooks("on_commit", "on_after_commit", "on_before_apply") if self.apply_on_parse then self.uci:apply(self.parsechain) self:_run_hooks("on_apply", "on_after_apply") else -- This is evaluated by the dispatcher and delegated to the -- template which in turn fires XHR to perform the actual -- apply actions. self.apply_needed = true end -- Reparse sections Node.parse(self, true) end for i, config in ipairs(self.parsechain) do self.uci:unload(config) end if type(self.commit_handler) == "function" then self:commit_handler(self:submitstate()) end end if self:submitstate() then if not self.save then self.state = FORM_INVALID elseif self.proceed then self.state = FORM_PROCEED else self.state = self.changed and FORM_CHANGED or FORM_VALID end else self.state = FORM_NODATA end return self:state_handler(self.state) end function Map.render(self, ...) self:_run_hooks("on_init") Node.render(self, ...) end -- Creates a child section function Map.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- UCI add function Map.add(self, sectiontype) return self.uci:add(self.config, sectiontype) end -- UCI set function Map.set(self, section, option, value) if type(value) ~= "table" or #value > 0 then if option then return self.uci:set(self.config, section, option, value) else return self.uci:set(self.config, section, value) end else return Map.del(self, section, option) end end -- UCI del function Map.del(self, section, option) if option then return self.uci:delete(self.config, section, option) else return self.uci:delete(self.config, section) end end -- UCI get function Map.get(self, section, option) if not section then return self.uci:get_all(self.config) elseif option then return self.uci:get(self.config, section, option) else return self.uci:get_all(self.config, section) end end --[[ Compound - Container ]]-- Compound = class(Node) function Compound.__init__(self, ...) Node.__init__(self) self.template = "cbi/compound" self.children = {...} end function Compound.populate_delegator(self, delegator) for _, v in ipairs(self.children) do v.delegator = delegator end end function Compound.parse(self, ...) local cstate, state = 0 for k, child in ipairs(self.children) do cstate = child:parse(...) state = (not state or cstate < state) and cstate or state end return state end --[[ Delegator - Node controller ]]-- Delegator = class(Node) function Delegator.__init__(self, ...) Node.__init__(self, ...) self.nodes = {} self.defaultpath = {} self.pageaction = false self.readinput = true self.allow_reset = false self.allow_cancel = false self.allow_back = false self.allow_finish = false self.template = "cbi/delegator" end function Delegator.set(self, name, node) assert(not self.nodes[name], "Duplicate entry") self.nodes[name] = node end function Delegator.add(self, name, node) node = self:set(name, node) self.defaultpath[#self.defaultpath+1] = name end function Delegator.insert_after(self, name, after) local n = #self.chain + 1 for k, v in ipairs(self.chain) do if v == after then n = k + 1 break end end table.insert(self.chain, n, name) end function Delegator.set_route(self, ...) local n, chain, route = 0, self.chain, {...} for i = 1, #chain do if chain[i] == self.current then n = i break end end for i = 1, #route do n = n + 1 chain[n] = route[i] end for i = n + 1, #chain do chain[i] = nil end end function Delegator.get(self, name) local node = self.nodes[name] if type(node) == "string" then node = load(node, name) end if type(node) == "table" and getmetatable(node) == nil then node = Compound(unpack(node)) end return node end function Delegator.parse(self, ...) if self.allow_cancel and Map.formvalue(self, "cbi.cancel") then if self:_run_hooks("on_cancel") then return FORM_DONE end end if not Map.formvalue(self, "cbi.delg.current") then self:_run_hooks("on_init") end local newcurrent self.chain = self.chain or self:get_chain() self.current = self.current or self:get_active() self.active = self.active or self:get(self.current) assert(self.active, "Invalid state") local stat = FORM_DONE if type(self.active) ~= "function" then self.active:populate_delegator(self) stat = self.active:parse() else self:active() end if stat > FORM_PROCEED then if Map.formvalue(self, "cbi.delg.back") then newcurrent = self:get_prev(self.current) else newcurrent = self:get_next(self.current) end elseif stat < FORM_PROCEED then return stat end if not Map.formvalue(self, "cbi.submit") then return FORM_NODATA elseif stat > FORM_PROCEED and (not newcurrent or not self:get(newcurrent)) then return self:_run_hook("on_done") or FORM_DONE else self.current = newcurrent or self.current self.active = self:get(self.current) if type(self.active) ~= "function" then self.active:populate_delegator(self) local stat = self.active:parse(false) if stat == FORM_SKIP then return self:parse(...) else return FORM_PROCEED end else return self:parse(...) end end end function Delegator.get_next(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k+1] end end end function Delegator.get_prev(self, state) for k, v in ipairs(self.chain) do if v == state then return self.chain[k-1] end end end function Delegator.get_chain(self) local x = Map.formvalue(self, "cbi.delg.path") or self.defaultpath return type(x) == "table" and x or {x} end function Delegator.get_active(self) return Map.formvalue(self, "cbi.delg.current") or self.chain[1] end --[[ Page - A simple node ]]-- Page = class(Node) Page.__init__ = Node.__init__ Page.parse = function() end --[[ SimpleForm - A Simple non-UCI form ]]-- SimpleForm = class(Node) function SimpleForm.__init__(self, config, title, description, data) Node.__init__(self, title, description) self.config = config self.data = data or {} self.template = "cbi/simpleform" self.dorender = true self.pageaction = false self.readinput = true end SimpleForm.formvalue = Map.formvalue SimpleForm.formvaluetable = Map.formvaluetable function SimpleForm.parse(self, readinput, ...) self.readinput = (readinput ~= false) if self:formvalue("cbi.skip") then return FORM_SKIP end if self:formvalue("cbi.cancel") and self:_run_hooks("on_cancel") then return FORM_DONE end if self:submitstate() then Node.parse(self, 1, ...) end local valid = true for k, j in ipairs(self.children) do for i, v in ipairs(j.children) do valid = valid and (not v.tag_missing or not v.tag_missing[1]) and (not v.tag_invalid or not v.tag_invalid[1]) and (not v.error) end end local state = not self:submitstate() and FORM_NODATA or valid and FORM_VALID or FORM_INVALID self.dorender = not self.handle if self.handle then local nrender, nstate = self:handle(state, self.data) self.dorender = self.dorender or (nrender ~= false) state = nstate or state end return state end function SimpleForm.render(self, ...) if self.dorender then Node.render(self, ...) end end function SimpleForm.submitstate(self) return self:formvalue("cbi.submit") end function SimpleForm.section(self, class, ...) if instanceof(class, AbstractSection) then local obj = class(self, ...) self:append(obj) return obj else error("class must be a descendent of AbstractSection") end end -- Creates a child field function SimpleForm.field(self, class, ...) local section for k, v in ipairs(self.children) do if instanceof(v, SimpleSection) then section = v break end end if not section then section = self:section(SimpleSection) end if instanceof(class, AbstractValue) then local obj = class(self, section, ...) obj.track_missing = true section:append(obj) return obj else error("class must be a descendent of AbstractValue") end end function SimpleForm.set(self, section, option, value) self.data[option] = value end function SimpleForm.del(self, section, option) self.data[option] = nil end function SimpleForm.get(self, section, option) return self.data[option] end function SimpleForm.get_scheme() return nil end Form = class(SimpleForm) function Form.__init__(self, ...) SimpleForm.__init__(self, ...) self.embedded = true end --[[ AbstractSection ]]-- AbstractSection = class(Node) function AbstractSection.__init__(self, map, sectiontype, ...) Node.__init__(self, ...) self.sectiontype = sectiontype self.map = map self.config = map.config self.optionals = {} self.defaults = {} self.fields = {} self.tag_error = {} self.tag_invalid = {} self.tag_deperror = {} self.changed = false self.optional = true self.addremove = false self.dynamic = false end -- Define a tab for the section function AbstractSection.tab(self, tab, title, desc) self.tabs = self.tabs or { } self.tab_names = self.tab_names or { } self.tab_names[#self.tab_names+1] = tab self.tabs[tab] = { title = title, description = desc, childs = { } } end -- Check whether the section has tabs function AbstractSection.has_tabs(self) return (self.tabs ~= nil) and (next(self.tabs) ~= nil) end -- Appends a new option function AbstractSection.option(self, class, option, ...) if instanceof(class, AbstractValue) then local obj = class(self.map, self, option, ...) self:append(obj) self.fields[option] = obj return obj elseif class == true then error("No valid class was given and autodetection failed.") else error("class must be a descendant of AbstractValue") end end -- Appends a new tabbed option function AbstractSection.taboption(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot assign option to not existing tab %q" % tostring(tab)) local l = self.tabs[tab].childs local o = AbstractSection.option(self, ...) if o then l[#l+1] = o end return o end -- Render a single tab function AbstractSection.render_tab(self, tab, ...) assert(tab and self.tabs and self.tabs[tab], "Cannot render not existing tab %q" % tostring(tab)) local k, node for k, node in ipairs(self.tabs[tab].childs) do node.last_child = (k == #self.tabs[tab].childs) node:render(...) end end -- Parse optional options function AbstractSection.parse_optionals(self, section) if not self.optional then return end self.optionals[section] = {} local field = self.map:formvalue("cbi.opt."..self.config.."."..section) for k,v in ipairs(self.children) do if v.optional and not v:cfgvalue(section) and not self:has_tabs() then if field == v.option then field = nil self.map.proceed = true else table.insert(self.optionals[section], v) end end end if field and #field > 0 and self.dynamic then self:add_dynamic(field) end end -- Add a dynamic option function AbstractSection.add_dynamic(self, field, optional) local o = self:option(Value, field, field) o.optional = optional end -- Parse all dynamic options function AbstractSection.parse_dynamic(self, section) if not self.dynamic then return end local arr = luci.util.clone(self:cfgvalue(section)) local form = self.map:formvaluetable("cbid."..self.config.."."..section) for k, v in pairs(form) do arr[k] = v end for key,val in pairs(arr) do local create = true for i,c in ipairs(self.children) do if c.option == key then create = false end end if create and key:sub(1, 1) ~= "." then self.map.proceed = true self:add_dynamic(key, true) end end end -- Returns the section's UCI table function AbstractSection.cfgvalue(self, section) return self.map:get(section) end -- Push events function AbstractSection.push_events(self) --luci.util.append(self.map.events, self.events) self.map.changed = true end -- Removes the section function AbstractSection.remove(self, section) self.map.proceed = true return self.map:del(section) end -- Creates the section function AbstractSection.create(self, section) local stat if section then stat = section:match("^[%w_]+$") and self.map:set(section, nil, self.sectiontype) else section = self.map:add(self.sectiontype) stat = section end if stat then for k,v in pairs(self.children) do if v.default then self.map:set(section, v.option, v.default) end end for k,v in pairs(self.defaults) do self.map:set(section, k, v) end end self.map.proceed = true return stat end SimpleSection = class(AbstractSection) function SimpleSection.__init__(self, form, ...) AbstractSection.__init__(self, form, nil, ...) self.template = "cbi/nullsection" end Table = class(AbstractSection) function Table.__init__(self, form, data, ...) local datasource = {} local tself = self datasource.config = "table" self.data = data or {} datasource.formvalue = Map.formvalue datasource.formvaluetable = Map.formvaluetable datasource.readinput = true function datasource.get(self, section, option) return tself.data[section] and tself.data[section][option] end function datasource.submitstate(self) return Map.formvalue(self, "cbi.submit") end function datasource.del(...) return true end function datasource.get_scheme() return nil end AbstractSection.__init__(self, datasource, "table", ...) self.template = "cbi/tblsection" self.rowcolors = true self.anonymous = true end function Table.parse(self, readinput) self.map.readinput = (readinput ~= false) for i, k in ipairs(self:cfgsections()) do if self.map:submitstate() then Node.parse(self, k) end end end function Table.cfgsections(self) local sections = {} for i, v in luci.util.kspairs(self.data) do table.insert(sections, i) end return sections end function Table.update(self, data) self.data = data end --[[ NamedSection - A fixed configuration section defined by its name ]]-- NamedSection = class(AbstractSection) function NamedSection.__init__(self, map, section, stype, ...) AbstractSection.__init__(self, map, stype, ...) -- Defaults self.addremove = false self.template = "cbi/nsection" self.section = section end function NamedSection.parse(self, novld) local s = self.section local active = self:cfgvalue(s) if self.addremove then local path = self.config.."."..s if active then -- Remove the section if self.map:formvalue("cbi.rns."..path) and self:remove(s) then self:push_events() return end else -- Create and apply default values if self.map:formvalue("cbi.cns."..path) then self:create(s) return end end end if active then AbstractSection.parse_dynamic(self, s) if self.map:submitstate() then Node.parse(self, s) end AbstractSection.parse_optionals(self, s) if self.changed then self:push_events() end end end --[[ TypedSection - A (set of) configuration section(s) defined by the type addremove: Defines whether the user can add/remove sections of this type anonymous: Allow creating anonymous sections validate: a validation function returning nil if the section is invalid ]]-- TypedSection = class(AbstractSection) function TypedSection.__init__(self, map, type, ...) AbstractSection.__init__(self, map, type, ...) self.template = "cbi/tsection" self.deps = {} self.anonymous = false end -- Return all matching UCI sections for this TypedSection function TypedSection.cfgsections(self) local sections = {} self.map.uci:foreach(self.map.config, self.sectiontype, function (section) if self:checkscope(section[".name"]) then table.insert(sections, section[".name"]) end end) return sections end -- Limits scope to sections that have certain option => value pairs function TypedSection.depends(self, option, value) table.insert(self.deps, {option=option, value=value}) end function TypedSection.parse(self, novld) if self.addremove then -- Remove local crval = REMOVE_PREFIX .. self.config local name = self.map:formvaluetable(crval) for k,v in pairs(name) do if k:sub(-2) == ".x" then k = k:sub(1, #k - 2) end if self:cfgvalue(k) and self:checkscope(k) then self:remove(k) end end end local co for i, k in ipairs(self:cfgsections()) do AbstractSection.parse_dynamic(self, k) if self.map:submitstate() then Node.parse(self, k, novld) end AbstractSection.parse_optionals(self, k) end if self.addremove then -- Create local created local crval = CREATE_PREFIX .. self.config .. "." .. self.sectiontype local origin, name = next(self.map:formvaluetable(crval)) if self.anonymous then if name then created = self:create(nil, origin) end else if name then -- Ignore if it already exists if self:cfgvalue(name) then name = nil; end name = self:checkscope(name) if not name then self.err_invalid = true end if name and #name > 0 then created = self:create(name, origin) and name if not created then self.invalid_cts = true end end end end if created then AbstractSection.parse_optionals(self, created) end end if self.sortable then local stval = RESORT_PREFIX .. self.config .. "." .. self.sectiontype local order = self.map:formvalue(stval) if order and #order > 0 then local sid local num = 0 for sid in util.imatch(order) do self.map.uci:reorder(self.config, sid, num) num = num + 1 end self.changed = (num > 0) end end if created or self.changed then self:push_events() end end -- Verifies scope of sections function TypedSection.checkscope(self, section) -- Check if we are not excluded if self.filter and not self:filter(section) then return nil end -- Check if at least one dependency is met if #self.deps > 0 and self:cfgvalue(section) then local stat = false for k, v in ipairs(self.deps) do if self:cfgvalue(section)[v.option] == v.value then stat = true end end if not stat then return nil end end return self:validate(section) end -- Dummy validate function function TypedSection.validate(self, section) return section end --[[ AbstractValue - An abstract Value Type null: Value can be empty valid: A function returning the value if it is valid otherwise nil depends: A table of option => value pairs of which one must be true default: The default value size: The size of the input fields rmempty: Unset value if empty optional: This value is optional (see AbstractSection.optionals) ]]-- AbstractValue = class(Node) function AbstractValue.__init__(self, map, section, option, ...) Node.__init__(self, ...) self.section = section self.option = option self.map = map self.config = map.config self.tag_invalid = {} self.tag_missing = {} self.tag_reqerror = {} self.tag_error = {} self.deps = {} self.subdeps = {} --self.cast = "string" self.track_missing = false self.rmempty = true self.default = nil self.size = nil self.optional = false end function AbstractValue.prepare(self) self.cast = self.cast or "string" end -- Add a dependencie to another section field function AbstractValue.depends(self, field, value) local deps if type(field) == "string" then deps = {} deps[field] = value else deps = field end table.insert(self.deps, {deps=deps, add=""}) end -- Generates the unique CBID function AbstractValue.cbid(self, section) return "cbid."..self.map.config.."."..section.."."..self.option end -- Return whether this object should be created function AbstractValue.formcreated(self, section) local key = "cbi.opt."..self.config.."."..section return (self.map:formvalue(key) == self.option) end -- Returns the formvalue for this object function AbstractValue.formvalue(self, section) return self.map:formvalue(self:cbid(section)) end function AbstractValue.additional(self, value) self.optional = value end function AbstractValue.mandatory(self, value) self.rmempty = not value end function AbstractValue.add_error(self, section, type, msg) self.error = self.error or { } self.error[section] = msg or type self.section.error = self.section.error or { } self.section.error[section] = self.section.error[section] or { } table.insert(self.section.error[section], msg or type) if type == "invalid" then self.tag_invalid[section] = true elseif type == "missing" then self.tag_missing[section] = true end self.tag_error[section] = true self.map.save = false end function AbstractValue.parse(self, section, novld) local fvalue = self:formvalue(section) local cvalue = self:cfgvalue(section) -- If favlue and cvalue are both tables and have the same content -- make them identical if type(fvalue) == "table" and type(cvalue) == "table" then local equal = #fvalue == #cvalue if equal then for i=1, #fvalue do if cvalue[i] ~= fvalue[i] then equal = false end end end if equal then fvalue = cvalue end end if fvalue and #fvalue > 0 then -- If we have a form value, write it to UCI local val_err fvalue, val_err = self:validate(fvalue, section) fvalue = self:transform(fvalue) if not fvalue and not novld then self:add_error(section, "invalid", val_err) end if fvalue and (self.forcewrite or not (fvalue == cvalue)) then if self:write(section, fvalue) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end end else -- Unset the UCI or error if self.rmempty or self.optional then if self:remove(section) then -- Push events self.section.changed = true --luci.util.append(self.map.events, self.events) end elseif cvalue ~= fvalue and not novld then -- trigger validator with nil value to get custom user error msg. local _, val_err = self:validate(nil, section) self:add_error(section, "missing", val_err) end end end -- Render if this value exists or if it is mandatory function AbstractValue.render(self, s, scope) if not self.optional or self.section:has_tabs() or self:cfgvalue(s) or self:formcreated(s) then scope = scope or {} scope.section = s scope.cbid = self:cbid(s) Node.render(self, scope) end end -- Return the UCI value of this object function AbstractValue.cfgvalue(self, section) local value if self.tag_error[section] then value = self:formvalue(section) else value = self.map:get(section, self.option) end if not value then return nil elseif not self.cast or self.cast == type(value) then return value elseif self.cast == "string" then if type(value) == "table" then return value[1] end elseif self.cast == "table" then return { value } end end -- Validate the form value function AbstractValue.validate(self, value) if self.datatype and value then if type(value) == "table" then local v for _, v in ipairs(value) do if v and #v > 0 and not verify_datatype(self.datatype, v) then return nil end end else if not verify_datatype(self.datatype, value) then return nil end end end return value end AbstractValue.transform = AbstractValue.validate -- Write to UCI function AbstractValue.write(self, section, value) return self.map:set(section, self.option, value) end -- Remove from UCI function AbstractValue.remove(self, section) return self.map:del(section, self.option) end --[[ Value - A one-line value maxlength: The maximum length ]]-- Value = class(AbstractValue) function Value.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/value" self.keylist = {} self.vallist = {} end function Value.reset_values(self) self.keylist = {} self.vallist = {} end function Value.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end -- DummyValue - This does nothing except being there DummyValue = class(AbstractValue) function DummyValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dvalue" self.value = nil end function DummyValue.cfgvalue(self, section) local value if self.value then if type(self.value) == "function" then value = self:value(section) else value = self.value end else value = AbstractValue.cfgvalue(self, section) end return value end function DummyValue.parse(self) end --[[ Flag - A flag being enabled or disabled ]]-- Flag = class(AbstractValue) function Flag.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/fvalue" self.enabled = "1" self.disabled = "0" self.default = self.disabled end -- A flag can only have two states: set or unset function Flag.parse(self, section) local fexists = self.map:formvalue( FEXIST_PREFIX .. self.config .. "." .. section .. "." .. self.option) if fexists then local fvalue = self:formvalue(section) and self.enabled or self.disabled local cvalue = self:cfgvalue(section) if fvalue ~= self.default or (not self.optional and not self.rmempty) then self:write(section, fvalue) else self:remove(section) end if (fvalue ~= cvalue) then self.section.changed = true end else self:remove(section) self.section.changed = true end end function Flag.cfgvalue(self, section) return AbstractValue.cfgvalue(self, section) or self.default end --[[ ListValue - A one-line value predefined in a list widget: The widget that will be used (select, radio) ]]-- ListValue = class(AbstractValue) function ListValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/lvalue" self.keylist = {} self.vallist = {} self.size = 1 self.widget = "select" end function ListValue.reset_values(self) self.keylist = {} self.vallist = {} end function ListValue.value(self, key, val, ...) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) for i, deps in ipairs({...}) do self.subdeps[#self.subdeps + 1] = {add = "-"..key, deps=deps} end end function ListValue.validate(self, val) if luci.util.contains(self.keylist, val) then return val else return nil end end --[[ MultiValue - Multiple delimited values widget: The widget that will be used (select, checkbox) delimiter: The delimiter that will separate the values (default: " ") ]]-- MultiValue = class(AbstractValue) function MultiValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/mvalue" self.keylist = {} self.vallist = {} self.widget = "checkbox" self.delimiter = " " end function MultiValue.render(self, ...) if self.widget == "select" and not self.size then self.size = #self.vallist end AbstractValue.render(self, ...) end function MultiValue.reset_values(self) self.keylist = {} self.vallist = {} end function MultiValue.value(self, key, val) if luci.util.contains(self.keylist, key) then return end val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function MultiValue.valuelist(self, section) local val = self:cfgvalue(section) if not(type(val) == "string") then return {} end return luci.util.split(val, self.delimiter) end function MultiValue.validate(self, val) val = (type(val) == "table") and val or {val} local result for i, value in ipairs(val) do if luci.util.contains(self.keylist, value) then result = result and (result .. self.delimiter .. value) or value end end return result end StaticList = class(MultiValue) function StaticList.__init__(self, ...) MultiValue.__init__(self, ...) self.cast = "table" self.valuelist = self.cfgvalue if not self.override_scheme and self.map:get_scheme(self.section.sectiontype, self.option) then local vs = self.map:get_scheme(self.section.sectiontype, self.option) if self.value and vs.values and not self.override_values then for k, v in pairs(vs.values) do self:value(k, v) end end end end function StaticList.validate(self, value) value = (type(value) == "table") and value or {value} local valid = {} for i, v in ipairs(value) do if luci.util.contains(self.keylist, v) then table.insert(valid, v) end end return valid end DynamicList = class(AbstractValue) function DynamicList.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/dynlist" self.cast = "table" self.keylist = {} self.vallist = {} end function DynamicList.reset_values(self) self.keylist = {} self.vallist = {} end function DynamicList.value(self, key, val) val = val or key table.insert(self.keylist, tostring(key)) table.insert(self.vallist, tostring(val)) end function DynamicList.write(self, section, value) local t = { } if type(value) == "table" then local x for _, x in ipairs(value) do if x and #x > 0 then t[#t+1] = x end end else t = { value } end if self.cast == "string" then value = table.concat(t, " ") else value = t end return AbstractValue.write(self, section, value) end function DynamicList.cfgvalue(self, section) local value = AbstractValue.cfgvalue(self, section) if type(value) == "string" then local x local t = { } for x in value:gmatch("%S+") do if #x > 0 then t[#t+1] = x end end value = t end return value end function DynamicList.formvalue(self, section) local value = AbstractValue.formvalue(self, section) if type(value) == "string" then if self.cast == "string" then local x local t = { } for x in value:gmatch("%S+") do t[#t+1] = x end value = t else value = { value } end end return value end --[[ TextValue - A multi-line value rows: Rows ]]-- TextValue = class(AbstractValue) function TextValue.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/tvalue" end --[[ Button ]]-- Button = class(AbstractValue) function Button.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/button" self.inputstyle = nil self.rmempty = true end FileUpload = class(AbstractValue) function FileUpload.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/upload" if not self.map.upload_fields then self.map.upload_fields = { self } else self.map.upload_fields[#self.map.upload_fields+1] = self end end function FileUpload.formcreated(self, section) return AbstractValue.formcreated(self, section) or self.map:formvalue("cbi.rlf."..section.."."..self.option) or self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") end function FileUpload.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) if val and fs.access(val) then return val end return nil end function FileUpload.formvalue(self, section) local val = AbstractValue.formvalue(self, section) if val then if not self.map:formvalue("cbi.rlf."..section.."."..self.option) and not self.map:formvalue("cbi.rlf."..section.."."..self.option..".x") then return val end fs.unlink(val) self.value = nil end return nil end function FileUpload.remove(self, section) local val = AbstractValue.formvalue(self, section) if val and fs.access(val) then fs.unlink(val) end return AbstractValue.remove(self, section) end FileBrowser = class(AbstractValue) function FileBrowser.__init__(self, ...) AbstractValue.__init__(self, ...) self.template = "cbi/browser" end
apache-2.0
lipp/tango
tango/server/zmq.lua
1
1617
local zmq = require"zmq" zmq.poller = require'zmq.poller' local serialize = require'tango.utils.serialization'.serialize local unserialize = require'tango.utils.serialization'.unserialize local dispatcher = require'tango.dispatcher' local default = require'tango.config'.server_default local print = print module('tango.server.zmq') local new = function(config) config = default(config) config.url = config.url or 'tcp://*:12345' config.context = config.context or zmq.init(1) config.poller = config.poller or zmq.poller(2) local serialize = config.serialize local unserialize = config.unserialize local dispatcher = dispatcher.new(config) local socket = config.context:socket(zmq.REP) socket:bind(config.url) local poller = config.poller local response_str local handle_request local send_response = function() socket:send(response_str) poller:modify(socket,zmq.POLLIN,handle_request) end handle_request = function() local request_str = socket:recv() if not request_str then socket:close() return end local request = unserialize(request_str) local response = dispatcher:dispatch(request) response_str = serialize(response) poller:modify(socket,zmq.POLLOUT,send_response) end poller:add(socket,zmq.POLLIN,handle_request) return config end local loop = function(config) local server = new(config) server.poller:start() server.context:term() end return { loop = loop, new = new }
mit
dromozoa/dromozoa-image
dromozoa/image/sips_reader.lua
3
2047
-- Copyright (C) 2015 Tomoyuki Fujimori <moyu@dromozoa.com> -- -- This file is part of dromozoa-image. -- -- dromozoa-image is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- dromozoa-image is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with dromozoa-image. If not, see <http://www.gnu.org/licenses/>. local sequence = require "dromozoa.commons.sequence" local shell = require "dromozoa.commons.shell" local string_reader = require "dromozoa.commons.string_reader" local write_file = require "dromozoa.commons.write_file" local class = {} class.support = shell.exec("sips >/dev/null 2>&1") function class.new(this) if type(this) == "string" then this = string_reader(this) end return { this = this; } end function class:apply() local this = self.this local commands = sequence():push("sips") commands:push("--setProperty", "format", "tga") local tmpin = os.tmpname() assert(write_file(tmpin, this:read("*a"))) commands:push(shell.quote(tmpin)) local tmpout = os.tmpname() commands:push("--out", shell.quote(tmpout)) local command = commands:concat(" ") .. " >/dev/null 2>&1" local result, what, code = shell.exec(command) os.remove(tmpin) if result == nil then os.remove(tmpout) return nil, what, code else local handle = assert(io.open(tmpout, "rb")) os.remove(tmpout) local img = class.super.read_tga(handle) handle:close() return img end end local metatable = { __index = class; } return setmetatable(class, { __call = function (_, this) return setmetatable(class.new(this), metatable) end; })
gpl-3.0
droogmic/droogmic-domoticz-lua
script_time_blinds.lua
1
8757
-- blind time script -- script names have three name components: script_trigger_name.lua -- trigger can be 'time' or 'device', name can be any string -- domoticz will execute all time and device triggers when the relevant trigger occurs -- -- copy this script and change the "name" part, all scripts named "demo" are ignored. -- -- Make sure the encoding is UTF8 of the file -- -- ingests tables: otherdevices,otherdevices_svalues -- -- otherdevices and otherdevices_svalues are two item array for all devices: -- otherdevices['yourotherdevicename']="On" -- otherdevices_svalues['yourotherthermometer'] = string of svalues -- -- Based on your logic, fill the commandArray with device commands. Device name is case sensitive. -- -- Always, and I repeat ALWAYS start by checking for a state. -- If you would only specify commandArray['AnotherDevice']='On', every time trigger (e.g. every minute) will switch AnotherDevice on. -- -- The print command will output lua print statements to the domoticz log for debugging. -- List all otherdevices states for debugging: -- for i, v in pairs(otherdevices) do print(i, v) end -- List all otherdevices svalues for debugging: -- for i, v in pairs(otherdevices_svalues) do print(i, v) end -- print('Lua Script - Timing Blinds') -- print(_VERSION) commandArray = {} t1 = os.date("*t") m1 = t1.min + t1.hour * 60 --print(m1) --TimeBlindTest if (false) then if (uservariables['TimeBlindTest'] < -3000) then m1 = timeofday['SunriseInMinutes'] + uservariables['TimeBlindTest'] + 4000 commandArray[100]={['Variable:TimeBlindTest']='0'} print('Testing mode ' .. m1) end if (uservariables['TimeBlindTest'] > -3000) and (uservariables['TimeBlindTest'] < 0) then m1 = timeofday['SunsetInMinutes'] + uservariables['TimeBlindTest'] + 2000 commandArray[100]={['Variable:TimeBlindTest']='0'} print('Testing mode ' .. m1) end if (uservariables['TimeBlindTest'] > 0) then m1 = uservariables['TimeBlindTest'] commandArray[100]={['Variable:TimeBlindTest']='0'} print('Testing mode ' .. m1) end end -- Blinds --Group1 = partial range + group2 --Group2 = full range --Group3 = privacy --Group4 = --GroupSolar if (true) then --print(otherdevices['Autoblind']) if (otherdevices['Autoblind'] == 'On') then --8am --if (m1 == 480) then --end --8:20am --if (m1 == 500) then --end --Sunrise +20 if after 8:40am(520) otherwise 8:40am --if (((m1 == timeofday['SunriseInMinutes'] + 20) and (m1 > 520)) or ((m1 == 520) and (timeofday['SunriseInMinutes'] + 20 <= 500))) then --8:40am if (m1 == 520) then commandArray[11]={['Blind Group1']='Stop'} commandArray[21]={['Blind Office']='Stop'} end --Sunrise+30 --if (m1 == timeofday['SunriseInMinutes'] + 30) then --end --Sunrise+40 if after 9:00am(540) otherwise 9:00am --if (((m1 == timeofday['SunriseInMinutes'] + 40) and (m1 > 540)) or ((m1 == 540) and (timeofday['SunriseInMinutes'] + 40 <= 540))) then --9:00am if (m1 == 540) then commandArray[12]={['Blind Group1']='Off'} commandArray[13]={['Blind Group1']='Stop AFTER 3'} commandArray[22]={['Blind Office']='Off'} commandArray[31]={['Blind Group2']='Stop'} commandArray[41]={['Blind Group3']='On'} commandArray[42]={['Blind Group3']='Stop AFTER 4'} end if (m1 == 541) then commandArray[43]={['Blind Group3']='Off'} commandArray[44]={['Blind Group3']='Stop AFTER 3'} end ---- --Sunset-60 --if (m1 == timeofday['SunsetInMinutes'] - 60) then --end --Sunset-30 --if (m1 == timeofday['SunsetInMinutes'] - 30) then --end --Sunset if (m1 == timeofday['SunsetInMinutes'] + 0) then commandArray[21]={['Blind Office']='Stop'} commandArray[31]={['Blind Group2']='On'} end if (m1 == timeofday['SunsetInMinutes'] + 1) then commandArray[22]={['Blind Office']='Off'} commandArray[23]={['Blind Office']='Stop AFTER 4'} end --Sunset+30 if (m1 == timeofday['SunsetInMinutes'] + 30) then commandArray[24]={['Blind Office']='Stop'} end --Sunset+60 if (m1 == timeofday['SunsetInMinutes'] + 60) then commandArray[11]={['Blind Group1']='Stop'} commandArray[25]={['Blind Office']='On'} end --Sunset+120 if (m1 == timeofday['SunsetInMinutes'] + 120) then commandArray[12]={['Blind Group1']='On'} commandArray[41]={['Blind Group3']='On'} end if (#commandArray>0) then print('Lua Script - TimeBlinds') print('Blinds Activated: m1 = ' .. m1) end end end -- Solarblind if (true) then -- print('power') -- print(otherdevices_svalues['Solar W']) -- print(otherdevices_svalues['Solar kWh']) -- print('midday') -- print(midday) if (otherdevices['Solarblind'] == 'On' and otherdevices['Autoblind'] == 'On') then power = tonumber(otherdevices_svalues['Solar W']) if ( uservariables["SolarProtectStatus"] ~= "On" and uservariables["SolarProtectStatus"] ~= "Off" ) then commandArray[101] = {['Variable:SolarProtectStatus']='Off'} end if (uservariables["SolarProtectStatus"] == 'Off') then midday = math.floor((timeofday['SunriseInMinutes']+timeofday['SunsetInMinutes'])/2) if ((power > 1000) or (power == 0 and m1 == midday)) then commandArray[102] = {['Variable:SolarProtectStatus']='On'} commandArray[104]={['Blind GroupSolarProtect']='Stop'} file = io.open("device_time.log", "a+") io.output(file) io.write(os.date('%F %T') .. '\t' .. m1 .. ' \tOn\nPower: ' .. power .. '\tSunrise+Sunset times: ' .. timeofday['SunriseInMinutes'] .. ' ' .. timeofday['SunsetInMinutes'] .. '\n\n') io.close(file) end end if (uservariables["SolarProtectStatus"] == 'On') then if ((power < 500 and power > 0) or (power == 0 and m1 == timeofday['SunsetInMinutes'] - 120)) then commandArray[103] = {['Variable:SolarProtectStatus']='Off'} commandArray[105]={['Blind GroupSolarProtect']='Off'} commandArray[106]={['Blind GroupSolarProtect']='Stop AFTER 3'} file = io.open("device_time.log", "a+") io.output(file) io.write(os.date('%F %T') .. '\t' .. m1 .. ' \tOff\nPower: ' .. power .. '\tSunrise+Sunset times: ' .. timeofday['SunriseInMinutes'] .. ' ' .. timeofday['SunsetInMinutes'] .. '\n\n') io.close(file) end end end end --Power measurement if (true) then --Checks if 10 minutes if (m1 % 5 == 0) then http = require('socket.http') ltn12 = require('ltn12') --http://192.168.1.31/solar_api/v1/GetInverterRealtimeData.fcgi?Scope=System --http://192.168.1.31/solar_api/GetAPIVersion.cgi base_url = uservariables['FroniusBaseURL'] t = {} req_body = '' local headers = { ["Content-Type"] = "application/json"; ["Content-Length"] = #req_body; } client, code, headers, status = http.request{url=base_url, headers=headers, source=ltn12.source.string(req_body), sink = ltn12.sink.table(t), method='GET'} --Check if page exists -- print(#t) if (#t~=0) then print('Lua Script - Power updated') json = require('json') s = table.concat(t) j = '['..s..']' --j=j:gsub('\n','') --j=j:gsub('\t','') --print(j) obj = json.decode(j) --print(obj[1].Body.Data.PAC.Values["1"]) power = obj[1].Body.Data.PAC.Values["1"] energy = obj[1].Body.Data.TOTAL_ENERGY.Values["1"] commandArray[110] = {['UpdateDevice'] = "55|0|"..power..";".. energy} commandArray[111] = {['UpdateDevice'] = "56|0|"..power} if (false) then if (otherdevices['Solarblind'] == 'On') then temp = otherdevices_temperature['Living Room'] if (temp < 18) then if (otherdevices['Blind GroupSolar'] ~= 'Stop') then midday = (timeofday['SunriseInMinutes']+timeofday['SunsetInMinutes'])/2 if ((power > 2500) or (power == 0 and((m1 - midday)<1 and (m1 - midday)>0))) then commandArray[112]={['Blind GroupSolar']='Off'} commandArray[113]={['Blind GroupSolar']='Stop AFTER 3'} file = io.open("device_time.log", "a+") io.output(file) io.write(os.date('%F %T') .. '\t' .. m1 .. ' \tUP\nTemp: ' .. temp .. '\tPower: ' .. power .. '\tSunrise+Sunset times: ' .. timeofday['SunriseInMinutes'] .. ' ' .. timeofday['SunsetInMinutes'] .. '\n\n') io.close(file) end end end if ((power < 1500 and power > 0) or (power == 0 and m1 == timeofday['SunsetInMinutes'] - 120)) then if (otherdevices['Blind GroupSolar'] == 'Stop') then commandArray[114]={['Blind GroupSolar']='On'} file = io.open("device_time.log", "a+") io.output(file) io.write(os.date('%F %T') .. '\t' .. m1 .. ' \tDOWN\nTemp: ' .. temp .. '\tPower: ' .. power .. '\tSunrise+Sunset times: ' .. timeofday['SunriseInMinutes'] .. ' ' .. timeofday['SunsetInMinutes'] .. '\n\n') io.close(file) end end end end end end end return commandArray
mit
nasomi/darkstar
scripts/zones/Port_Windurst/npcs/Kohlo-Lakolo.lua
36
10182
----------------------------------- -- Area: Port Windurst -- NPC: Kohlo-Lakolo -- Invloved In Quests: Truth, Justice, and the Onion Way!, -- Know One's Onions, -- Inspector's Gadget, -- Onion Rings, -- Crying Over Onions, -- Wild Card, -- The Promise ----------------------------------- package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/Port_Windurst/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS); if (KnowOnesOnions == QUEST_ACCEPTED) then count = trade:getItemCount(); WildOnion = trade:hasItemQty(4387,4); if (WildOnion == true and count == 4) then player:startEvent(0x018e,0,4387); end elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then count = trade:getItemCount(); RarabTail = trade:hasItemQty(4444,1); if (RarabTail == true and count == 1) then player:startEvent(0x017a,0,4444); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TruthJusticeOnionWay = player:getQuestStatus(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); KnowOnesOnions = player:getQuestStatus(WINDURST,KNOW_ONE_S_ONIONS); InspectorsGadget = player:getQuestStatus(WINDURST,INSPECTOR_S_GADGET); OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS); CryingOverOnions = player:getQuestStatus(WINDURST,CRYING_OVER_ONIONS); WildCard = player:getQuestStatus(WINDURST,WILD_CARD); ThePromise = player:getQuestStatus(WINDURST,THE_PROMISE); NeedToZone = player:needToZone(); Level = player:getMainLvl(); Fame = player:getFameLevel(WINDURST); if (ThePromise == QUEST_COMPLETED) then player:startEvent(0x0220); elseif (ThePromise == QUEST_ACCEPTED) then InvisibleManSticker = player:hasKeyItem(INVISIBLE_MAN_STICKER); if (InvisibleManSticker == true) then ThePromiseCS_Seen = player:getVar("ThePromiseCS_Seen"); if (ThePromiseCS_Seen == 1) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,THE_PROMISE); player:addFame(WINDURST,WIN_FAME*150); player:delKeyItem(INVISIBLE_MAN_STICKER); player:addItem(13135); player:messageSpecial(ITEM_OBTAINED,13135); player:setVar("ThePromise",0); player:setVar("ThePromiseCS_Seen",0); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13135); end else player:startEvent(0x020a,0,INVISIBLE_MAN_STICKER); end else player:startEvent(0x0202); end elseif (WildCard == QUEST_COMPLETED) then player:startEvent(0x0201,0,INVISIBLE_MAN_STICKER); elseif (WildCard == QUEST_ACCEPTED) then WildCardVar = player:getVar("WildCard"); if (WildCardVar == 0) then player:setVar("WildCard",1); end player:showText(npc,KOHLO_LAKOLO_DIALOG_A); elseif (CryingOverOnions == QUEST_COMPLETED) then player:startEvent(0x01f9); elseif (CryingOverOnions == QUEST_ACCEPTED) then CryingOverOnionsVar = player:getVar("CryingOverOnions"); if (CryingOverOnionsVar == 3) then player:startEvent(0x0200); elseif (CryingOverOnionsVar == 2) then player:startEvent(0x01f1); else player:startEvent(0x01f2); end elseif (OnionRings == QUEST_COMPLETED) then if (NeedToZone == false and Fame >= 5) then player:startEvent(0x01f0); else player:startEvent(0x01b8); end elseif (OnionRings == QUEST_ACCEPTED) then OldRing = player:hasKeyItem(OLD_RING); if (OldRing == true) then OnionRingsTime = player:getVar("OnionRingsTime"); CurrentTime = os.time(); if (CurrentTime >= OnionRingsTime) then player:startEvent(0x01b1); else player:startEvent(0x01af); end end elseif (InspectorsGadget == QUEST_COMPLETED) then if (NeedToZone == false and Fame >= 3) then OldRing = player:hasKeyItem(OLD_RING); if (OldRing == true) then OnionRingsVar = player:getVar("OnionRings"); if (OnionRingsVar == 1) then player:startEvent(0x01ae,0,OLD_RING); else player:startEvent(0x01b0,0,OLD_RING); end else player:startEvent(0x01ad); end else player:startEvent(0x01a6); end elseif (InspectorsGadget == QUEST_ACCEPTED) then FakeMoustache = player:hasKeyItem(FAKE_MOUSTACHE); if (FakeMoustache == true) then player:startEvent(0x01a5); else player:startEvent(0x019e); end elseif (KnowOnesOnions == QUEST_COMPLETED) then if (NeedToZone == false and Fame >= 2) then player:startEvent(0x019d); else player:startEvent(0x0191); end elseif (KnowOnesOnions == QUEST_ACCEPTED) then KnowOnesOnionsVar = player:getVar("KnowOnesOnions"); KnowOnesOnionsTime = player:getVar("KnowOnesOnionsTime"); CurrentTime = os.time(); if (KnowOnesOnionsVar == 2) then player:startEvent(0x0190); elseif (KnowOnesOnionsVar == 1 and CurrentTime >= KnowOnesOnionsTime) then player:startEvent(0x0182); elseif (KnowOnesOnionsVar == 1) then player:startEvent(0x018f,0,4387); else player:startEvent(0x0188,0,4387); end elseif (TruthJusticeOnionWay == QUEST_COMPLETED) then if (NeedToZone == false and Level >= 5) then player:startEvent(0x0187,0,4387); else player:startEvent(0x017b); end elseif (TruthJusticeOnionWay == QUEST_ACCEPTED) then player:startEvent(0x0173); elseif (TruthJusticeOnionWay == QUEST_AVAILABLE) then player:startEvent(0x0170); else player:startEvent(0x0169); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0170 and option == 0) then player:addQuest(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); elseif (csid == 0x017a) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,TRUTH_JUSTICE_AND_THE_ONION_WAY); player:addFame(WINDURST,WIN_FAME*75); player:addTitle(STAR_ONION_BRIGADE_MEMBER); player:tradeComplete(); player:addItem(13093); player:messageSpecial(ITEM_OBTAINED,13093); player:needToZone(true); else player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,13093); end elseif (csid == 0x0187) then player:addQuest(WINDURST,KNOW_ONE_S_ONIONS); elseif (csid == 0x018e) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then TradeTime = os.time(); player:tradeComplete(); player:addItem(4857); player:messageSpecial(ITEM_OBTAINED,4857); player:setVar("KnowOnesOnions",1); player:setVar("KnowOnesOnionsTime", TradeTime + 86400); else player:messageSpecial(FULL_INVENTORY_AFTER_TRADE,4857); end elseif (csid == 0x0182 or csid == 0x0190) then player:completeQuest(WINDURST,KNOW_ONE_S_ONIONS); player:addFame(WINDURST,WIN_FAME*80); player:addTitle(SOB_SUPER_HERO); player:setVar("KnowOnesOnions",0); player:setVar("KnowOnesOnionsTime",0); player:needToZone(true); elseif (csid == 0x019d and option == 0) then player:addQuest(WINDURST,INSPECTOR_S_GADGET); elseif (csid == 0x01a5) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,INSPECTOR_S_GADGET); player:addFame(WINDURST,WIN_FAME*90); player:addTitle(FAKEMOUSTACHED_INVESTIGATOR); player:addItem(13204); player:messageSpecial(ITEM_OBTAINED,13204); player:needToZone(true); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13204); end elseif (csid == 0x01ad) then player:setVar("OnionRings",1); elseif (csid == 0x01ae) then OnionRings = player:getQuestStatus(WINDURST,ONION_RINGS); if (OnionRings == QUEST_AVAILABLE) then CurrentTime = os.time(); player:addQuest(WINDURST,ONION_RINGS); player:setVar("OnionRingsTime", CurrentTime + 86400); end elseif (csid == 0x01b0 or csid == 0x01b1) then player:completeQuest(WINDURST,ONION_RINGS); player:addFame(WINDURST,WIN_FAME*100); player:addTitle(STAR_ONION_BRIGADIER); player:delKeyItem(OLD_RING); player:setVar("OnionRingsTime",0); player:needToZone(true); elseif (csid == 0x01b8) then OnionRingsVar = player:getVar("OnionRings"); NeedToZone = player:getVar("NeedToZone"); if (OnionRingsVar == 2 and NeedToZone == 0) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:setVar("OnionRings",0); player:addItem(17029); player:messageSpecial(ITEM_OBTAINED,17029); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17029); end end elseif (csid == 0x01f0) then player:addQuest(WINDURST,CRYING_OVER_ONIONS); elseif (csid == 0x01f1) then player:setVar("CryingOverOnions",3); elseif (csid == 0x0201) then player:addQuest(WINDURST,THE_PROMISE); elseif (csid == 0x020a) then FreeSlots = player:getFreeSlotsCount(); if (FreeSlots >= 1) then player:completeQuest(WINDURST,THE_PROMISE); player:addFame(WINDURST,WIN_FAME*150); player:delKeyItem(INVISIBLE_MAN_STICKER); player:addItem(13135); player:messageSpecial(ITEM_OBTAINED,13135); player:setVar("ThePromise",0); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13135); player:setVar("ThePromiseCS_Seen",1); end end end;
gpl-3.0
Hello23-Ygopro/ygopro-ds
expansions/script/c27004177.lua
1
1530
--EX03-23 Frieza, Obsession of The Clan local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_FRIEZAS_ARMY,CHARACTER_FRIEZA,SPECIAL_TRAIT_FRIEZA_CLAN) ds.AddPlayProcedure(c,COLOR_YELLOW,2,2) --negate attack ds.AddAutoAttack(c,0,true,scard.negtg,scard.negop,DS_FLAG_EFFECT_CARD_CHOOSE,scard.negcon) end scard.dragon_ball_super_card=true scard.combo_cost=0 function scard.negcon(e,tp,eg,ep,ev,re,r,rp) return ds.ldscon(aux.FilterBoolFunction(Card.IsSpecialTrait,SPECIAL_TRAIT_FRIEZA_CLAN))(e,tp,eg,ep,ev,re,r,rp) and e:GetHandler():GetFlagEffect(sid)==0 end function scard.tgfilter1(c) return c:IsSpecialTrait(SPECIAL_TRAIT_FRIEZA_CLAN) and not c:IsCharacter(CHARACTER_FRIEZA) and c:IsAbleToDrop() end scard.negtg=ds.CheckCardFunction(scard.tgfilter1,LOCATION_HAND,0) function scard.tgfilter2(c) return c:IsSpecialTrait(SPECIAL_TRAIT_FRIEZA_CLAN) and not c:IsCharacter(CHARACTER_FRIEZA) end function scard.negop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToSkill(e) or c:IsFacedown() then return end Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TODROP) local g=Duel.SelectMatchingCard(tp,scard.tgfilter2,tp,LOCATION_HAND,0,1,1,nil) if g:GetCount()==0 or Duel.SendtoDrop(g,DS_REASON_SKILL)==0 then return end Duel.NegateAttack() --negate skill Duel.NegateSkill(0) c:RegisterFlagEffect(sid,RESET_EVENT+RESETS_STANDARD+RESET_PHASE+PHASE_END,EFFECT_FLAG_CLIENT_HINT,1,0,aux.Stringid(sid,1)) end
gpl-3.0
minigeek/MMDAgent
Library_Bullet_Physics/src/Demos/OpenCLClothDemo/AMD/premake4.lua
4
1137
hasCL = findOpenCL_AMD() if (hasCL) then project "AppOpenCLClothDemo_AMD" defines { "USE_AMD_OPENCL","CL_PLATFORM_AMD"} initOpenCL_AMD() language "C++" kind "ConsoleApp" targetdir "../../.." libdirs {"../../../Glut"} links { "LinearMath", "BulletCollision", "BulletDynamics", "BulletSoftBody", "BulletSoftBodySolvers_OpenCL_AMD", "opengl32" } configuration "x64" links { "glut64", "glew64" } configuration "x32" links { "glut32", "glew32" } configuration{} includedirs { "../../../src", "../../../Glut", "../../SharedOpenCL", "../../OpenGL" } files { "../cl_cloth_demo.cpp", "../../SharedOpenCL/btOclUtils.h", "../../SharedOpenCL/btOclCommon.h", "../../SharedOpenCL/btOclUtils.cpp", "../../SharedOpenCL/btOclCommon.cpp", "../../OpenGL/GLDebugDrawer.cpp", "../../OpenGL/stb_image.cpp", "../../OpenGL/stb_image.h", "../gl_win.cpp", "../clstuff.cpp", "../clstuff.h", "../gl_win.h", "../cloth.h" } end
bsd-3-clause
cristiandonosoc/unexperiments
dotaoh/lib/hump/signal.lua
24
2729
--[[ Copyright (c) 2012-2013 Matthias Richter Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. Except as contained in this notice, the name(s) of the above copyright holders shall not be used in advertising or otherwise to promote the sale, use or other dealings in this Software without prior written authorization. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. ]]-- local Registry = {} Registry.__index = function(self, key) return Registry[key] or (function() local t = {} rawset(self, key, t) return t end)() end function Registry:register(s, f) self[s][f] = f return f end function Registry:emit(s, ...) for f in pairs(self[s]) do f(...) end end function Registry:remove(s, ...) local f = {...} for i = 1,select('#', ...) do self[s][f[i]] = nil end end function Registry:clear(...) local s = {...} for i = 1,select('#', ...) do self[s[i]] = {} end end function Registry:emit_pattern(p, ...) for s in pairs(self) do if s:match(p) then self:emit(s, ...) end end end function Registry:remove_pattern(p, ...) for s in pairs(self) do if s:match(p) then self:remove(s, ...) end end end function Registry:clear_pattern(p) for s in pairs(self) do if s:match(p) then self[s] = {} end end end local function new() return setmetatable({}, Registry) end local default = new() return setmetatable({ new = new, register = function(...) default:register(...) end, emit = function(...) default:emit(...) end, remove = function(...) default:remove(...) end, clear = function(...) default:clear(...) end, emit_pattern = function(...) default:emit_pattern(...) end, remove_pattern = function(...) default:remove_pattern(...) end, clear_pattern = function(...) default:clear_pattern(...) end, }, {__call = new})
mit
nasomi/darkstar
scripts/zones/Phomiuna_Aqueducts/npcs/qm3.lua
34
1033
----------------------------------- -- Area: Phomiuna Aqueducts -- NPC: qm3 (???) -- Notes: Opens north door @ J-9 -- @pos 116.743 -24.636 27.518 27 ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DoorOffset = npc:getID() - 2; if (GetNPCByID(DoorOffset):getAnimation() == 9) then GetNPCByID(DoorOffset):openDoor(7) -- _0ri 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
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Palguevion.lua
36
1806
----------------------------------- -- Area: Northern San d'Oria -- NPC: Palguevion -- Only sells when San d'Oria controlls Valdeaunia Region ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/globals/conquest"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(VALDEAUNIA); if (RegionOwner ~= SANDORIA) then player:showText(npc,PALGUEVION_CLOSED_DIALOG); else player:showText(npc,PALGUEVION_OPEN_DIALOG); stock = {0x111e,29, -- Frost Turnip 0x027e,170} -- Sage showShop(player,SANDORIA,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
znek/xupnpd
src/xupnpd_ssdp.lua
6
2747
-- Copyright (C) 2011-2015 Anton Burdinuk -- clark15b@gmail.com -- https://tsdemuxer.googlecode.com/svn/trunk/xupnpd ssdp_msg_alive={} ssdp_msg_byebye={} function ssdp_msg(nt,usn,nts) return string.format( 'NOTIFY * HTTP/1.1\r\n'.. 'HOST: 239.255.255.250:1900\r\n'.. 'CACHE-CONTROL: max-age=%s\r\n'.. 'LOCATION: %s\r\n'.. 'NT: %s\r\n'.. 'NTS: %s\r\n'.. 'Server: %s\r\n'.. 'USN: %s\r\n\r\n', cfg.ssdp_max_age,ssdp_location,nt,nts,ssdp_server,usn ) end ssdp_service_list= { 'upnp:rootdevice', 'urn:schemas-upnp-org:device:MediaServer:1', 'urn:schemas-upnp-org:service:ContentDirectory:1', 'urn:schemas-upnp-org:service:ConnectionManager:1', 'urn:microsoft.com:service:X_MS_MediaReceiverRegistrar:1' } function ssdp_init(t,nts) local uuid='uuid:'..ssdp_uuid table.insert(t,ssdp_msg(ssdp_uuid2,ssdp_uuid2,nts)) for i,s in ipairs(ssdp_service_list) do table.insert(t,ssdp_msg(s,ssdp_uuid2..'::'..s,nts)) end end function ssdp_alive() for i,s in ipairs(ssdp_msg_alive) do ssdp.send(s) end end function ssdp_byebye() for i,s in ipairs(ssdp_msg_byebye) do ssdp.send(s) end end function ssdp_handler(what,from,msg) if msg.reqline[1]=='M-SEARCH' and msg['man']=='ssdp:discover' then local st=msg['st'] local resp=false if st=='ssdp:all' or st==ssdp_uuid2 then resp=true else for i,s in ipairs(ssdp_service_list) do if st==s then resp=true break end end end if resp then ssdp.send(string.format( 'HTTP/1.1 200 OK\r\n'.. 'CACHE-CONTROL: max-age=%s\r\n'.. 'DATE: %s\r\n'.. 'EXT:\r\n'.. 'LOCATION: %s\r\n'.. 'Server: %s\r\n'.. 'ST: %s\r\n'.. 'USN: %s::%s\r\n\r\n', cfg.ssdp_max_age,os.date('!%a, %d %b %Y %H:%M:%S GMT'),ssdp_location,ssdp_server,st,ssdp_uuid2,st),from) end end end events["SSDP"]=ssdp_handler events["ssdp_timer"]=function (what,sec) ssdp_alive() core.timer(sec,what) end ssdp.init(cfg.ssdp_interface,1,cfg.ssdp_loop,cfg.debug) -- interface, ttl, allow_loop, debug (0,1 or 2) www_location='http://'..ssdp.interface()..':'..cfg.http_port ssdp_location=www_location..'/dev.xml' if not cfg.uuid or cfg.uuid=='' then ssdp_uuid=core.uuid() else ssdp_uuid=cfg.uuid end ssdp_uuid2='uuid:'..ssdp_uuid ssdp_server='eXtensible UPnP agent' ssdp_init(ssdp_msg_alive,'ssdp:alive') ssdp_init(ssdp_msg_byebye,'ssdp:byebye') ssdp_alive() core.timer(cfg.ssdp_notify_interval,"ssdp_timer") table.insert(atexit,ssdp_byebye)
gpl-2.0
shangjiyu/luci-with-extra
applications/luci-app-pbx/luasrc/model/cbi/pbx-advanced.lua
18
14476
--[[ 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(0)" 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
nasomi/darkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Zarfhid.lua
34
1034
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Zarfhid -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00DC); 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
nasomi/darkstar
scripts/zones/Temenos/bcnms/Central_Temenos_1st_Floor.lua
19
1075
----------------------------------- -- Area: Temenos -- Name: ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) SetServerVariable("[C_Temenos_1st]UniqueID",GenerateLimbusKey()); HideArmouryCrates(GetInstanceRegion(1303),TEMENOS); HideTemenosDoor(GetInstanceRegion(1303)); player:setVar("Limbus_Trade_Item-T",0); end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) player:setVar("limbusbitmap",0); player:setVar("characterLimbusKey",GetServerVariable("[C_Temenos_1st]UniqueID")); player:setVar("LimbusID",1303); player:delKeyItem(COSMOCLEANSE); player:delKeyItem(WHITE_CARD); end; -- Leaving by every mean possible, given by the LeaveCode -- 3=Disconnected or warped out (if dyna is empty: launch 4 after 3) -- 4=Finish he dynamis function onBcnmLeave(player,instance,leavecode) --print("leave code "..leavecode); if (leavecode == 4) then player:setPos(580,-1.5,4.452,192); ResetPlayerLimbusVariable(player) end end;
gpl-3.0
akornatskyy/lucid
src/security/crypto/ticket.lua
1
1920
local struct = require 'struct' local rand = require 'security.crypto.rand' local pack, unpack, rand_bytes = struct.pack, struct.unpack, rand.bytes local assert, type, time = assert, type, os.time local setmetatable = setmetatable local Ticket = { encode = function(self, s) local b = rand_bytes(12) s = self.cipher:encrypt( b:sub(1, 4) .. pack('<I4', time() + self.max_age) .. b:sub(5, 8) .. s .. b:sub(9, 12)) return self.encoder.encode(self.digest(s) .. s) end, decode = function(self, s) s = self.encoder.decode(s) if not s then return nil, 'unable to decode' end local t = s:sub(1, self.digest_size) s = s:sub(1 + self.digest_size) if t ~= self.digest(s) then return nil, 'signature missmatch' end s = self.cipher:decrypt(s) if not s then return nil, 'unable to decrypt' end t = unpack('<I4', s:sub(5, 8)) - time() if t < 0 or t > self.max_age then return nil, 'expired' end return s:sub(13, -5), t end } local mt = {__index = Ticket} local new = function(self) if type(self.digest) == 'string' then local d = require 'security.crypto.digest' self.digest = d.new(self.digest) elseif type(self.digest) ~= 'function' then error('digest: string or function expected', 2) end if not self.encoder then self.encoder = require 'core.encoding.base64' end assert(self.cipher) assert(self.cipher.encrypt) assert(self.cipher.decrypt) assert(self.encoder) assert(self.encoder.encode) assert(self.encoder.decode) if not self.max_age then self.max_age = 900 end self.digest_size = self.digest(''):len() return setmetatable(self, mt) end return { new = new }
mit
nasomi/darkstar
scripts/zones/Metalworks/npcs/Topuru-Kuperu.lua
38
1044
----------------------------------- -- Area: Metalworks -- NPC: Topuru-Kuperu -- Type: Standard NPC -- @zone: 237 -- @pos 28.284 -17.39 42.269 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00fb); 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
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/sn69.meta.lua
2
3245
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = { "0 255 255 255", "0 222 255 255", "0 78 255 255", "6 0 255 255" }, radius = { x = 120, y = 120 }, standard_deviation = 5 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = -7 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = -9, y = 3 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = -8 }, rotation = -90 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = -10, y = 1 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = { 4, 5, 0, 3, 4, 3, 0, 1, 2, 3 }, original_poly = { { x = -15.5, y = -10 }, { x = 15.5, y = -10 }, { x = 15, y = -5 }, { x = -4, y = 3 }, { x = -7, y = 9 }, { x = -15.5, y = 10 } } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
nasomi/darkstar
scripts/zones/Norg/npcs/Paito-Maito.lua
34
2624
----------------------------------- -- Area: Norg -- NPC: Paito-Maito -- Standard Info NPC ----------------------------------- require("scripts/globals/pathfind"); local path = { -71.189713, -9.413510, 74.024879, -71.674171, -9.317029, 73.054794, -72.516525, -9.298064, 72.363213, -73.432983, -9.220915, 71.773857, -74.358955, -9.142115, 71.163277, -75.199585, -9.069098, 70.583145, -76.184708, -9.006280, 70.261375, -77.093193, -9.000236, 70.852921, -77.987053, -9.037421, 71.464264, -79.008476, -9.123112, 71.825165, -80.083740, -9.169785, 72.087944, -79.577698, -9.295252, 73.087708, -78.816307, -9.365192, 73.861855, -77.949852, -9.323165, 74.500496, -76.868950, -9.301287, 74.783707, -75.754913, -9.294973, 74.927345, -74.637566, -9.341335, 74.902016, -73.521400, -9.382154, 74.747322, -72.420792, -9.415255, 74.426178, -71.401161, -9.413510, 74.035446, -70.392426, -9.413510, 73.627884, -69.237152, -9.413510, 73.155815, -70.317207, -9.413510, 73.034027, -71.371315, -9.279585, 72.798569, -72.378838, -9.306310, 72.392982, -73.315544, -9.230491, 71.843933, -74.225883, -9.153550, 71.253113, -75.120522, -9.076024, 70.638908, -76.054642, -9.019394, 70.204910, -76.981323, -8.999838, 70.762978, -77.856903, -9.024825, 71.403915, -78.876686, -9.115798, 71.789764, -79.930756, -9.171277, 72.053635, -79.572502, -9.295024, 73.087646, -78.807686, -9.364762, 73.869614, -77.916420, -9.321617, 74.516357, -76.824738, -9.300390, 74.790466, -75.738380, -9.295794, 74.930130, -74.620911, -9.341956, 74.899994, -73.493645, -9.382988, 74.739204, -72.413185, -9.415321, 74.420128, -71.452393, -9.413510, 74.054657, -70.487755, -9.413510, 73.666130 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(pathfind.first(path)); -- onPath(npc); end; function onPath(npc) pathfind.patrol(npc, path); end; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x005A); npc:wait(-1); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option,npc) --printf("CSID: %u",csid); --printf("RESULT: %u",option); npc:wait(0); end;
gpl-3.0
texane/opende_kaapi
build/premake4.lua
1
13306
---------------------------------------------------------------------- -- Premake4 configuration script for OpenDE -- Contributed by Jason Perkins (starkos@industriousone.com) -- For more information on Premake: http://industriousone.com/premake ---------------------------------------------------------------------- ---------------------------------------------------------------------- -- Demo list: add/remove demos from here and the rest of the build -- should just work. ---------------------------------------------------------------------- local demos = { "boxstack", "buggy", "cards", "chain1", "chain2", "collision", "crash", "cylvssphere", "feedback", "friction", "gyroscopic", "heightfield", "hinge", "I", "jointPR", "jointPU", "joints", "kinematic", "motion", "motor", "ode", "piston", "plane2d", "slider", "space", "space_stress", "step", } local trimesh_demos = { "basket", "cyl", "moving_trimesh", "trimesh", } if not _OPTIONS["no-trimesh"] then demos = table.join(demos, trimesh_demos) end ---------------------------------------------------------------------- -- Configuration options ---------------------------------------------------------------------- newoption { trigger = "with-demos", description = "Builds the demo applications and DrawStuff library" } newoption { trigger = "with-tests", description = "Builds the unit test application" } newoption { trigger = "with-gimpact", description = "Use GIMPACT for trimesh collisions (experimental)" } newoption { trigger = "all-collis-libs", description = "Include sources of all collision libraries into the project" } newoption { trigger = "with-libccd", description = "Uses libccd for handling some collision tests absent in ODE." } newoption { trigger = "no-dif", description = "Exclude DIF (Dynamics Interchange Format) exports" } newoption { trigger = "no-trimesh", description = "Exclude trimesh collision geometry" } newoption { trigger = "enable-ou", description = "Use TLS for global variables (experimental)" } newoption { trigger = "16bit-indices", description = "Use 16-bit indices for trimeshes (default is 32-bit)" } newoption { trigger = "old-trimesh", description = "Use old OPCODE trimesh-trimesh collider" } newoption { trigger = "to", value = "path", description = "Set the output location for the generated project files" } newoption { trigger = "only-shared", description = "Only build shared (DLL) version of the library" } newoption { trigger = "only-static", description = "Only build static versions of the library" } newoption { trigger = "only-single", description = "Only use single-precision math" } newoption { trigger = "only-double", description = "Only use double-precision math" } -- always clean all of the optional components and toolsets if _ACTION == "clean" then _OPTIONS["with-demos"] = "" _OPTIONS["with-tests"] = "" for action in premake.action.each() do os.rmdir(action.trigger) end end -- special validation for Xcode if _ACTION == "xcode3" and (not _OPTIONS["only-single"] and not _OPTIONS["only-double"]) then error( "Xcode does not support different library types in a single project.\n" .. "Please use one of the flags: --only-static or --only-shared", 0) end -- build the list of configurations, based on the flags. Ends up -- with configurations like "Debug", "DebugSingle" or "DebugSingleShared" local configs = { "Debug", "Release" } local function addconfigs(...) local newconfigs = { } for _, root in ipairs(configs) do for _, suffix in ipairs(arg) do table.insert(newconfigs, root .. suffix) end end configs = newconfigs end if not _OPTIONS["only-single"] and not _OPTIONS["only-double"] then addconfigs("Single", "Double") end if not _OPTIONS["only-shared"] and not _OPTIONS["only-static"] then addconfigs("DLL", "Lib") end ---------------------------------------------------------------------- -- The solution, and solution-wide settings ---------------------------------------------------------------------- solution "ode" language "C++" uuid "4DA77C12-15E5-497B-B1BB-5100D5161E15" location ( _OPTIONS["to"] or _ACTION ) includedirs { "../include", "../ode/src" } -- apply the configuration list built above configurations (configs) configuration { "Debug*" } defines { "_DEBUG" } flags { "Symbols" } configuration { "Release*" } flags { "OptimizeSpeed", "NoFramePointer" } configuration { "only-single or *Single*" } defines { "dSINGLE", "CCD_SINGLE" } configuration { "only-double or *Double*" } defines { "dDOUBLE", "CCD_DOUBLE" } configuration { "Windows" } defines { "WIN32" } configuration { "MacOSX" } linkoptions { "-framework Carbon" } -- give each configuration a unique output directory for _, name in ipairs(configurations()) do configuration { name } targetdir ( "../lib/" .. name ) end -- disable Visual Studio security warnings configuration { "vs*" } defines { "_CRT_SECURE_NO_DEPRECATE" } -- don't remember why we had to do this configuration { "vs2002 or vs2003", "*Lib" } flags { "StaticRuntime" } ---------------------------------------------------------------------- -- The demo projects, automated from list above. These go first so -- they will be selected as the active project automatically in IDEs ---------------------------------------------------------------------- if _OPTIONS["with-demos"] then for _, name in ipairs(demos) do project ( "demo_" .. name ) kind "ConsoleApp" location ( _OPTIONS["to"] or _ACTION ) files { "../ode/demo/demo_" .. name .. ".*" } links { "ode", "drawstuff" } configuration { "Windows" } files { "../drawstuff/src/resources.rc" } links { "user32", "winmm", "gdi32", "opengl32", "glu32" } configuration { "MacOSX" } linkoptions { "-framework Carbon -framework OpenGL -framework AGL" } configuration { "not Windows", "not MacOSX" } links { "GL", "GLU" } end end ---------------------------------------------------------------------- -- The ODE library project ---------------------------------------------------------------------- project "ode" -- kind "StaticLib" location ( _OPTIONS["to"] or _ACTION ) includedirs { "../ode/src/joints", "../OPCODE", "../GIMPACT/include", "../ou/include", "../libccd/src" } files { "../include/ode/*.h", "../ode/src/joints/*.h", "../ode/src/joints/*.cpp", "../ode/src/*.h", "../ode/src/*.c", "../ode/src/*.cpp", } excludes { "../ode/src/collision_std.cpp", } configuration { "no-dif" } excludes { "../ode/src/export-dif.cpp" } configuration { "no-trimesh" } excludes { "../ode/src/collision_trimesh_colliders.h", "../ode/src/collision_trimesh_internal.h", "../ode/src/collision_trimesh_opcode.cpp", "../ode/src/collision_trimesh_gimpact.cpp", "../ode/src/collision_trimesh_box.cpp", "../ode/src/collision_trimesh_ccylinder.cpp", "../ode/src/collision_cylinder_trimesh.cpp", "../ode/src/collision_trimesh_distance.cpp", "../ode/src/collision_trimesh_ray.cpp", "../ode/src/collision_trimesh_sphere.cpp", "../ode/src/collision_trimesh_trimesh.cpp", "../ode/src/collision_trimesh_plane.cpp" } configuration { "not no-trimesh", "with-gimpact or all-collis-libs" } files { "../GIMPACT/**.h", "../GIMPACT/**.cpp" } configuration { "not no-trimesh", "not with-gimpact" } files { "../OPCODE/**.h", "../OPCODE/**.cpp" } configuration { "enable-ou" } files { "../ou/**.h", "../ou/**.cpp" } defines { "_OU_NAMESPACE=odeou" } configuration { "with-libccd" } files { "../libccd/src/ccd/*.h", "../libccd/src/*.c", "../ode/src/collision_libccd.cpp", "../ode/src/collision_libccd.h" } defines { "dLIBCCD_ENABLED", "dLIBCCD_CYL_CYL" } configuration { "not with-libccd" } excludes { "../ode/src/collision_libccd.cpp", "../ode/src/collision_libccd.h" } configuration { "windows" } links { "user32" } configuration { "only-static or *Lib" } kind "StaticLib" defines "ODE_LIB" configuration { "only-shared or *DLL" } kind "SharedLib" defines "ODE_DLL" configuration { "Debug" } targetname "oded" configuration { "Release" } targetname "ode" configuration { "DebugSingle*" } targetname "ode_singled" configuration { "ReleaseSingle*" } targetname "ode_single" configuration { "DebugDouble*" } targetname "ode_doubled" configuration { "ReleaseDouble*" } targetname "ode_double" ---------------------------------------------------------------------- -- Write a custom <config.h> to src/ode, based on the supplied flags ---------------------------------------------------------------------- if _ACTION then io.input("config-default.h") local text = io.read("*a") if _OPTIONS["no-trimesh"] then text = string.gsub(text, "#define dTRIMESH_ENABLED 1", "/* #define dTRIMESH_ENABLED 1 */") text = string.gsub(text, "#define dTRIMESH_OPCODE 1", "/* #define dTRIMESH_OPCODE 1 */") elseif (_OPTIONS["with-gimpact"]) then text = string.gsub(text, "#define dTRIMESH_OPCODE 1", "#define dTRIMESH_GIMPACT 1") end if _OPTIONS["enable-ou"] then text = string.gsub(text, "/%* #define dOU_ENABLED 1 %*/", "#define dOU_ENABLED 1") text = string.gsub(text, "/%* #define dATOMICS_ENABLED 1 %*/", "#define dATOMICS_ENABLED 1") text = string.gsub(text, "/%* #define dTLS_ENABLED 1 %*/", "#define dTLS_ENABLED 1") end if _OPTIONS["16bit-indices"] then text = string.gsub(text, "#define dTRIMESH_16BIT_INDICES 0", "#define dTRIMESH_16BIT_INDICES 1") end if _OPTIONS["old-trimesh"] then text = string.gsub(text, "#define dTRIMESH_OPCODE_USE_OLD_TRIMESH_TRIMESH_COLLIDER 0", "#define dTRIMESH_OPCODE_USE_OLD_TRIMESH_TRIMESH_COLLIDER 1") end io.output("../ode/src/config.h") io.write(text) io.close() end ---------------------------------------------------------------------- -- The DrawStuff library project ---------------------------------------------------------------------- if _OPTIONS["with-demos"] then project "drawstuff" location ( _OPTIONS["to"] or _ACTION ) files { "../include/drawstuff/*.h", "../drawstuff/src/internal.h", "../drawstuff/src/drawstuff.cpp" } configuration { "Debug*" } targetname "drawstuffd" configuration { "only-static or *Lib" } kind "StaticLib" defines { "DS_LIB" } configuration { "only-shared or *DLL" } kind "SharedLib" defines { "DS_DLL", "USRDLL" } configuration { "Windows" } files { "../drawstuff/src/resource.h", "../drawstuff/src/resources.rc", "../drawstuff/src/windows.cpp" } links { "user32", "opengl32", "glu32", "winmm", "gdi32" } configuration { "MacOSX" } defines { "HAVE_APPLE_OPENGL_FRAMEWORK" } files { "../drawstuff/src/osx.cpp" } linkoptions { "-framework Carbon -framework OpenGL -framework AGL" } configuration { "not Windows", "not MacOSX" } files { "../drawstuff/src/x11.cpp" } links { "X11", "GL", "GLU" } end ---------------------------------------------------------------------- -- The automated test application ---------------------------------------------------------------------- if _OPTIONS["with-tests"] then project "tests" kind "ConsoleApp" location ( _OPTIONS["to"] or _ACTION ) includedirs { "../tests/UnitTest++/src" } files { "../tests/*.cpp", "../tests/joints/*.cpp", "../tests/UnitTest++/src/*" } links { "ode" } configuration { "Windows" } files { "../tests/UnitTest++/src/Win32/*" } configuration { "not Windows" } files { "../tests/UnitTest++/src/Posix/*" } -- add post-build step to automatically run test executable local path_to_lib = path.getrelative(location(), "../lib") local command = path.translate(path.join(path_to_lib, "%s/tests")) for _, name in ipairs(configurations()) do configuration { name } postbuildcommands { command:format(name) } end end
lgpl-2.1
shangjiyu/luci-with-extra
applications/luci-app-cpulimit/luasrc/model/cbi/cpulimit.lua
20
1274
m = Map("cpulimit", translate("cpulimit"),translate("Use cpulimit to limit app's cpu using.")) s = m:section(TypedSection, "list", translate("Settings")) s.template = "cbi/tblsection" s.anonymous = true s.addremove = true enable = s:option(Flag, "enabled", translate("enable", "enable")) enable.optional = false enable.rmempty = false local pscmd="ps | awk '{print $5}' | sed '1d' | sort -k2n | uniq | sed '/^\\\[/d' | sed '/sed/d' | sed '/awk/d' | sed '/hostapd/d' | sed '/pppd/d' | sed '/mwan3/d' | sed '/sleep/d' | sed '/sort/d' | sed '/ps/d' | sed '/uniq/d' | awk -F '/' '{print $NF}'" local shellpipe = io.popen(pscmd,"r") exename = s:option(Value, "exename", translate("exename"), translate("name of the executable program file.CAN NOT BE A PATH!")) exename.optional = false exename.rmempty = false exename.default = "vsftpd" for psvalue in shellpipe:lines() do exename:value(psvalue) end limit = s:option(Value, "limit", translate("limit")) limit.optional = false limit.rmempty = false limit.default = "50" limit:value("100","100%") limit:value("90","90%") limit:value("80","80%") limit:value("70","70%") limit:value("60","60%") limit:value("50","50%") limit:value("40","40%") limit:value("30","30%") limit:value("20","20%") limit:value("10","10%") return m
apache-2.0
nasomi/darkstar
scripts/zones/Altar_Room/npcs/Magicite.lua
19
1576
----------------------------------- -- Area: Altar Room -- NPC: Magicite -- Involved in Mission: Magicite -- @zone 152 -- @pos -344 25 43 ----------------------------------- package.loaded["scripts/zones/Altar_Room/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Altar_Room/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(player:getNation()) == 13 and player:hasKeyItem(MAGICITE_ORASTONE) == false) then if (player:getVar("MissionStatus") < 4) then player:startEvent(0x002c,1); -- play Lion part of the CS (this is first magicite) else player:startEvent(0x002c); -- don't play Lion part of the CS end else player:messageSpecial(THE_MAGICITE_GLOWS_OMINOUSLY); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x002c) then player:setVar("MissionStatus",4); player:addKeyItem(MAGICITE_ORASTONE); player:messageSpecial(KEYITEM_OBTAINED,MAGICITE_ORASTONE); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/crepe_caprice.lua
36
1318
----------------------------------------- -- ID: 5776 -- Item: Crepe Caprice -- Food Effect: 60 Min, All Races ----------------------------------------- -- HP +20 -- MP Healing 3 -- Magic Accuracy +5 -- Magic Defense +2 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5776); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_MPHEAL, 3); target:addMod(MOD_MACC, 5); target:addMod(MOD_MDEF, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_MPHEAL, 3); target:delMod(MOD_MACC, 5); target:delMod(MOD_MDEF, 2); end;
gpl-3.0
nasomi/darkstar
scripts/zones/North_Gustaberg_[S]/npcs/Gebhardt.lua
19
1206
----------------------------------- -- Area: North Gustaberg (S) (I-6) -- NPC: Gebhardt -- Involved in Quests: The Fighting Fourth ----------------------------------- package.loaded["scripts/zones/North_Gustaberg_[S]/TextIDs"] = nil; package.loaded["scripts/globals/quests"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/North_Gustaberg_[S]/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(CRYSTAL_WAR,THE_FIGHTING_FOURTH) == QUEST_ACCEPTED and player:hasKeyItem(917)) == true then player:startEvent(0x0066) else player:startEvent(0x006E) end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0066) then player:delKeyItem(BATTLE_RATIONS); player:setVar("THE_FIGHTING_FOURTH",1); end end;
gpl-3.0
EnjoyHacking/nn
SparseJacobian.lua
61
8618
nn.SparseJacobian = {} function nn.SparseJacobian.backward (module, input, param, dparam) local doparam = 0 if param then doparam = 1 end -- output deriv module:forward(input) local dout = module.output.new():resizeAs(module.output) -- 1D view local sdout = module.output.new(dout:storage(), 1, dout:nElement()) -- jacobian matrix to calculate local jacobian if doparam == 1 then jacobian = torch.Tensor(param:nElement(), dout:nElement()):zero() else jacobian = torch.Tensor(input:size(1), dout:nElement()):zero() end for i=1,sdout:nElement() do dout:zero() sdout[i] = 1 module:zeroGradParameters() local din = module:updateGradInput(input, dout) module:accGradParameters(input, dout) if doparam == 1 then jacobian:select(2,i):copy(dparam) else jacobian:select(2,i):copy(din:select(2,2)) end end return jacobian end function nn.SparseJacobian.backwardUpdate (module, input, param) -- output deriv module:forward(input) local dout = module.output.new():resizeAs(module.output) -- 1D view local sdout = module.output.new(dout:storage(),1,dout:nElement()) -- jacobian matrix to calculate local jacobian = torch.Tensor(param:nElement(),dout:nElement()):zero() -- original param local params = module:parameters() local origparams = {} for j=1,#params do table.insert(origparams, params[j]:clone()) end for i=1,sdout:nElement() do -- Reset parameters for j=1,#params do params[j]:copy(origparams[j]) end dout:zero() sdout[i] = 1 module:zeroGradParameters() module:updateGradInput(input, dout) module:accUpdateGradParameters(input, dout, 1) jacobian:select(2,i):copy(param) end for j=1,#params do params[j]:copy(origparams[j]) end return jacobian end function nn.SparseJacobian.forward(module, input, param) local doparam = 0 if param then doparam = 1 end param = param or input -- perturbation amount local small = 1e-6 -- 1D view of input --local tst = param:storage() local sin if doparam == 1 then sin = param.new(param):resize(param:nElement()) else sin = input.new(input):select(2,2) end local out = module:forward(input) -- jacobian matrix to calculate local jacobian if doparam == 1 then jacobian = torch.Tensor():resize(param:nElement(), out:nElement()) else jacobian = torch.Tensor():resize(input:size(1), out:nElement()) end local outa = torch.Tensor(jacobian:size(2)) local outb = torch.Tensor(jacobian:size(2)) for i=1,sin:nElement() do sin[i] = sin[i] - small outa:copy(module:forward(input)) sin[i] = sin[i] + 2*small outb:copy(module:forward(input)) sin[i] = sin[i] - small outb:add(-1,outa):div(2*small) jacobian:select(1,i):copy(outb) end return jacobian end function nn.SparseJacobian.forwardUpdate(module, input, param) -- perturbation amount local small = 1e-6 -- 1D view of input --local tst = param:storage() local sin = param.new(param):resize(param:nElement())--param.new(tst,1,tst:size()) -- jacobian matrix to calculate local jacobian = torch.Tensor():resize(param:nElement(),module:forward(input):nElement()) local outa = torch.Tensor(jacobian:size(2)) local outb = torch.Tensor(jacobian:size(2)) for i=1,sin:nElement() do sin[i] = sin[i] - small outa:copy(module:forward(input)) sin[i] = sin[i] + 2*small outb:copy(module:forward(input)) sin[i] = sin[i] - small outb:add(-1,outa):div(2*small) jacobian:select(1,i):copy(outb) jacobian:select(1,i):mul(-1) jacobian:select(1,i):add(sin[i]) end return jacobian end function nn.SparseJacobian.testJacobian (module, input, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval)) local jac_fprop = nn.SparseJacobian.forward(module,input) local jac_bprop = nn.SparseJacobian.backward(module,input) local error = jac_fprop-jac_bprop return error:abs():max() end function nn.SparseJacobian.testJacobianParameters (module, input, param, dparam, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval)) param:copy(torch.rand(param:nElement()):mul(inrange):add(minval)) local jac_bprop = nn.SparseJacobian.backward(module, input, param, dparam) local jac_fprop = nn.SparseJacobian.forward(module, input, param) local error = jac_fprop - jac_bprop return error:abs():max() end function nn.SparseJacobian.testJacobianUpdateParameters (module, input, param, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval input:select(2,2):copy(torch.rand(input:size(1)):mul(inrange):add(minval)) param:copy(torch.rand(param:nElement()):mul(inrange):add(minval)) local params_bprop = nn.SparseJacobian.backwardUpdate(module, input, param) local params_fprop = nn.SparseJacobian.forwardUpdate(module, input, param) local error = params_fprop - params_bprop return error:abs():max() end function nn.SparseJacobian.testIO(module,input, minval, maxval) minval = minval or -2 maxval = maxval or 2 local inrange = maxval - minval -- run module module:forward(input) local go = module.output:clone():copy(torch.rand(module.output:nElement()):mul(inrange):add(minval)) module:zeroGradParameters() module:updateGradInput(input,go) module:accGradParameters(input,go) local fo = module.output:clone() local bo = module.gradInput:clone() -- write module local f = torch.DiskFile('tmp.bin','w'):binary() f:writeObject(module) f:close() -- read module local m = torch.DiskFile('tmp.bin'):binary():readObject() m:forward(input) m:zeroGradParameters() m:updateGradInput(input,go) m:accGradParameters(input,go) -- cleanup os.remove('tmp.bin') local fo2 = m.output:clone() local bo2 = m.gradInput:clone() local errf = fo - fo2 local errb = bo - bo2 return errf:abs():max(), errb:abs():max() end function nn.SparseJacobian.testAllUpdate(module, input, weight, gradWeight) local gradOutput local lr = torch.uniform(0.1, 1) local errors = {} -- accGradParameters local maccgp = module:clone() local weightc = maccgp[weight]:clone() maccgp:forward(input) gradOutput = torch.rand(maccgp.output:size()) maccgp:zeroGradParameters() maccgp:updateGradInput(input, gradOutput) maccgp:accGradParameters(input, gradOutput) maccgp:updateParameters(lr) errors["accGradParameters"] = (weightc-maccgp[gradWeight]*lr-maccgp[weight]):norm() -- accUpdateGradParameters local maccugp = module:clone() maccugp:forward(input) maccugp:updateGradInput(input, gradOutput) maccugp:accUpdateGradParameters(input, gradOutput, lr) errors["accUpdateGradParameters"] = (maccugp[weight]-maccgp[weight]):norm() -- shared, accGradParameters local macsh1 = module:clone() local macsh2 = module:clone() macsh2:share(macsh1, weight) macsh1:forward(input) macsh2:forward(input) macsh1:zeroGradParameters() macsh2:zeroGradParameters() macsh1:updateGradInput(input, gradOutput) macsh2:updateGradInput(input, gradOutput) macsh1:accGradParameters(input, gradOutput) macsh2:accGradParameters(input, gradOutput) macsh1:updateParameters(lr) macsh2:updateParameters(lr) local err = (weightc-maccgp[gradWeight]*(lr*2)-macsh1[weight]):norm() err = err + (weightc-maccgp[gradWeight]*(lr*2)-macsh2[weight]):norm() errors["accGradParameters [shared]"] = err -- shared, accUpdateGradParameters local macshu1 = module:clone() local macshu2 = module:clone() macshu2:share(macshu1, weight) macshu1:forward(input) macshu2:forward(input) macshu1:updateGradInput(input, gradOutput) macshu2:updateGradInput(input, gradOutput) macshu1:accUpdateGradParameters(input, gradOutput, lr) macshu2:accUpdateGradParameters(input, gradOutput, lr) err = (weightc-maccgp[gradWeight]*(lr*2)-macshu1[weight]):norm() err = err + (weightc-maccgp[gradWeight]*(lr*2)-macshu2[weight]):norm() errors["accUpdateGradParameters [shared]"] = err return errors end
bsd-3-clause
EnjoyHacking/nn
SpatialDropout.lua
33
1453
local SpatialDropout, Parent = torch.class('nn.SpatialDropout', 'nn.Module') function SpatialDropout:__init(p) Parent.__init(self) self.p = p or 0.5 self.train = true self.noise = torch.Tensor() end function SpatialDropout:updateOutput(input) self.output:resizeAs(input):copy(input) if self.train then if input:dim() == 4 then self.noise:resize(input:size(1), input:size(2), 1, 1) elseif input:dim() == 3 then self.noise:resize(input:size(1), 1, 1) else error('Input must be 4D (nbatch, nfeat, h, w) or 3D (nfeat, h, w)') end self.noise:bernoulli(1-self.p) -- We expand the random dropouts to the entire feature map because the -- features are likely correlated accross the map and so the dropout -- should also be correlated. self.output:cmul(torch.expandAs(self.noise, input)) else self.output:mul(1-self.p) end return self.output end function SpatialDropout:updateGradInput(input, gradOutput) if self.train then self.gradInput:resizeAs(gradOutput):copy(gradOutput) self.gradInput:cmul(torch.expandAs(self.noise, input)) -- simply mask the gradients with the noise vector else error('backprop only defined while training') end return self.gradInput end function SpatialDropout:setp(p) self.p = p end function SpatialDropout:__tostring__() return string.format('%s(%f)', torch.type(self), self.p) end
bsd-3-clause
nasomi/darkstar
scripts/zones/Nashmau/npcs/Yoyoroon.lua
34
1613
----------------------------------- -- Area: Nashmau -- NPC: Yoyoroon -- Standard Merchant NPC ----------------------------------- package.loaded["scripts/zones/Nashmau/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Nashmau/TextIDs"); require("scripts/globals/shop"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,YOYOROON_SHOP_DIALOG); stock = {0x08BF,4940, -- Tension Spring 0x08C0,9925, -- Inhibitor 0x08C2,9925, -- Mana Booster 0x08C3,4940, -- Loudspeaker 0x08C6,4940, -- Accelerator 0x08C7,9925, -- Scope 0x08CA,9925, -- Shock Absorber 0x08CB,4940, -- Armor Plate 0x08CE,4940, -- Stabilizer 0x08CF,9925, -- Volt Gun 0x08D2,4940, -- Mana Jammer 0x08D4,9925, -- Stealth Screen 0x08D6,4940, -- Auto-Repair Kit 0x08D8,9925, -- Damage Gauge 0x08DA,4940, -- Mana Tank 0x08DC,9925} -- Mana Conserver showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
MatthewDwyer/botman
mudlet/profiles/newbot/scripts/chat/gmsg_friends.lua
1
25483
--[[ Botman - A collection of scripts for managing 7 Days to Die servers Copyright (C) 2020 Matthew Dwyer This copyright applies to the Lua source code in this Mudlet profile. Email smegzor@gmail.com URL http://botman.nz Source https://bitbucket.org/mhdwyer/botman --]] local pid, pname, debug, max, result, help, tmp local shortHelp = false local skipHelp = false debug = false -- should be false unless testing function gmsg_friends() calledFunction = "gmsg_friends" result = false tmp = {} if botman.debugAll then debug = true -- this should be true end -- ################## Friend command functions ################## local function cmd_AddFriend() local playerName if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}friend {player}" help[2] = "Tell the bot that a player is your friend. The bot can also read your friend list directly from the game. If you only friend them using this command, they will not be friended on the server itself only in the bot." tmp.command = help[1] tmp.keywords = "add,friend" tmp.accessLevel = 99 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "add") or string.find(chatvars.command, "friend") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end -- Say hello to my little friend if (chatvars.words[1] == "friend") and (chatvars.playerid ~= 0) then pname = string.sub(chatvars.command, string.find(chatvars.command, "friend ") + 7) pname = string.trim(pname) id = LookupPlayer(pname) if id == 0 then id = LookupArchivedPlayer(pname) if id ~= 0 then playerName = playersArchived[id].name end else playerName = players[id].name end if (id == 0) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Imaginary friends don't count. Unless you work for the FCC, pick someone that exists.[-]") botman.faultyChat = false return true end if (id == chatvars.playerid) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]I know you are lonely but you're supposed to make friends with OTHER people.[-]") botman.faultyChat = false return true end -- add to friends table if (friends[chatvars.playerid].friends == nil) then friends[chatvars.playerid] = {} friends[chatvars.playerid].friends = "" end if addFriend(chatvars.playerid, id, false) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]" .. playerName .. " is now recognised as a friend[-]") else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You are already friends with " .. playerName .. ".[-]") end botman.faultyChat = false return true end end local function cmd_ForgetFriends() local PlayerName if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}clear friends {player} (only admins can specify a player)" help[2] = "Clear your friends list. Note that this does not unfriend players that you friended via your game. You will need to unfriend those players there yourself." tmp.command = help[1] tmp.keywords = "del,remo,forget,friend" tmp.accessLevel = 99 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "clear") or string.find(chatvars.command, "friend") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end -- FORGET FREEMAN! if (chatvars.words[1] == "clear" and chatvars.words[2] == "friends") and (chatvars.playerid ~= 0) then if (chatvars.accessLevel < 3) and chatvars.words[3] ~= nil then pname = string.sub(chatvars.command, string.find(chatvars.command, "friends") + 8) pname = string.trim(pname) id = LookupPlayer(pname) if id == 0 then id = LookupArchivedPlayer(pname) if id ~= 0 then playerName = playersArchived[id].name end else playerName = players[id].name end if id ~= 0 then -- reset the players friends list friends[id] = {} message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Player " .. playerName .. " has no friends :([-]") if botman.dbConnected then conn:execute("DELETE FROM friends WHERE steam = " .. id) end else if (chatvars.playername ~= "Server") then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]No player found called " .. pname .. "[-]") else irc_chat(chatvars.ircAlias, "No player found called " .. pname) end end botman.faultyChat = false return true end -- reset the players friends list friends[chatvars.playerid] = {} message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You have no friends :([-]") if botman.dbConnected then conn:execute("DELETE FROM friends WHERE steam = " .. chatvars.playerid) end botman.faultyChat = false return true end end local function cmd_FriendMe() if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}friendme {player}" help[2] = "Admins can force a player to be their friend with this command. It only applies to the bot, not the game itself." tmp.command = help[1] tmp.keywords = "add,friend" tmp.accessLevel = 2 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "add") or string.find(chatvars.command, "friend") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end -- This is how admins make friends =D if (chatvars.words[1] == "friendme") and (chatvars.playerid ~= 0) then if (chatvars.accessLevel > 2) then message(string.format("pm %s [%s]" .. restrictedCommandMessage(), chatvars.playerid, server.chatColour)) botman.faultyChat = false return true end pname = string.sub(chatvars.command, string.find(chatvars.command, "friendme ") + 9) pname = string.trim(pname) id = LookupPlayer(pname) if id == 0 then id = LookupArchivedPlayer(pname) if not (id == 0) then if (chatvars.playername ~= "Server") then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Player " .. playersArchived[id].name .. " was archived. Get them to rejoin the server, then repeat this command.[-]") else irc_chat(chatvars.ircAlias, "Player " .. playersArchived[id].name .. " was archived. Get them to rejoin the server, then repeat this command.") end botman.faultyChat = false return true end else if (not isFriend(id, chatvars.playerid)) then if friends[id].friends == "" then friends[id].friends = chatvars.playerid else friends[id].friends = friends[id].friends .. "," .. chatvars.playerid end message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]" .. players[id].name .. " now lists you as a friend.[-]") if botman.dbConnected then conn:execute("INSERT INTO friends (steam, friend) VALUES (" .. id .. "," .. chatvars.playerid .. ")") end botman.faultyChat = false return true else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You are already a friend of " .. players[id].name .. ".[-]") end end botman.faultyChat = false return true end end local function cmd_FriendPlayerToPlayer() if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}player {player} friend {other player}\n" help[1] = help[1] .. "eg. {#}player joe friend mary" help[2] = "Admins can force a player to friend another player with this command. It only applies to the bot, not the game itself." tmp.command = help[1] tmp.keywords = "add,friend" tmp.accessLevel = 2 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "add") or string.find(chatvars.command, "friend") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end if (chatvars.words[1] == "player") and string.find(chatvars.command, " friend ") and (chatvars.playerid ~= 0) then if (chatvars.playername ~= "Server") then if (chatvars.accessLevel > 2) then message(string.format("pm %s [%s]" .. restrictedCommandMessage(), chatvars.playerid, server.chatColour)) botman.faultyChat = false return true end else if (chatvars.accessLevel > 2) then irc_chat(chatvars.ircAlias, "This command is restricted.") botman.faultyChat = false return true end end tmp = {} tmp.pname = string.sub(chatvars.command, string.find(chatvars.command, "player ") + 7, string.find(chatvars.command, " friend ") - 1) tmp.pname = string.trim(tmp.pname) tmp.pid = LookupPlayer(tmp.pname) if (tmp.pid == 0) then tmp.pid = LookupArchivedPlayer(tmp.pname) if not (tmp.pid == 0) then if (chatvars.playername ~= "Server") then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Player " .. playersArchived[tmp.pid].name .. " was archived. Get them to rejoin the server, then repeat this command.[-]") else irc_chat(chatvars.ircAlias, "Player " .. playersArchived[tmp.pid].name .. " was archived. Get them to rejoin the server, then repeat this command.") end else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]No match for " .. tmp.pname .. "[-]") end botman.faultyChat = false return true end tmp.fname = string.sub(chatvars.command, string.find(chatvars.command, " friend ") + 8) tmp.fname = string.trim(tmp.fname) tmp.fid = LookupPlayer(tmp.fname) if (tmp.fid == 0) then tmp.fid = LookupArchivedPlayer(tmp.fname) if not (tmp.fid == 0) then if (chatvars.playername ~= "Server") then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Player " .. playersArchived[tmp.fid].name .. " was archived. Get them to rejoin the server, then repeat this command.[-]") else irc_chat(chatvars.ircAlias, "Player " .. playersArchived[tmp.fid].name .. " was archived. Get them to rejoin the server, then repeat this command.") end else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]No match for " .. tmp.fname .. "[-]") end botman.faultyChat = false return true end -- add to friends table if (friends[tmp.pid].friends == nil) then friends[tmp.pid] = {} friends[tmp.pid].friends = "" end if addFriend(tmp.pid, tmp.fid, false) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]" .. players[tmp.pid].name .. " is now friends with " .. players[tmp.fid].name .. "[-]") else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]" .. players[tmp.pid].name .. " is already friends with " .. players[tmp.fid].name .. "[-]") end botman.faultyChat = false return true end end local function cmd_ListFriends() local playerName if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}friends {player} (only admins can specify a player)" help[2] = "List your friends." tmp.command = help[1] tmp.keywords = "list,friend" tmp.accessLevel = 99 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "list") or string.find(chatvars.command, "friend") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end -- List a player's trophies er.. I mean friends. if (chatvars.words[1] == "friends") and (chatvars.playerid ~= 0) then pid = chatvars.playerid if chatvars.accessLevel > 2 and chatvars.words[2] ~= nil then botman.faultyChat = false return true end if chatvars.accessLevel < 3 and chatvars.words[2] ~= nil then pname = string.sub(chatvars.command, string.find(chatvars.command, "friends") + 8, string.len(chatvars.command)) pid = LookupPlayer(pname) if pid == 0 then pid = LookupArchivedPlayer(pname) if not (pid == 0) then playerName = playersArchived[pid].name else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]No player found called " .. pname .. "[-]") botman.faultyChat = false return true end else playerName = players[pid].name end end -- pm a list of all the players friends if (friends[pid] == 0) or friends[pid].friends == "" then if (pid == chatvars.playerid) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You have no friends :([-]") else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]" .. playerName .. " has no friends.[-]") end botman.faultyChat = false return true end friendlist = string.split(friends[pid].friends, ",") if (pid == chatvars.playerid) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You are friends with..[-]") else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]" .. playerName .. " is friends with..[-]") end max = table.maxn(friendlist) for i=1,max,1 do if (friendlist[i] ~= "") then id = LookupPlayer(friendlist[i]) if id ~= 0 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]" .. players[id].name .. "[-]") else id = LookupArchivedPlayer(friendlist[i]) if id ~= 0 then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]" .. playersArchived[id].name .. "[-]") end end end end botman.faultyChat = false return true end end local function cmd_Unfriend() local playerName if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}unfriend {player}" help[2] = "Unfriend a player." tmp.command = help[1] tmp.keywords = "remo,del,friend" tmp.accessLevel = 99 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "remo") or string.find(chatvars.command, "friend") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end -- Say hello to the hand. if (chatvars.words[1] == "unfriend") and (chatvars.playerid ~= 0) then if chatvars.words[2] == nil then botman.faultyChat = commandHelp("help friends", chatvars.playerid) return true end if (friends[chatvars.playerid] == nil or friends[chatvars.playerid] == {}) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You have no friends :([-]") botman.faultyChat = false return true end pname = string.sub(chatvars.command, string.find(chatvars.command, "unfriend ") + 9) pname = string.trim(pname) id = LookupPlayer(pname) if id == 0 then id = LookupArchivedPlayer(pname) if not (id == 0) then playerName = playersArchived[id].name else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You don't have any friends called " .. pname .. ".[-]") botman.faultyChat = false return true end else playerName = players[id].name end -- unfriend someone if (id ~= 0) then if botman.dbConnected then -- check to see if this friend was auto friended and warn the player that they must unfriend them via the game. cursor,errorString = conn:execute("select * from friends where steam = " .. chatvars.playerid .. " AND friend = " .. id .. " AND autoAdded = 1") row = cursor:fetch({}, "a") if row then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You need to unfriend " .. playerName .. " via the game since that is how you added them.[-]") botman.faultyChat = false return true end end friendlist = string.split(friends[chatvars.playerid].friends, ",") -- now simply rebuild friend skipping over the one we are removing friends[chatvars.playerid].friends = "" max = table.maxn(friendlist) for i=1,max,1 do if (friendlist[i] ~= id) and friendlist[i] ~= "" then if friends[chatvars.playerid].friends == "" then friends[chatvars.playerid].friends = friendlist[i] else friends[chatvars.playerid].friends = friends[chatvars.playerid].friends .. "," .. friendlist[i] end end end if botman.dbConnected then conn:execute("DELETE FROM friends WHERE steam = " .. chatvars.playerid .. " AND friend = " .. id) end message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You are no longer friends with " .. playerName .. "[-]") end botman.faultyChat = false return true end end local function cmd_UnfriendMe() local playerName if (chatvars.showHelp and not skipHelp) or botman.registerHelp then help = {} help[1] = " {#}unfriendme {player}\n" help[1] = help[1] .. " {#}unfriendme everyone" help[2] = "Unfriend a player or everyone. This command is for admins only." tmp.command = help[1] tmp.keywords = "remo,del,friend" tmp.accessLevel = 2 tmp.description = help[2] tmp.notes = "" tmp.ingameOnly = 1 help[3] = helpCommandRestrictions(tmp) if botman.registerHelp then registerHelp(tmp) end if string.find(chatvars.command, "remo") or string.find(chatvars.command, "friend") or chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, help[1]) if not shortHelp then irc_chat(chatvars.ircAlias, help[2]) irc_chat(chatvars.ircAlias, help[3]) irc_chat(chatvars.ircAlias, ".") end chatvars.helpRead = true end end -- My friend doesn't like you. -- I don't like you either. if (chatvars.words[1] == "unfriendme") and (chatvars.playerid ~= 0) then if (chatvars.accessLevel > 2) then message(string.format("pm %s [%s]" .. restrictedCommandMessage(), chatvars.playerid, server.chatColour)) botman.faultyChat = false return true end if chatvars.words[2] ~= "everyone" then pname = string.sub(chatvars.command, string.find(chatvars.command, "unfriendme ") + 12) pname = string.trim(pname) id = LookupPlayer(pname) if id == 0 then id = LookupArchivedPlayer(pname) if id ~= 0 then playerName = playersArchived[id].name else message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]No player found called " .. pname .. "[-]") botman.faultyChat = false return true end else playerName = players[id].name end end for k, v in pairs(friends) do if (k == id) or chatvars.words[2] == "everyone" then friendlist = string.split(friends[k].friends, ",") -- now simply rebuild friend skipping over the one we are removing friends[k].friends = "" max = table.maxn(friendlist) for i=1,max,1 do if (friendlist[i] ~= chatvars.playerid) then if friends[k].friends == "" then friends[k].friends = friendlist[i] else friends[k].friends = friends[k].friends .. "," .. friendlist[i] end end end if (k == id) then message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You are off " .. playerName .. "'s friends list.[-]") if botman.dbConnected then conn:execute("DELETE FROM friends WHERE steam = " .. k .. " AND friend = " .. chatvars.playerid) end botman.faultyChat = false return true end end end if (chatvars.words[2] == "everyone") then if botman.dbConnected then conn:execute("DELETE FROM friends WHERE friend = " .. chatvars.playerid) end message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You are off everyones friends list.[-]") botman.faultyChat = false return true end end end -- ################## End of command functions ################## if botman.registerHelp then irc_chat(chatvars.ircAlias, "==== Registering help - friend commands ====") if debug then dbug("Registering help - friend commands") end tmp.topicDescription = "These commands are adding/removing or viewing a player's friends." cursor,errorString = conn:execute("SELECT * FROM helpTopics WHERE topic = 'friends'") rows = cursor:numrows() if rows == 0 then cursor,errorString = conn:execute("SHOW TABLE STATUS LIKE 'helpTopics'") row = cursor:fetch(row, "a") tmp.topicID = row.Auto_increment conn:execute("INSERT INTO helpTopics (topic, description) VALUES ('friends', '" .. escape(tmp.topicDescription) .. "')") end end -- don't proceed if there is no leading slash if (string.sub(chatvars.command, 1, 1) ~= server.commandPrefix and server.commandPrefix ~= "") then botman.faultyChat = false return false end if (debug) then dbug("debug friends line " .. debugger.getinfo(1).currentline) end if chatvars.showHelp then if chatvars.words[3] then if not string.find(chatvars.words[3], "friends") then skipHelp = true end end if chatvars.words[1] == "help" then skipHelp = false end if chatvars.words[1] == "list" then shortHelp = true end end if (debug) then dbug("debug friends line " .. debugger.getinfo(1).currentline) end if chatvars.showHelp and not skipHelp and chatvars.words[1] ~= "help" then irc_chat(chatvars.ircAlias, ".") irc_chat(chatvars.ircAlias, "Friend Commands:") irc_chat(chatvars.ircAlias, "================") irc_chat(chatvars.ircAlias, ".") irc_chat(chatvars.ircAlias, "These commands are adding/removing or viewing a player's friends.") irc_chat(chatvars.ircAlias, ".") end if (debug) then dbug("debug friends line " .. debugger.getinfo(1).currentline) end if chatvars.showHelpSections then irc_chat(chatvars.ircAlias, "friends") end if (debug) then dbug("debug friends line " .. debugger.getinfo(1).currentline) end result = cmd_FriendPlayerToPlayer() if result then if debug then dbug("debug cmd_FriendPlayerToPlayer triggered") end return result end if (debug) then dbug("debug friends line " .. debugger.getinfo(1).currentline) end result = cmd_AddFriend() if result then if debug then dbug("debug cmd_AddFriend triggered") end return result end if (debug) then dbug("debug friends line " .. debugger.getinfo(1).currentline) end result = cmd_ForgetFriends() if result then if debug then dbug("debug cmd_ForgetFriends triggered") end return result end if (debug) then dbug("debug friends line " .. debugger.getinfo(1).currentline) end result = cmd_Unfriend() if result then if debug then dbug("debug cmd_Unfriend triggered") end return result end if (debug) then dbug("debug friends line " .. debugger.getinfo(1).currentline) end result = cmd_FriendMe() if result then if debug then dbug("debug cmd_FriendMe triggered") end return result end if (debug) then dbug("debug friends line " .. debugger.getinfo(1).currentline) end result = cmd_ListFriends() if result then if debug then dbug("debug cmd_ListFriends triggered") end return result end if (debug) then dbug("debug friends line " .. debugger.getinfo(1).currentline) end result = cmd_UnfriendMe() if result then if debug then dbug("debug cmd_UnfriendMe triggered") end return result end if botman.registerHelp then irc_chat(chatvars.ircAlias, "**** Friend commands help registered ****") if debug then dbug("Friend commands help registered") end topicID = topicID + 1 end if debug then dbug("debug friends end") end -- can't touch dis if true then return result end end
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/yellow_fish_7.meta.lua
16
1922
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = { "255 177 82 255", "51 204 0 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/yellow_fish_3.meta.lua
16
1922
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 60, light_colors = { "255 177 82 255", "51 204 0 255" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 } } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
nasomi/darkstar
scripts/zones/Tahrongi_Canyon/npcs/Excavation_Point.lua
29
1114
----------------------------------- -- Area: Tahrongi Canyon -- NPC: Excavation Point ----------------------------------- package.loaded["scripts/zones/Tahrongi_Canyon/TextIDs"] = nil; ------------------------------------- require("scripts/globals/excavation"); require("scripts/zones/Tahrongi_Canyon/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) startExcavation(player,player:getZoneID(),npc,trade,0x0385); end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(MINING_IS_POSSIBLE_HERE,605); 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
nasomi/darkstar
scripts/globals/abilities/rogues_roll.lua
9
2778
----------------------------------- -- Ability: Rogue's Roll -- Improves critical hit rate for party members within area of effect -- Optimal Job: Thief -- Lucky Number: 5 -- Unlucky Number: 9 -- Level: 43 -- -- Die Roll |No THF |With THF -- -------- ------- ----------- -- 1 |2% |8% -- 2 |2% |8% -- 3 |3% |9% -- 4 |4% |10% -- 5 |12% |18% -- 6 |5% |11% -- 7 |6% |12% -- 8 |6% |12% -- 9 |1% |7% -- 10 |8% |14% -- 11 |19% |25% -- 12+ |-6% |-6% ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = getCorsairRollEffect(ability:getID()); ability:setRange(ability:getRange() + player:getMod(MOD_ROLL_RANGE)); if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; else player:setLocalVar("THF_roll_bonus", 0); return 0,0; end end; ----------------------------------- -- onUseAbilityRoll ----------------------------------- function onUseAbilityRoll(caster,target,ability,total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {2, 2, 3, 4, 12, 5, 6, 6, 1, 8, 19, 6} local effectpower = effectpowers[total] local jobBonus = caster:getLocalVar("THF_roll_bonus"); if (total < 12) then -- see chaos_roll.lua for comments if (jobBonus == 0) then if (caster:hasPartyJob(JOB_THF) or math.random(0, 99) < caster:getMod(MOD_JOB_BONUS_CHANCE)) then jobBonus = 1; else jobBonus = 2; end end if (jobBonus == 1) then effectpower = effectpower + 6; end if (target:getID() == caster:getID()) then caster:setLocalVar("THF_roll_bonus", jobBonus); end end if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_ROGUES_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_CRITHITRATE) == false) then ability:setMsg(423); end end;
gpl-3.0
thesabbir/luci
applications/luci-app-asterisk/luasrc/model/cbi/asterisk-mod-chan.lua
68
1513
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true chan_agent = module:option(ListValue, "chan_agent", "Agent Proxy Channel", "") chan_agent:value("yes", "Load") chan_agent:value("no", "Do Not Load") chan_agent:value("auto", "Load as Required") chan_agent.rmempty = true chan_alsa = module:option(ListValue, "chan_alsa", "Channel driver for GTalk", "") chan_alsa:value("yes", "Load") chan_alsa:value("no", "Do Not Load") chan_alsa:value("auto", "Load as Required") chan_alsa.rmempty = true chan_gtalk = module:option(ListValue, "chan_gtalk", "Channel driver for GTalk", "") chan_gtalk:value("yes", "Load") chan_gtalk:value("no", "Do Not Load") chan_gtalk:value("auto", "Load as Required") chan_gtalk.rmempty = true chan_iax2 = module:option(Flag, "chan_iax2", "Option chan_iax2", "") chan_iax2.rmempty = true chan_local = module:option(ListValue, "chan_local", "Local Proxy Channel", "") chan_local:value("yes", "Load") chan_local:value("no", "Do Not Load") chan_local:value("auto", "Load as Required") chan_local.rmempty = true chan_sip = module:option(ListValue, "chan_sip", "Session Initiation Protocol (SIP)", "") chan_sip:value("yes", "Load") chan_sip:value("no", "Do Not Load") chan_sip:value("auto", "Load as Required") chan_sip.rmempty = true return cbimap
apache-2.0
shakfu/start-vm
config/artful/awesome/vicious/widgets/pkg_all.lua
1
1931
--------------------------------------------------- -- Licensed under the GNU General Public License v2 -- * (c) 2010, Adrian C. <anrxc@sysphere.org> --------------------------------------------------- -- {{{ Grab environment local io = { popen = io.popen } local math = { max = math.max } local setmetatable = setmetatable local spawn = require("awful.spawn") -- }}} -- Pkg: provides number of pending updates on UNIX systems -- vicious.widgets.pkg local pkg_all = {} -- {{{ Packages widget type function pkg_all.async(format, warg, callback) if not warg then return end -- Initialize counters local manager = { ["Arch"] = { cmd = "pacman -Qu" }, ["Arch C"] = { cmd = "checkupdates" }, ["Arch S"] = { cmd = "yes | pacman -Sup", sub = 1 }, ["Debian"] = { cmd = "apt-show-versions -u -b" }, ["Ubuntu"] = { cmd = "aptitude search '~U'" }, ["Fedora"] = { cmd = "yum list updates", sub = 3 }, ["FreeBSD"] ={ cmd = "pkg version -I -l '<'" }, ["Mandriva"]={ cmd = "urpmq --auto-select" } } -- Check if updates are available local function parse(str, skiprows) local size, lines, first = 0, "", skiprows or 0 for line in str:gmatch("[^\r\n]+") do if size >= first then lines = lines .. (size == first and "" or "\n") .. line end size = size + 1 end size = math.max(size-first, 0) return {size, lines} end -- Select command local _pkg = manager[warg] spawn.easy_async(_pkg.cmd, function(stdout) callback(parse(stdout, _pkg.sub)) end) end -- }}} -- {{{ Packages widget type local function worker(format, warg) local ret = nil pkg_all.async(format, warg, function(data) ret = data end) while ret==nil do end return ret end -- }}} return setmetatable(pkg_all, { __call = function(_, ...) return worker(...) end })
mit
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/metropolis_backpack.meta.lua
2
3144
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.69999998807907104, amplification = 60, light_colors = { "0 255 255 255", "255 0 228 255" }, radius = { x = 80, y = 80 }, standard_deviation = 7 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 9, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = { { x = -13, y = -7 }, { x = -9, y = -22 }, { x = -5, y = -27 }, { x = 11, y = -24 }, { x = 12, y = 23 }, { x = -4, y = 26 }, { x = -10, y = 22 } } }, torso = { back = { pos = { x = 0, y = 0 }, rotation = 0 }, head = { pos = { x = 0, y = 0 }, rotation = 0 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder = { pos = { x = 0, y = 0 }, rotation = 0 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
nasomi/darkstar
scripts/globals/items/mercanbaligi.lua
18
1262
----------------------------------------- -- ID: 5454 -- Item: Mercanbaligi -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 4 -- Mind -6 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5454); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 4); target:addMod(MOD_MND, -6); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 4); target:delMod(MOD_MND, -6); end;
gpl-3.0
coolflyreg/gs
3rd/skynet-mingw/lualib/http/internal.lua
95
2613
local table = table local type = type local M = {} local LIMIT = 8192 local function chunksize(readbytes, body) while true do local f,e = body:find("\r\n",1,true) if f then return tonumber(body:sub(1,f-1),16), body:sub(e+1) end if #body > 128 then -- pervent the attacker send very long stream without \r\n return end body = body .. readbytes() end end local function readcrln(readbytes, body) if #body >= 2 then if body:sub(1,2) ~= "\r\n" then return end return body:sub(3) else body = body .. readbytes(2-#body) if body ~= "\r\n" then return end return "" end end function M.recvheader(readbytes, lines, header) if #header >= 2 then if header:find "^\r\n" then return header:sub(3) end end local result local e = header:find("\r\n\r\n", 1, true) if e then result = header:sub(e+4) else while true do local bytes = readbytes() header = header .. bytes if #header > LIMIT then return end e = header:find("\r\n\r\n", -#bytes-3, true) if e then result = header:sub(e+4) break end if header:find "^\r\n" then return header:sub(3) end end end for v in header:gmatch("(.-)\r\n") do if v == "" then break end table.insert(lines, v) end return result end function M.parseheader(lines, from, header) local name, value for i=from,#lines do local line = lines[i] if line:byte(1) == 9 then -- tab, append last line if name == nil then return end header[name] = header[name] .. line:sub(2) else name, value = line:match "^(.-):%s*(.*)" if name == nil or value == nil then return end name = name:lower() if header[name] then local v = header[name] if type(v) == "table" then table.insert(v, value) else header[name] = { v , value } end else header[name] = value end end end return header end function M.recvchunkedbody(readbytes, bodylimit, header, body) local result = "" local size = 0 while true do local sz sz , body = chunksize(readbytes, body) if not sz then return end if sz == 0 then break end size = size + sz if bodylimit and size > bodylimit then return end if #body >= sz then result = result .. body:sub(1,sz) body = body:sub(sz+1) else result = result .. body .. readbytes(sz - #body) body = "" end body = readcrln(readbytes, body) if not body then return end end local tmpline = {} body = M.recvheader(readbytes, tmpline, body) if not body then return end header = M.parseheader(tmpline,1,header) return result, header end return M
gpl-2.0
nasomi/darkstar
scripts/zones/RuAun_Gardens/Zone.lua
28
15340
----------------------------------- -- -- Zone: RuAun_Gardens (130) -- ----------------------------------- package.loaded["scripts/zones/RuAun_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/missions"); require("scripts/globals/conquest"); require("scripts/zones/RuAun_Gardens/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17310100,17310101,17310102,17310103,17310104,17310105}; SetFieldManual(manuals); -- Blue portal timers (2 minutes) -- counterclockwise SetServerVariable("Main-to-Seiryu-BlueTeleport",0); SetServerVariable("Seiryu-to-Genbu-BlueTeleport",0); SetServerVariable("Genbu-to-Byakko-BlueTeleport",0); SetServerVariable("Byakko-to-Suzaku-BlueTeleport",0); SetServerVariable("Suzaku-to-Main-BlueTeleport",0); -- clockwise SetServerVariable("Main-to-Suzaku-BlueTeleport",0); SetServerVariable("Suzaku-to-Byakko-BlueTeleport",0); SetServerVariable("Byakko-to-Genbu-BlueTeleport",0); SetServerVariable("Genbu-to-Seiryu-BlueTeleport",0); SetServerVariable("Seiryu-to-Main-BlueTeleport",0); ------------------------------ -- Red teleports ------------------------------ zone:registerRegion(1,-3,-54,-583,1,-50,-579); zone:registerRegion(2,147,-26,-449,151,-22,-445); zone:registerRegion(3,186,-43,-405,190,-39,-401); zone:registerRegion(4,272,-42,-379,276,-38,-375); zone:registerRegion(5,306,-39,-317,310,-35,-313); zone:registerRegion(6,393,-39,193,397,-35,197); zone:registerRegion(7,62,-39,434,66,-35,438); zone:registerRegion(8,-2,-42,464,2,-38,468); zone:registerRegion(9,-65,-39,434,-61,-35,438); zone:registerRegion(10,-397,-39,193,-393,-35,197); zone:registerRegion(11,-445,-42,142,-441,-38,146); zone:registerRegion(12,-276,-42,-379,-272,-38,-375); zone:registerRegion(13,-191,-43,-405,-187,-39,-401); zone:registerRegion(14,-151,-26,-449,-147,-22,-445); zone:registerRegion(15,543,-73,-19,547,-69,-15); zone:registerRegion(16,182,-73,511,186,-69,515); zone:registerRegion(17,-432,-73,332,-428,-69,336); zone:registerRegion(18,-453,-73,-308,-449,-69,-304); zone:registerRegion(19,-436,-39,71,-432,-35,75); zone:registerRegion(20,-310,-39,-317,-306,-35,-313); zone:registerRegion(21,441,-42,142,445,-38,146); zone:registerRegion(22,432,-39,71,436,-35,75); ------------------------------ -- Blue teleports ------------------------------ zone:registerRegion(23,162.5,-31,-353.5,168.5,-30,-347.5); -- Main To Seriyu zone:registerRegion(24,374.5,-25,61.5,380.5,-24,67.5); -- Seriyu to Genbu zone:registerRegion(25,52.5,-25,376.5,58.5,-24,382.5); -- Genbu to Byakko zone:registerRegion(26,-346.5,-25,166.5,-340.5,-24,172.5); -- Byakko to Suzaku zone:registerRegion(27,-270.5,-25,-277.5,-264.5,-24,-271.5); -- Suzaku to Main zone:registerRegion(28,-170,-31,-354.4,-162,-30,-347.2); -- Main to Suzaku zone:registerRegion(29,-381,-25,61.5,-374.5,-24,67.5); -- Suzaku to Byakko zone:registerRegion(30,-58,-25,376.5,-52,-24,382.5); -- Byakko to Genbu zone:registerRegion(31,340.5,-25,166.5,346.5,-24,172.5); --Genbu to Seriyu zone:registerRegion(32,264.5,-25,-277.5,270.5,-24,-271.5); -- Seriyu to Main ------------------------------ -- Yellow teleports ------------------------------ zone:registerRegion(33,454,-5,-149,456,-3,-147); zone:registerRegion(34,278,-5,383,281,-3,386); zone:registerRegion(35,-283,-5,386,-280,-3,389); zone:registerRegion(36,-456,-5,-149,-454,-3,-147); ---432,-72,335,-429,-70,333 ------------------------------ -- Green teleports ------------------------------ zone:registerRegion(37,-145,-41,-156,-142,-39,-153); zone:registerRegion(38,142,-41,-156,145,-39,-153 ); UpdateTreasureSpawnPoint(17310020); SetRegionalConquestOverseers(zone:getRegionID()) 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(333.017,-44.896,-458.35,164); end if (player:getCurrentMission(ZILART) == THE_GATE_OF_THE_GODS and player:getVar("ZilartStatus") == 1) then cs = 0x0033; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { --------------------------------- [1] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0000); end, --------------------------------- [2] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0001); end, --------------------------------- [3] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0002); end, --------------------------------- [4] = function (x) -- Portal -- --------------------------------- if (math.random(0,1) == 0) then player:startEvent(0x0004); else player:startEvent(0x0005); end end, --------------------------------- [5] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0006); end, --------------------------------- [6] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0009); end, --------------------------------- [7] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0010); end, --------------------------------- [8] = function (x) -- Portal -- --------------------------------- if (math.random(0,1) == 0) then player:startEvent(0x0012); else player:startEvent(0x0013); end end, --------------------------------- [9] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0014); end, --------------------------------- [10] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0017); end, --------------------------------- [11] = function (x) -- Portal -- --------------------------------- if (math.random(0,1) == 0) then player:startEvent(0x0019); else player:startEvent(0x001A); end end, --------------------------------- [12] = function (x) -- Portal -- --------------------------------- if (math.random(0,1) == 0) then player:startEvent(0x0020); else player:startEvent(0x0021); end end, --------------------------------- [13] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0022); end, --------------------------------- [14] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0024); end, --------------------------------- [15] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0025); end, --------------------------------- [16] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0026); end, --------------------------------- [17] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0027); end, --------------------------------- [18] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0028); end, --------------------------------- [19] = function (x) -- Portal -- --------------------------------- player:startEvent(0x001B); end, --------------------------------- [20] = function (x) -- Portal -- --------------------------------- player:startEvent(0x001E); end, --------------------------------- [21] = function (x) -- Portal -- --------------------------------- if (math.random(0,1) == 0) then player:startEvent(0x000B); else player:startEvent(0x000C); end end, --------------------------------- [22] = function (x) -- Portal -- --------------------------------- player:startEvent(0x0009); end, ----------- BLUE portals -------------- --------------------------------- [23] = function (x) -- Portal -- Main To Seriyu --------------------------------- if (GetNPCByID(17310054):getAnimation() == 8) then player:startEvent(0x0003); end end, --------------------------------- [24] = function (x) -- Portal -- Seriyu to Genbu --------------------------------- if (GetNPCByID(17310057):getAnimation() == 8) then player:startEvent(0x000A); end end, --------------------------------- [25] = function (x) -- Portal -- Genbu to Byakko --------------------------------- if (GetNPCByID(17310060):getAnimation() == 8) then player:startEvent(0x0011); end end, --------------------------------- [26] = function (x) -- Portal -- Byakko to Suzaku --------------------------------- if (GetNPCByID(17310063):getAnimation() == 8) then player:startEvent(0x0018); end end, --------------------------------- [27] = function (x) -- Portal -- Suzaku to Main --------------------------------- if (GetNPCByID(17310066):getAnimation() == 8) then player:startEvent(0x001F); end end, --------------------------------- [28] = function (x) -- Portal -- Main to Suzaku --------------------------------- if (GetNPCByID(17310067):getAnimation() == 8) then player:startEvent(0x0023); end end, --------------------------------- [29] = function (x) -- Portal -- Suzaku to Byakko --------------------------------- if (GetNPCByID(17310064):getAnimation() == 8) then player:startEvent(0x001C); end end, --------------------------------- [30] = function (x) -- Portal -- Byakko to Genbu --------------------------------- if (GetNPCByID(17310061):getAnimation() == 8) then player:startEvent(0x0015); end end, --------------------------------- [31] = function (x) -- Portal -- Genbu to Seriyu --------------------------------- if (GetNPCByID(17310058):getAnimation() == 8) then player:startEvent(0x000E); end end, --------------------------------- [32] = function (x) -- Portal -- Seriyu to Main --------------------------------- if (GetNPCByID(17310055):getAnimation() == 8) then player:startEvent(0x0007); end end, --------------------------------- [33] = function (x) -- Seiryu's Portal -- --------------------------------- player:startEvent(0x0008); end, --------------------------------- [34] = function (x) -- Genbu's Portal -- --------------------------------- player:startEvent(0x000f); end, --------------------------------- [35] = function (x) -- Byakko's Portal -- --------------------------------- player:startEvent(0x0016); end, --------------------------------- [36] = function (x) -- Suzaku's Portal -- --------------------------------- player:startEvent(0x001d); end, --------------------------------- [37] = function (x) --------------------------------- if (player:getVar("skyShortcut") == 1) then player:startEvent(0x002a); else title = player:getTitle(); if (title == 401) then player:startEvent(0x0029,title); else player:startEvent(0x002b,title); end end end, --------------------------------- [38] = function (x) --------------------------------- if (player:getVar("skyShortcut") == 1) then player:startEvent(0x002a); else title = player:getTitle(); if (title == 401) then player:startEvent(0x0029,title); else player:startEvent(0x002b,title); end end end, default = function (x) end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0029 and option ~= 0) then player:setVar("skyShortcut",1); elseif (csid == 0x0033) then player:setVar("ZilartStatus",0); player:completeMission(ZILART,THE_GATE_OF_THE_GODS); player:addMission(ZILART,ARK_ANGELS); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/abilities/pets/pet_frost_breath.lua
25
1248
--------------------------------------------------- -- Frost Breath --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill, master) ---------- Deep Breathing ---------- -- 0 for none -- 1 for first merit -- 0.25 for each merit after the first -- TODO: 0.1 per merit for augmented AF2 (10663 *w/ augment*) local deep = 1; if (pet:hasStatusEffect(EFFECT_MAGIC_ATK_BOOST) == true) then deep = deep + 1 + (master:getMerit(MERIT_DEEP_BREATHING)-1)*0.25; pet:delStatusEffect(EFFECT_MAGIC_ATK_BOOST); end local gear = master:getMod(MOD_WYVERN_BREATH)/256; -- Master gear that enhances breath local dmgmod = MobBreathMove(pet, target, 0.185, pet:getMainLvl()*15, ELE_ICE); -- Works out to (hp/6) + 15, as desired dmgmod = (dmgmod * (1+gear))*deep; local dmg = MobFinalAdjustments(dmgmod,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_ICE,MOBPARAM_IGNORE_SHADOWS); target:delHP(dmg); return dmg; end
gpl-3.0
Samanj5/spam-is-alive
plugins/bugzilla.lua
611
3983
do local BASE_URL = "https://bugzilla.mozilla.org/rest/" local function bugzilla_login() local url = BASE_URL.."login?login=" .. _config.bugzilla.username .. "&password=" .. _config.bugzilla.password print("accessing " .. url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_check(id) -- data = bugzilla_login() local url = BASE_URL.."bug/" .. id .. "?api_key=" .. _config.bugzilla.apikey -- print(url) local res,code = https.request( url ) local data = json:decode(res) return data end local function bugzilla_listopened(email) local url = BASE_URL.."bug?include_fields=id,summary,status,whiteboard,resolution&email1=" .. email .. "&email2=" .. email .. "&emailassigned_to2=1&emailreporter1=1&emailtype1=substring&emailtype2=substring&f1=bug_status&f2=bug_status&n1=1&n2=1&o1=equals&o2=equals&resolution=---&v1=closed&v2=resolved&api_key=" .. _config.bugzilla.apikey local res,code = https.request( url ) print(res) local data = json:decode(res) return data end local function run(msg, matches) local response = "" if matches[1] == "status" then local data = bugzilla_check(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator response = response .. "\n Last update: "..data.bugs[1].last_change_time response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] print(response) end elseif matches[1] == "list" then local data = bugzilla_listopened(matches[2]) vardump(data) if data.error == true then return "Sorry, API failed with message: " .. data.message else -- response = "Bug #"..matches[1]..":\nReporter: "..data.bugs[1].creator -- response = response .. "\n Last update: "..data.bugs[1].last_change_time -- response = response .. "\n Status: "..data.bugs[1].status.." "..data.bugs[1].resolution -- response = response .. "\n Whiteboard: "..data.bugs[1].whiteboard -- response = response .. "\n Access: https://bugzilla.mozilla.org/show_bug.cgi?id=" .. matches[1] local total = table.map_length(data.bugs) print("total bugs: " .. total) local response = "There are " .. total .. " number of bug(s) assigned/reported by " .. matches[2] if total > 0 then response = response .. ": " for tableKey, bug in pairs(data.bugs) do response = response .. "\n #" .. bug.id response = response .. "\n Status: " .. bug.status .. " " .. bug.resolution response = response .. "\n Whiteboard: " .. bug.whiteboard response = response .. "\n Summary: " .. bug.summary end end end end return response end -- (table) -- [bugs] = (table) -- [1] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 927704 -- [whiteboard] = (string) [approved][full processed] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/mozilla-summit-2013/ -- [2] = (table) -- [status] = (string) ASSIGNED -- [id] = (number) 1049337 -- [whiteboard] = (string) [approved][full processed][waiting receipts][waiting report and photos] -- [summary] = (string) Budget Request - Arief Bayu Purwanto - https://reps.mozilla.org/e/workshop-firefox-os-pada-workshop-media-sosial-untuk-perubahan-1/ -- total bugs: 2 return { description = "Lookup bugzilla status update", usage = "/bot bugzilla [bug number]", patterns = { "^/bugzilla (status) (.*)$", "^/bugzilla (list) (.*)$" }, run = run } end
gpl-2.0
nasomi/darkstar
scripts/globals/spells/pyrohelix.lua
9
1729
-------------------------------------- -- Spell: Pyrohelix -- Deals fire 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); local duration = getHelixDuration(caster) + caster:getMod(MOD_HELIX_DURATION); duration = duration * (resist/2); if (dot > 0) then target:addStatusEffect(EFFECT_HELIX,dot,3,duration); end; return dmg; end;
gpl-3.0
mkjanke/Focus-Points
focuspoints.lrdevplugin/Info.lua
5
1612
--[[ Copyright 2016 Whizzbang Inc 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. --]] return { -- http://notebook.kulchenko.com/zerobrane/debugging-lightroom-plugins-zerobrane-studio-ide -- tail -f ~/Documents/libraryLogger.log LrSdkVersion = 5.0, LrSdkMinimumVersion = 5.0, LrToolkitIdentifier = 'com.thewhizzbang.focuspoint', LrPluginName = "Focus Point Viewer", LrLibraryMenuItems = { { title = "Show Focus Point", file = "FocusPoint.lua", enabledWhen = "photosSelected" }, { title = "Show Metadata", file = "ShowMetadata.lua", enabledWhen = "photosSelected" }, }, VERSION = { major=0, minor=0, revision=1, build=1, }, LrPluginInfoProvider = 'FocusPointsInfoProvider.lua', } --[[ KNOWN BUGS: 1. LrPhoto.getDevelopmentSettings()["Orientation"] return nil. I have no way of knowing if the photo was rotated in development mode 2. Orientation must be determined from the metadata. The metdata does not tell me if the camera was upside down e.g. rotation of 180 degrees. It only tells me normal, 90, or 270 --]]
apache-2.0
thesabbir/luci
applications/luci-app-ddns/luasrc/controller/ddns.lua
29
7451
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Copyright 2013 Manuel Munz <freifunk at somakoma dot de> -- Copyright 2014 Christian Schoenebeck <christian dot schoenebeck at gmail dot com> -- Licensed to the public under the Apache License 2.0. module("luci.controller.ddns", package.seeall) local NX = require "nixio" local NXFS = require "nixio.fs" local DISP = require "luci.dispatcher" local HTTP = require "luci.http" local UCI = require "luci.model.uci" local SYS = require "luci.sys" local DDNS = require "luci.tools.ddns" -- ddns multiused functions local UTIL = require "luci.util" DDNS_MIN = "2.4.2-1" -- minimum version of service required function index() local nxfs = require "nixio.fs" -- global definitions not available local sys = require "luci.sys" -- in function index() local ddns = require "luci.tools.ddns" -- ddns multiused functions local verinst = ddns.ipkg_ver_installed("ddns-scripts") local verok = ddns.ipkg_ver_compare(verinst, ">=", "2.0.0-0") -- do NOT start it not ddns-scripts version 2.x if not verok then return end -- no config create an empty one if not nxfs.access("/etc/config/ddns") then nxfs.writefile("/etc/config/ddns", "") end entry( {"admin", "services", "ddns"}, cbi("ddns/overview"), _("Dynamic DNS"), 59) entry( {"admin", "services", "ddns", "detail"}, cbi("ddns/detail"), nil ).leaf = true entry( {"admin", "services", "ddns", "hints"}, cbi("ddns/hints", {hideapplybtn=true, hidesavebtn=true, hideresetbtn=true}), nil ).leaf = true entry( {"admin", "services", "ddns", "global"}, cbi("ddns/global"), nil ).leaf = true entry( {"admin", "services", "ddns", "logview"}, call("logread") ).leaf = true entry( {"admin", "services", "ddns", "startstop"}, call("startstop") ).leaf = true entry( {"admin", "services", "ddns", "status"}, call("status") ).leaf = true end -- function to read all sections status and return data array local function _get_status() local uci = UCI.cursor() local service = SYS.init.enabled("ddns") and 1 or 0 local url_start = DISP.build_url("admin", "system", "startup") local data = {} -- Array to transfer data to javascript data[#data+1] = { enabled = service, -- service enabled url_up = url_start, -- link to enable DDS (System-Startup) } uci:foreach("ddns", "service", function (s) -- Get section we are looking at -- and enabled state local section = s[".name"] local enabled = tonumber(s["enabled"]) or 0 local datelast = "_empty_" -- formatted date of last update local datenext = "_empty_" -- formatted date of next update -- get force seconds local force_seconds = DDNS.calc_seconds( tonumber(s["force_interval"]) or 72 , s["force_unit"] or "hours" ) -- get/validate pid and last update local pid = DDNS.get_pid(section) local uptime = SYS.uptime() local lasttime = DDNS.get_lastupd(section) if lasttime > uptime then -- /var might not be linked to /tmp lasttime = 0 -- and/or not cleared on reboot end -- no last update happen if lasttime == 0 then datelast = "_never_" -- we read last update else -- calc last update -- sys.epoch - sys uptime + lastupdate(uptime) local epoch = os.time() - uptime + lasttime -- use linux date to convert epoch datelast = DDNS.epoch2date(epoch) -- calc and fill next update datenext = DDNS.epoch2date(epoch + force_seconds) end -- process running but update needs to happen -- problems if force_seconds > uptime force_seconds = (force_seconds > uptime) and uptime or force_seconds if pid > 0 and ( lasttime + force_seconds - uptime ) <= 0 then datenext = "_verify_" -- run once elseif force_seconds == 0 then datenext = "_runonce_" -- no process running and NOT enabled elseif pid == 0 and enabled == 0 then datenext = "_disabled_" -- no process running and enabled elseif pid == 0 and enabled ~= 0 then datenext = "_stopped_" end -- get/set monitored interface and IP version local iface = s["interface"] or "_nonet_" local use_ipv6 = tonumber(s["use_ipv6"]) or 0 if iface ~= "_nonet_" then local ipv = (use_ipv6 == 1) and "IPv6" or "IPv4" iface = ipv .. " / " .. iface end -- try to get registered IP local domain = s["domain"] or "_nodomain_" local dnsserver = s["dns_server"] or "" local force_ipversion = tonumber(s["force_ipversion"] or 0) local force_dnstcp = tonumber(s["force_dnstcp"] or 0) local command = [[/usr/lib/ddns/dynamic_dns_lucihelper.sh]] command = command .. [[ get_registered_ip ]] .. domain .. [[ ]] .. use_ipv6 .. [[ ]] .. force_ipversion .. [[ ]] .. force_dnstcp .. [[ ]] .. dnsserver local reg_ip = SYS.exec(command) if reg_ip == "" then reg_ip = "_nodata_" end -- fill transfer array data[#data+1] = { section = section, enabled = enabled, iface = iface, domain = domain, reg_ip = reg_ip, pid = pid, datelast = datelast, datenext = datenext } end) uci:unload("ddns") return data end -- called by XHR.get from detail_logview.htm function logread(section) -- read application settings local uci = UCI.cursor() local log_dir = uci:get("ddns", "global", "log_dir") or "/var/log/ddns" local lfile = log_dir .. "/" .. section .. ".log" local ldata = NXFS.readfile(lfile) if not ldata or #ldata == 0 then ldata="_nodata_" end uci:unload("ddns") HTTP.write(ldata) end -- called by XHR.get from overview_status.htm function startstop(section, enabled) local uci = UCI.cursor() local pid = DDNS.get_pid(section) local data = {} -- Array to transfer data to javascript -- if process running we want to stop and return if pid > 0 then local tmp = NX.kill(pid, 15) -- terminate NX.nanosleep(2) -- 2 second "show time" -- status changed so return full status data = _get_status() HTTP.prepare_content("application/json") HTTP.write_json(data) return end -- read uncommitted changes -- we don't save and commit data from other section or other options -- only enabled will be done local exec = true local changed = uci:changes("ddns") for k_config, v_section in pairs(changed) do -- security check because uci.changes only gets our config if k_config ~= "ddns" then exec = false break end for k_section, v_option in pairs(v_section) do -- check if only section of button was changed if k_section ~= section then exec = false break end for k_option, v_value in pairs(v_option) do -- check if only enabled was changed if k_option ~= "enabled" then exec = false break end end end end -- we can not execute because other -- uncommitted changes pending, so exit here if not exec then HTTP.write("_uncommitted_") return end -- save enable state uci:set("ddns", section, "enabled", ( (enabled == "true") and "1" or "0") ) uci:save("ddns") uci:commit("ddns") uci:unload("ddns") -- start dynamic_dns_updater.sh script os.execute ([[/usr/lib/ddns/dynamic_dns_updater.sh %s 0 > /dev/null 2>&1 &]] % section) NX.nanosleep(3) -- 3 seconds "show time" -- status changed so return full status data = _get_status() HTTP.prepare_content("application/json") HTTP.write_json(data) end -- called by XHR.poll from overview_status.htm function status() local data = _get_status() HTTP.prepare_content("application/json") HTTP.write_json(data) end
apache-2.0
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Danngogg.lua
36
1427
----------------------------------- -- Area: Northern San d'Oria -- NPC: Danngogg -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x021c); 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
thesabbir/luci
protocols/luci-proto-3g/luasrc/model/cbi/admin_network/proto_3g.lua
52
4346
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local device, apn, service, pincode, username, password, dialnumber local ipv6, maxwait, defaultroute, metric, peerdns, dns, keepalive_failure, keepalive_interval, demand device = section:taboption("general", Value, "device", translate("Modem device")) device.rmempty = false local device_suggestions = nixio.fs.glob("/dev/tty[A-Z]*") or nixio.fs.glob("/dev/tts/*") if device_suggestions then local node for node in device_suggestions do device:value(node) end end service = section:taboption("general", Value, "service", translate("Service Type")) service:value("", translate("-- Please choose --")) service:value("umts", "UMTS/GPRS") service:value("umts_only", translate("UMTS only")) service:value("gprs_only", translate("GPRS only")) service:value("evdo", "CDMA/EV-DO") apn = section:taboption("general", Value, "apn", translate("APN")) pincode = section:taboption("general", Value, "pincode", translate("PIN")) username = section:taboption("general", Value, "username", translate("PAP/CHAP username")) password = section:taboption("general", Value, "password", translate("PAP/CHAP password")) password.password = true dialnumber = section:taboption("general", Value, "dialnumber", translate("Dial number")) dialnumber.placeholder = "*99***1#" if luci.model.network:has_ipv6() then ipv6 = section:taboption("advanced", ListValue, "ipv6") ipv6:value("auto", translate("Automatic")) ipv6:value("0", translate("Disabled")) ipv6:value("1", translate("Manual")) ipv6.default = "auto" end maxwait = section:taboption("advanced", Value, "maxwait", translate("Modem init timeout"), translate("Maximum amount of seconds to wait for the modem to become ready")) maxwait.placeholder = "20" maxwait.datatype = "min(1)" defaultroute = section:taboption("advanced", Flag, "defaultroute", translate("Use default gateway"), translate("If unchecked, no default route is configured")) defaultroute.default = defaultroute.enabled metric = section:taboption("advanced", Value, "metric", translate("Use gateway metric")) metric.placeholder = "0" metric.datatype = "uinteger" metric:depends("defaultroute", defaultroute.enabled) peerdns = section:taboption("advanced", Flag, "peerdns", translate("Use DNS servers advertised by peer"), translate("If unchecked, the advertised DNS server addresses are ignored")) peerdns.default = peerdns.enabled dns = section:taboption("advanced", DynamicList, "dns", translate("Use custom DNS servers")) dns:depends("peerdns", "") dns.datatype = "ipaddr" dns.cast = "string" keepalive_failure = section:taboption("advanced", Value, "_keepalive_failure", translate("LCP echo failure threshold"), translate("Presume peer to be dead after given amount of LCP echo failures, use 0 to ignore failures")) function keepalive_failure.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^(%d+)[ ,]+%d+") or v) end end function keepalive_failure.write() end function keepalive_failure.remove() end keepalive_failure.placeholder = "0" keepalive_failure.datatype = "uinteger" keepalive_interval = section:taboption("advanced", Value, "_keepalive_interval", translate("LCP echo interval"), translate("Send LCP echo requests at the given interval in seconds, only effective in conjunction with failure threshold")) function keepalive_interval.cfgvalue(self, section) local v = m:get(section, "keepalive") if v and #v > 0 then return tonumber(v:match("^%d+[ ,]+(%d+)")) end end function keepalive_interval.write(self, section, value) local f = tonumber(keepalive_failure:formvalue(section)) or 0 local i = tonumber(value) or 5 if i < 1 then i = 1 end if f > 0 then m:set(section, "keepalive", "%d %d" %{ f, i }) else m:del(section, "keepalive") end end keepalive_interval.remove = keepalive_interval.write keepalive_interval.placeholder = "5" keepalive_interval.datatype = "min(1)" demand = section:taboption("advanced", Value, "demand", translate("Inactivity timeout"), translate("Close inactive connection after the given amount of seconds, use 0 to persist connection")) demand.placeholder = "0" demand.datatype = "uinteger"
apache-2.0
luanorlandi/SwiftSpaceBattle
src/ship/player.lua
2
4130
require "effect/spawnblink" local deckSize = Vector:new(60 * window.scale, 60 * window.scale) local deck = MOAIGfxQuad2D.new() deck:setTexture("texture/ship/ship5.png") deck:setRect(-deckSize.x, -deckSize.y, deckSize.x, deckSize.y) local deckDmg = MOAIGfxQuad2D.new() deckDmg:setTexture("texture/ship/ship5dmg.png") deckDmg:setRect(-deckSize.x, -deckSize.y, deckSize.x, deckSize.y) Player = {} Player.__index = Player function Player:new(pos) local P = {} P = Ship:new(deck, pos) setmetatable(P, Player) P.name = "Player" P.deck = deck P.deckDmg = deckDmg P.hp = 100 P.maxHp = 100 P.maxAcc = 0.25 * window.scale P.dec = P.maxAcc / 3 P.maxSpd = 3.5 * window.scale P.minSpd = P.maxAcc / 5 P.area.size = Rectangle:new(Vector:new(0, 0), deckSize) P.area:newRectangularArea(Vector:new(0, -0.4 * deckSize.y), Vector:new(0.8 * deckSize.x, 0.2 * deckSize.y)) P.area:newRectangularArea(Vector:new(0, 0), Vector:new(0.2 * deckSize.x, 1.0 * deckSize.y)) P.shotType = ShotLaserBlue P.shotSpd = 10 * window.scale P.fireRate = 0.5 table.insert(P.wpn, Vector:new(0.6 * P.area.size.size.x, 1.0 * P.area.size.size.y)) table.insert(P.wpn, Vector:new(-0.6 * P.area.size.size.x, 1.0 * P.area.size.size.y)) table.insert(P.fla, Vector:new(0.6 * P.area.size.size.x, -0.1 * P.area.size.size.y)) table.insert(P.fla, Vector:new(-0.6 * P.area.size.size.x, -0.1 * P.area.size.size.y)) P.spawnDuration = 1.8 P.expType = ExplosionType2 P.expDuration = 1.2 local spawnThread = coroutine.create(function() spawnBlink(P.sprite, P.spawnDuration) P.spawning = false end) coroutine.resume(spawnThread) table.insert(P.threads, spawnThread) -- hp regeneration local hpRegenThread = coroutine.create(function() Ship.hpRegen(P) end) coroutine.resume(hpRegenThread) table.insert(P.threads, hpRegenThread) return P end function Player:move() if self.spawned then -- define acceleration if MOAIEnvironment.osBrand == "Windows" or MOAIEnvironment.osBrand == "Android" then if input.left == true then self.acc.x = -self.maxAcc elseif input.right == true then self.acc.x = self.maxAcc else self.acc.x = 0.0 end else -- probably html host if input.pointerPos.x < player.pos.x - deckSize.x then self.acc.x = -self.maxAcc elseif input.pointerPos.x > player.pos.x + deckSize.x then self.acc.x = self.maxAcc else self.acc.x = 0.0 end end -- rotate ship if not self.rot:isActive() then -- define acceleration if MOAIEnvironment.osBrand == "Windows" or MOAIEnvironment.osBrand == "Android" then if input.up == true and self.aim.y == -1 then self.rot = self.sprite:moveRot(180, 0.8) self.aim.y = 1 interface.buttons:androidChangeSprite(self.aim.y) elseif input.down == true and self.aim.y == 1 then self.rot = self.sprite:moveRot(180, 0.8) self.aim.y = -1 interface.buttons:androidChangeSprite(self.aim.y) end else -- probably html host if input.pointerPos.y > player.pos.y and self.aim.y == -1 then self.rot = self.sprite:moveRot(180, 0.8) self.aim.y = 1 elseif input.pointerPos.y < player.pos.y and self.aim.y == 1 then self.rot = self.sprite:moveRot(180, 0.8) self.aim.y = -1 end end -- copy aim if playerData ~= nil then playerData.aim.x = self.aim.x playerData.aim.y = self.aim.y end end else self.acc.x = 0 self.acc.y = 0 end Ship.move(self) end function Player:rotateInstantly() self.sprite:moveRot(180, 0) self.aim.y = -self.aim.y end function Player:shoot() if self.spawned then if MOAIEnvironment.osBrand == "Windows" or MOAIEnvironment.osBrand == "Android" then if (input.up == true and self.aim.y == 1) or (input.down == true and self.aim.y == -1) or input.space then Ship.shoot(self, playerShots) end elseif input.pointerPressed or input.space then -- probably html host Ship.shoot(self, playerShots) end end end function Player:damaged(dmg) playerData:breakCombo() Ship.damaged(self, dmg) end function Player:muzzleflash() Ship.muzzleflashType1(self) end
gpl-3.0
nasomi/darkstar
scripts/zones/Beaucedine_Glacier_[S]/npcs/Gray_Colossus_LC.lua
38
1071
----------------------------------- -- Area: Beaucedine Glacier (S) -- NPC: Gray Colossus, L.C. -- Type: Campaign Arbiter -- @zone: 136 -- @pos 76.178 -60.763 -48.775 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Beaucedine_Glacier_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01c3); 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
nasomi/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Animated_Gun.lua
16
1469
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Animated Gun ----------------------------------- require("scripts/globals/status"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if (mob:AnimationSub() == 3) then SetDropRate(105,1585,1000); else SetDropRate(105,1585,0); end target:showText(mob,ANIMATED_GUN_DIALOG); SpawnMob(17330513,120):updateEnmity(target); SpawnMob(17330514,120):updateEnmity(target); SpawnMob(17330515,120):updateEnmity(target); SpawnMob(17330516,120):updateEnmity(target); SpawnMob(17330517,120):updateEnmity(target); SpawnMob(17330518,120):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) -- TODO: add battle dialog end; ----------------------------------- -- onMobDisengage ----------------------------------- function onMobDisengage(mob) mob:showText(mob,ANIMATED_GUN_DIALOG+2); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) killer:showText(mob,ANIMATED_GUN_DIALOG+1); DespawnMob(17330513); DespawnMob(17330514); DespawnMob(17330515); DespawnMob(17330516); DespawnMob(17330517); DespawnMob(17330518); end;
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/metropolis_torso_pistol_shot_3.meta.lua
2
2812
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 0.43000000715255737, amplification = 140, light_colors = { "89 31 168 255", "48 42 88 255", "61 16 123 0" }, radius = { x = 80, y = 80 }, standard_deviation = 6 }, generate_desaturation = false }, offsets = { gun = { bullet_spawn = { x = 0, y = 0 }, chamber = { pos = { x = 0, y = 0 }, rotation = 0 }, chamber_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, detachable_magazine = { pos = { x = 0, y = 0 }, rotation = 0 }, shell_spawn = { pos = { x = 0, y = 0 }, rotation = 0 } }, item = { attachment_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, back_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, beep_offset = { pos = { x = 0, y = 0 }, rotation = 0 }, hand_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, head_anchor = { pos = { x = 0, y = 0 }, rotation = 0 }, shoulder_anchor = { pos = { x = 0, y = 0 }, rotation = 0 } }, legs = { foot = { x = 0, y = 0 } }, non_standard_shape = { convex_partition = {}, original_poly = {} }, torso = { back = { pos = { x = -2, y = 15 }, rotation = -86.820167541503906 }, head = { pos = { x = -3, y = 1 }, rotation = 1.3400000333786011 }, legs = { pos = { x = 0, y = 0 }, rotation = 0 }, primary_hand = { pos = { x = 67, y = 6 }, rotation = 0 }, secondary_hand = { pos = { x = 0, y = 0 }, rotation = 0 }, secondary_shoulder = { pos = { x = 19, y = -4 }, rotation = 92 }, shoulder = { pos = { x = -21, y = -8 }, rotation = 87 }, strafe_facing_offset = -90 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
nasomi/darkstar
scripts/zones/Selbina/npcs/Vobo.lua
17
1507
----------------------------------- -- Area: Selbina -- NPC: Vobo -- Involved in Quest: Riding on the Clouds -- @pos 37 -14 81 248 ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_3") == 2) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_3",0); player:tradeComplete(); player:addKeyItem(SOMBER_STONE); player:messageSpecial(KEYITEM_OBTAINED,SOMBER_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02C6); 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
telergybot/kelidestan5454
plugins/banhammer.lua
214
11956
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end local bots_protection = "Yes" local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = '' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if member_id == our_id then return false end if get_cmd == 'kick' then if is_momod2(member_id, chat_id) then return send_large_msg(receiver, "you can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) then return send_large_msg(receiver, "you can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') return unbanall_user(member_id, chat_id) end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end local receiver = get_receiver(msg) if matches[1]:lower() == 'kickme' then-- /kickme if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return nil end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(tonumber(matches[2]), msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local member = string.gsub(matches[2], '@', '') local get_cmd = 'ban' local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end return end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'unban' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if msg.to.type == 'chat' then local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local member = string.gsub(matches[2], '@', '') local get_cmd = 'kick' local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id if msg.to.type == 'chat' then local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'banall' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local member = string.gsub(matches[2], '@', '') local get_cmd = 'unbanall' chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
nasomi/darkstar
scripts/zones/Port_San_dOria/npcs/Brifalien.lua
17
1776
----------------------------------- -- Area: Port San d'Oria -- NPC: Brifalien -- Involved in Quests: Riding on the Clouds -- @zone 232 -- @pos -20 -4 -74 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart Flyer player:messageSpecial(FLYER_REFUSED); end end if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_1") == 7) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_1",0); player:tradeComplete(); player:addKeyItem(SCOWLING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SCOWLING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x024d); 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
nasomi/darkstar
scripts/globals/items/slice_of_juicy_mutton.lua
35
1397
----------------------------------------- -- ID: 4335 -- Item: slice_of_juicy_mutton -- Food Effect: 240Min, All Races ----------------------------------------- -- Strength 3 -- Intelligence -1 -- Attack % 27 -- Attack Cap 35 ----------------------------------------- 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,4335); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 3); target:addMod(MOD_INT, -1); target:addMod(MOD_FOOD_ATTP, 27); target:addMod(MOD_FOOD_ATT_CAP, 35); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 3); target:delMod(MOD_INT, -1); target:delMod(MOD_FOOD_ATTP, 27); target:delMod(MOD_FOOD_ATT_CAP, 35); end;
gpl-3.0
Wouterz90/SuperSmashDota
Game/scripts/vscripts/libraries/attachments.lua
1
21490
ATTACHMENTS_VERSION = "1.00" --[[ Lua-controlled Frankenstein Attachments Library by BMD Installation -"require" this file inside your code in order to gain access to the Attachments global table. -Optionally require "libraries/notifications" before this file so that the Attachment Configuration GUI can display messages via the Notifications library. -Ensure that this file is placed in the vscripts/libraries path -Ensure that you have the barebones_attachments.xml, barebones_attachments.js, and barebones_attachments.css files in your panorama content folder to use the GUI. -Ensure that barebones_attachments.xml is included in your custom_ui_manifest.xml with <CustomUIElement type="Hud" layoutfile="file://{resources}/layout/custom_game/barebones_attachments.xml" /> -Finally, include the "attachments.txt" in your scripts directory if you have a pre-build database of attachment settings. Library Usage -The library when required in loads in the "scripts/attachments.txt" file containing the attachment properties database for use during your game mode. -Attachment properties are specified as a 3-tuple of unit model name, attachment point string, and attachment prop model name. -Ex: ("models/heroes/antimage/antimage.vmdl" // "attach_hitloc" // "models/items/axe/weapon_heavy_cutter.vmdl") -Optional particles can be specified in the "Particles" block of attachmets.txt. -To attach a prop to a unit, use the Attachments:AttachProp(unit, attachPoint, model[, scale[, properties] ]) function -Ex: Attachments:AttachProp(unit, "attach_hitloc", "models/items/axe/weapon_heavy_cutter.vmdl", 1.0) -This will create the prop and retrieve the properties from the database to attach it to the provided unit -If you pass in an already created prop or unit as the 'model' parameter, the attachment system will scale, position, and attach that prop/unit without creating a new one -Scale is the prop scale to be used, and defaults to 1.0. The scale of the prop will also be scaled based on the unit model scale. -It is possible not to use the attachment database, but to instead provide the properties directly in the 'properties' parameter. -This properties table will look like: { pitch = 45.0, yaw = 55.0, roll = 65.0, XPos = 10.0, YPos = -10.0, ZPos = -33.0, Animation = "idle_hurt" } -To retrieve the currently attached prop entity, you can call Attachments:GetCurrentAttachment(unit, attachPoint) -Ex: local prop = Attachments:AttachProp(unit, "attach_hitloc") -Calling prop:RemoveSelf() will automatically detach the prop from the unit -To access the loaded Attachment database directly (for reading properties directly), you can call Attachments:GetAttachmentDatabase() Attachment Configuration Usage -In tools-mode, execute "attachment_configure <ADDON_NAME>" to activate the attachment configuration GUI for setting up the attachment database. -See https://www.youtube.com/watch?v=PS1XmHGP3sw for an example of how to generally use the GUI -The Load button will reload the database from disk and update the current attach point/prop model if values are stored therein. -The Hide button will hide/remove the current atatach point/prop model being displayed -The Save button will save the current properties as well as any other adjusted properties in the attachment database to disk. -Databases will be saved to the scripts/attachments.txt file of the addon you set when calling the attachment_configure <ADDON_NAME> command. -More detail to come... Notes -"attach_origin" can be used as the attachment string for attaching a prop do the origin of the unit, even if that unit has no attachment point named "attach_origin" -Attached props will automatically scale when the parent unit/models are scaled, so rescaling individual props after attachment is not necessary. -This library requires that the "libraries/timers.lua" be present in your vscripts directory. Examples: --Attach an Axe axe model to the "attach_hitloc" to a given unit at a 1.0 Scale. Attachments:AttachProp(unit, "attach_hitloc", "models/items/axe/weapon_heavy_cutter.vmdl", 1.0) --For GUI use, see https://www.youtube.com/watch?v=PS1XmHGP3sw ]] --LinkLuaModifier( "modifier_animation_freeze", "libraries/modifiers/modifier_animation_freeze.lua", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_animation_freeze_stun", "libraries/attachments.lua", LUA_MODIFIER_MOTION_NONE ) modifier_animation_freeze_stun = class({}) function modifier_animation_freeze_stun:OnCreated(keys) end function modifier_animation_freeze_stun:GetAttributes() return MODIFIER_ATTRIBUTE_PERMANENT + MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE --+ MODIFIER_ATTRIBUTE_MULTIPLE end function modifier_animation_freeze_stun:IsHidden() return true end function modifier_animation_freeze_stun:IsDebuff() return false end function modifier_animation_freeze_stun:IsPurgable() return false end function modifier_animation_freeze_stun:CheckState() local state = { [MODIFIER_STATE_FROZEN] = true, [MODIFIER_STATE_STUNNED] = true, } return state end -- Drop out of self-include to prevent execution of timers library and other code in modifier lua VM environment if not Entities or not Entities.CreateByClassname then return end require('libraries/timers') local Notify = function(player, msg, duration) duration = duration or 2 if Notifications then local table = {text=msg, duration=duration, style={color="red"}} Notifications:Bottom(player, table) else print('[Attachments.lua] ' .. msg) end end function WriteKV(file, firstLine, t, indent, done) if type(t) ~= "table" then return end done = done or {} done[t] = true indent = indent or 1 file:write(string.rep ("\t", indent-1) .. "\"" .. firstLine .. "\"\n") file:write(string.rep ("\t", indent-1) .. "{\n") for k,value in pairs(t) do if type(value) == "table" and not done[value] then done [value] = true WriteKV (file, k, value, indent + 1, done) elseif type(value) == "userdata" and not done[value] then --skip userdata else file:write(string.rep ("\t", indent) .. "\"" .. tostring(k) .. "\"\t\t\"" .. tostring(value) .. "\"\n") end end file:write(string.rep ("\t", indent-1) .. "}\n") end if not Attachments then Attachments = class({}) end function Attachments:start() local src = debug.getinfo(1).source --print(src) self.gameDir = "" self.addonName = "" if IsInToolsMode() then if src:sub(2):find("(.*dota 2 beta[\\/]game[\\/]dota_addons[\\/])([^\\/]+)[\\/]") then self.gameDir, self.addonName = string.match(src:sub(2), "(.*dota 2 beta[\\/]game[\\/]dota_addons[\\/])([^\\/]+)[\\/]") --print('[attachments] ', self.gameDir) --print('[attachments] ', self.addonName) self.initialized = true self.activated = false self.dbFilePath = nil self.currentAttach = {} self.hiddenCosmetics = {} self.doAttach = true self.doSphere = false self.attachDB = LoadKeyValues("scripts/attachments.txt") if IsInToolsMode() then print('[attachments] Tools Mode') SendToServerConsole("dota_combine_models 0") Convars:RegisterCommand( "attachment_configure", Dynamic_Wrap(Attachments, 'ActivateAttachmentSetup'), "Activate Attachment Setup", FCVAR_CHEAT ) end else print("[attachments] RELOADING") SendToServerConsole("script_reload_code " .. src:sub(2)) end else self.initialized = true self.activated = false self.dbFilePath = nil self.currentAttach = {} self.hiddenCosmetics = {} self.doAttach = true self.doSphere = false self.attachDB = LoadKeyValues("scripts/attachments.txt") end end function Attachments:ActivateAttachmentSetup() addon = Attachments.addonName --[[if addon == nil or addon == "" then print("[Attachments.lua] Addon name must be specified.") return end]] print("running") if not io then print("[Attachments.lua] Attachments Setup is only available in tools mode.") return end if not Attachments.activated then local file = io.open("../../dota_addons/" .. addon .. "/scripts/attachments.txt", 'r') if not file and Attachments.dbFilePath == nil then print("[Attachments.lua] Cannot find file 'dota_addons/" .. addon .. "/scripts/attachments.txt'. Re-execute the console command to force create the file.") Attachments.dbFilePath = "" return end Attachments.dbFilePath = "../../dota_addons/" .. addon .. "/scripts/attachments.txt" if not file then file = io.open(Attachments.dbFilePath, 'w') WriteKV(file, "Attachments", {}) print("[Attachments.lua] Created file: 'dota_addons/" .. addon .. "/scripts/attachments.txt'.") end file:close() CustomGameEventManager:RegisterListener("Attachment_DoSphere", Dynamic_Wrap(Attachments, "Attachment_DoSphere")) CustomGameEventManager:RegisterListener("Attachment_DoAttach", Dynamic_Wrap(Attachments, "Attachment_DoAttach")) CustomGameEventManager:RegisterListener("Attachment_Freeze", Dynamic_Wrap(Attachments, "Attachment_Freeze")) CustomGameEventManager:RegisterListener("Attachment_UpdateAttach", Dynamic_Wrap(Attachments, "Attachment_UpdateAttach")) CustomGameEventManager:RegisterListener("Attachment_SaveAttach", Dynamic_Wrap(Attachments, "Attachment_SaveAttach")) CustomGameEventManager:RegisterListener("Attachment_LoadAttach", Dynamic_Wrap(Attachments, "Attachment_LoadAttach")) CustomGameEventManager:RegisterListener("Attachment_HideAttach", Dynamic_Wrap(Attachments, "Attachment_HideAttach")) CustomGameEventManager:RegisterListener("Attachment_UpdateUnit", Dynamic_Wrap(Attachments, "Attachment_UpdateUnit")) CustomGameEventManager:RegisterListener("Attachment_HideCosmetic", Dynamic_Wrap(Attachments, "Attachment_HideCosmetic")) Attachments.activated = true Attachments.doSphere = true end local ply = Convars:GetCommandClient() CustomGameEventManager:Send_ServerToPlayer(ply, "activate_attachment_configuration", {}) end function Attachments:Attachment_DoSphere(args) --DebugPrint(1,'Attachment_DoSphere') --DebugPrintTable(1,args) Attachments.doSphere = args.doSphere == 1 Attachments:Attachment_UpdateAttach(args) end function Attachments:Attachment_DoAttach(args) --DebugPrint(1,'Attachment_DoAttach') --DebugPrintTable(1,args) Attachments.doAttach = args.doAttach == 1 Attachments:Attachment_UpdateAttach(args) end function Attachments:Attachment_Freeze(args) --DebugPrint(1,'Attachment_Freeze') --DebugPrintTable(1,args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end if args.freeze == 1 then unit:AddNewModifier(unit, nil, "modifier_animation_freeze_stun", {}) unit:SetForwardVector(Vector(0,-1,0)) --unit:AddNewModifier(unit, nil, "modifier_stunned", {}) else unit:RemoveModifierByName("modifier_animation_freeze_stun") --unit:RemoveModifierByName("modifier_stunned") end end function Attachments:Attachment_UpdateAttach(args) DebugPrint(1,'Attachment_UpdateAttach') DebugPrintTable(1,args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local properties = args.properties local unitModel = unit:GetModelName() local attach = properties.attach local model = properties.model properties.attach = nil properties.model = nil if not string.find(model, "%.vmdl$") then Notify(args.PlayerID, "Prop model must end in '.vmdl'.") return end local point = unit:ScriptLookupAttachment(attach) if attach ~= "attach_origin" and point == 0 then Notify(args.PlayerID, "Attach point '" .. attach .. "' not found.") return end local db = Attachments.attachDB if not db[unitModel] then db[unitModel] = {} end if not db[unitModel][attach] then db[unitModel][attach] = {} end local oldProperties = db[unitModel][attach][model] or {} -- update old properties for k,v in pairs(properties) do oldProperties[k] = v end properties = oldProperties db[unitModel][attach][model] = properties if not Attachments.currentAttach[args.index] then Attachments.currentAttach[args.index] = {} end local prop = Attachments.currentAttach[args.index][attach] if prop and IsValidEntity(prop) then prop:RemoveSelf() end --Attachments.currentAttach[args.index][attach] = Attachments:AttachProp(unit, attach, model, properties.scale) Attachments:AttachProp(unit, attach, model, properties.scale) end function Attachments:Attachment_SaveAttach(args) --DebugPrint(1,'Attachment_SaveAttach') --DebugPrintTable(1,args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local properties = args.properties local unitModel = unit:GetModelName() local attach = properties.attach local model = properties.model Attachments:Attachment_UpdateAttach(args) if not io then print("[Attachments.lua] Attachments Setup is only available in tools mode.") return end if Attachments.dbFilePath == nil or Attachments.dbFilePath == "" then print("[Attachments.lua] Attachments database file must be set.") return end local file = io.open(Attachments.dbFilePath, 'w') WriteKV(file, "Attachments", Attachments.attachDB) file:close(); end function Attachments:Attachment_LoadAttach(args) --DebugPrint(1,'Attachment_LoadAttach') --DebugPrintTable(1,args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local properties = args.properties local unitModel = unit:GetModelName() local attach = properties.attach local model = properties.model if not io then print("[Attachments.lua] Attachments Setup is only available in tools mode.") return end Attachments.attachDB = LoadKeyValues("scripts/attachments.txt") local db = Attachments.attachDB if not db[unitModel] or not db[unitModel][attach] or not db[unitModel][attach][model] then Notify(args.PlayerID, "No saved attach found for '" .. attach .. "'' / '" .. model .. "' on this unit.") return end local ply = PlayerResource:GetPlayer(args.PlayerID) local properties = {} for k,v in pairs(db[unitModel][attach][model]) do properties[k] = v end properties.attach = attach properties.model = model CustomGameEventManager:Send_ServerToPlayer(ply, "attachment_update_fields", properties) end function Attachments:Attachment_HideAttach(args) --DebugPrint(1,'Attachment_HideAttach') --DebugPrintTable(1,args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local properties = args.properties local attach = properties.attach local currentAttach = Attachments.currentAttach if not currentAttach[args.index] or not currentAttach[args.index][attach] then Notify(args.PlayerID, "No Current Attach to Hide for '" .. attach .. "'.") return end local prop = currentAttach[args.index][attach] if prop and IsValidEntity(prop) then prop:RemoveSelf() end currentAttach[args.index][attach] = nil end function Attachments:Attachment_UpdateUnit(args) --DebugPrint(1,'Attachment_UpdateUnit') --DebugPrintTable(1,args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local cosmetics = {} for i,child in ipairs(unit:GetChildren()) do if child:GetClassname() == "dota_item_wearable" and child:GetModelName() ~= "" then table.insert(cosmetics, child:GetModelName()) end end --DebugPrintTable(1,cosmetics) CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(args.PlayerID), "attachment_cosmetic_list", cosmetics ) end function Attachments:Attachment_HideCosmetic(args) --DebugPrint(1,'Attachment_HideCosmetic') --DebugPrintTable(1,args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local model = args.model; local cosmetics = {} for i,child in ipairs(unit:GetChildren()) do if child:GetClassname() == "dota_item_wearable" and child:GetModelName() == model then local hiddenCosmetics = Attachments.hiddenCosmetics[args.index] if not hiddenCosmetics then hiddenCosmetics = {} Attachments.hiddenCosmetics[args.index] = hiddenCosmetics end if hiddenCosmetics[model] then child:RemoveEffects(EF_NODRAW) hiddenCosmetics[model] = nil else --print("HIDING") child:AddEffects(EF_NODRAW) hiddenCosmetics[model] = true end end end end function Attachments:GetAttachmentDatabase() return Attachments.attachDB end function Attachments:GetCurrentAttachment(unit, attachPoint) if not Attachments.currentAttach[unit:entindex()] then return nil end local prop = Attachments.currentAttach[unit:entindex()][attachPoint] return prop end function Attachments:AttachProp(unit, attachPoint, model, scale, properties) local unitModel = unit:GetModelName() local propModel = model local db = Attachments.attachDB if propModel.GetModelName then propModel = propModel:GetModelName() end if not properties then if not db[unitModel] or not db[unitModel][attachPoint] or not db[unitModel][attachPoint][propModel] then print("[Attachments.lua] No attach found in attachment database for '" .. unitModel .. "', '" .. attachPoint .. "', '" .. propModel .. "'") return end end local attach = unit:ScriptLookupAttachment(attachPoint) local scale = scale or db[unitModel][attachPoint][propModel]['scale'] or 1.0 properties = properties or db[unitModel][attachPoint][propModel] local pitch = tonumber(properties.pitch) local yaw = tonumber(properties.yaw) local roll = tonumber(properties.roll) --local angleSpace = QAngle(properties.QX, properties.QY, properties.QZ) local offset = Vector(tonumber(properties.XPos), tonumber(properties.YPos), tonumber(properties.ZPos)) * scale * unit:GetModelScale() local animation = properties.Animation --offset = RotatePosition(Vector(0,0,0), RotationDelta(angleSpace, QAngle(0,0,0)), offset) --local new_prop = Entities:CreateByClassname("prop_dynamic") local prop = nil if model.GetName and IsValidEntity(model) then prop = model else prop = SpawnEntityFromTableSynchronous("prop_dynamic", {model = propModel, DefaultAnim=animation, targetname=DoUniqueString("prop_dynamic")}) prop:SetModelScale(scale * unit:GetModelScale()) end local angles = unit:GetAttachmentAngles(attach) angles = QAngle(angles.x, angles.y, angles.z) --angles = RotationDelta(angles,QAngle(pitch, yaw, roll)) --print(prop:GetAngles()) --print(angles) --print(RotationDelta(RotationDelta(angles,QAngle(pitch, yaw, roll)),QAngle(0,0,0))) --angles = QAngle(pitch, yaw, roll) if not Attachments.doAttach then angles = QAngle(pitch, yaw, roll) end angles = RotateOrientation(angles,RotationDelta(QAngle(pitch, yaw, roll), QAngle(0,0,0))) --print('angleSpace = QAngle(' .. angles.x .. ', ' .. angles.y .. ', ' .. angles.z .. ')') local attach_pos = unit:GetAttachmentOrigin(attach) --attach_pos = attach_pos + RotatePosition(Vector(0,0,0), QAngle(angles.x,angles.y,angles.z), offset) attach_pos = attach_pos + RotatePosition(Vector(0,0,0), angles, offset) prop:SetAbsOrigin(attach_pos) prop:SetAngles(angles.x,angles.y,angles.z) -- Attach and store it if Attachments.doAttach then if attachPoint == "attach_origin" then prop:SetParent(unit, "") else prop:SetParent(unit, attachPoint) end end -- From Noya local particle_data = nil if db['Particles'] then particle_data = db['Particles'][propModel] end if particle_data then for particleName,control_points in pairs(particle_data) do prop.fx = ParticleManager:CreateParticle(particleName, PATTACH_ABSORIGIN, prop) -- Loop through the Control Point Entities for k,ent_point in pairs(control_points) do ParticleManager:SetParticleControlEnt(prop.fx, tonumber(k), prop, PATTACH_POINT_FOLLOW, ent_point, prop:GetAbsOrigin(), true) end end end if Attachments.timer then Timers:RemoveTimer(Attachments.timer) end Attachments.timer = Timers:CreateTimer(function() if Attachments.doSphere then if unit and IsValidEntity(unit) then DebugDrawSphere(unit:GetAttachmentOrigin(attach), Vector(255,255,255), 100, 15, true, .03) end if prop and IsValidEntity(prop) then DebugDrawSphere(prop:GetAbsOrigin(), Vector(0,0,0), 100, 15, true, .03) end end return .03 end) if not Attachments.currentAttach[unit:GetEntityIndex()] then Attachments.currentAttach[unit:GetEntityIndex()] = {} end Attachments.currentAttach[unit:GetEntityIndex()][attachPoint] = prop return prop end if not Attachments.initialized then Attachments:start() end
mit
nasomi/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Elysia.lua
17
2386
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Elysia -- Starts Quest: Unforgiven -- @zone 26 -- @pos -50.410 -22.204 -41.640 ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs") require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/globals/player"); require("scripts/globals/titles"); ----------------------------------- -- For those who don't know -- at the end of if (player:getQuestStatus(REGION,QUEST_NAME) -- == 0 means QUEST_AVAILABLE -- == 1 means QUEST_ACCEPTED -- == 2 means QUEST_COMPLETED -- e.g. if (player:getQuestStatus(OTHER_AREAS,UNFORGIVEN) == 0 -- means if (player:getQuestStatus(OTHER_AREAS,UNFORGIVEN) == QUEST AVAILABLE ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local Unforgiven = player:getQuestStatus(OTHER_AREAS,UNFORGIVEN); if (Unforgiven == 0) then player:startEvent(0x00C8); -- Quest Start Dialogue elseif (Unforgiven == 1 and player:getVar("UnforgivenVar") == 1) then player:startEvent(0x00CB); -- Dialogue if player hasn't talked to Pradiulot (2nd stage of Quest) elseif (Unforgiven == 1 and player:hasKeyItem(609) == false) then player:startEvent(0x00C9); -- Dialogue if player doesn't have keyitem elseif (Unforgiven == 1 and player:hasKeyItem(609) == true) then player:startEvent(0x00CA); -- Dialogue if player has keyitem (1st stage of Quest) else player:startEvent(0x00BE); 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 == 0x00C8) then player:addQuest(OTHER_AREAS,UNFORGIVEN); elseif (csid == 0x00CA) then player:setVar("UnforgivenVar",1); -- SET THE VAR end end;
gpl-3.0