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/Northern_San_dOria/npcs/HomePoint#2.lua
17
1262
----------------------------------- -- Area: Northern San dOria -- NPC: HomePoint#2 -- @pos 10 -0.2 95 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Northern_San_dOria/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fd, 4); 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 == 0x21fd) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/flame_claymore.lua
42
1072
----------------------------------------- -- ID: 16588 -- Item: Flame Claymore -- Additional Effect: Fire Damage ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onAdditionalEffect Action ----------------------------------- function onAdditionalEffect(player,target,damage) local chance = 5; if (math.random(0,99) >= chance) then return 0,0,0; else local dmg = math.random(3,10); local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(player, ELE_FIRE, target, dmg, params); dmg = dmg * applyResistanceAddEffect(player,target,ELE_FIRE,0); dmg = adjustForTarget(target,dmg,ELE_FIRE); dmg = finalMagicNonSpellAdjustments(player,target,ELE_FIRE,dmg); local message = MSGBASIC_ADD_EFFECT_DMG; if (dmg < 0) then message = MSGBASIC_ADD_EFFECT_HEAL; end return SUBEFFECT_FIRE_DAMAGE,message,dmg; end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Mhaura/npcs/Numi_Adaligo.lua
17
1404
----------------------------------- -- Area: Mhaura -- NPC: Numi Adaligo -- Involved In Quest: RYCHARDE_THE_CHEF ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); require("scripts/globals/settings"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x32); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local RychardetheChef = player:getQuestStatus(OTHER_AREAS,RYCHARDE_THE_CHEF); local QuestStatus=player:getVar("QuestRychardetheChef_var"); if ((option == 2) and (RychardetheChef == QUEST_AVAILABLE) and (tonumber(QuestStatus) == 0)) then player:setVar("QuestRychardetheChef_var",1); -- first stage of rycharde the chef quest end; end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/bretzel.lua
35
1302
----------------------------------------- -- ID: 4391 -- Item: Bretzel -- Food Effect: 3Min, All Races ----------------------------------------- -- Magic % 8 -- Magic Cap 55 -- Vitality 2 ----------------------------------------- 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,180,4391); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_MPP, 8); target:addMod(MOD_FOOD_MP_CAP, 55); target:addMod(MOD_VIT, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_MPP, 8); target:delMod(MOD_FOOD_MP_CAP, 55); target:delMod(MOD_VIT, 2); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Animated_Dagger.lua
16
1481
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Animated Dagger ----------------------------------- require("scripts/globals/status"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if (mob:AnimationSub() == 3) then SetDropRate(103,1572,1000); else SetDropRate(103,1572,0); end target:showText(mob,ANIMATED_DAGGER_DIALOG); SpawnMob(17330306,120):updateEnmity(target); SpawnMob(17330307,120):updateEnmity(target); SpawnMob(17330308,120):updateEnmity(target); SpawnMob(17330316,120):updateEnmity(target); SpawnMob(17330317,120):updateEnmity(target); SpawnMob(17330318,120):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) -- TODO: add battle dialog end; ----------------------------------- -- onMobDisengage ----------------------------------- function onMobDisengage(mob) mob:showText(mob,ANIMATED_DAGGER_DIALOG+2); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) killer:showText(mob,ANIMATED_DAGGER_DIALOG+1); DespawnMob(17330306); DespawnMob(17330307); DespawnMob(17330308); DespawnMob(17330316); DespawnMob(17330317); DespawnMob(17330318); end;
gpl-3.0
iuser99/BoL
Common/SidasAutoCarryPlugin - Mordekaiser.lua
2
1834
--[[ SAC Mordekaiser Credits to eXtragoZ for pet management Version 1.2 - Converted to iFoundation_v2 LAST TESTED 1.2 ON 8.11 WORKING PERFECT --]] require "iFoundation_v2" local SkillQ = Caster(_Q, 200, SPELL_SELF) local SkillW = Caster(_W, 750, SPELL_TARGETED_FRIENDLY) local SkillE = Caster(_E, 700, SPELL_CONE) local SkillR = Caster(_R, 850, SPELL_TARGETED) local rGhost = false local rDelay = 0 function PluginOnLoad() AutoCarry.SkillsCrosshair.range = 600 MainMenu = AutoCarry.MainMenu PluginMenu = AutoCarry.PluginMenu PluginMenu:addParam("sep1", "-- Spell Cast Options --", SCRIPT_PARAM_INFO, "") PluginMenu:addParam("rKS", "KillSteal with R", SCRIPT_PARAM_ONOFF, true) PluginMenu:addParam("eKS", "KillSteal with E", SCRIPT_PARAM_ONOFF, true) PluginMenu:addParam("wPercentage", "Monitor w percentage",SCRIPT_PARAM_SLICE, 0, 0, 100, 0) end function PluginOnTick() Target = AutoCarry.GetAttackTarget() rGhost = myHero:GetSpellData(_R).name == "mordekaisercotgguide" if Target and MainMenu.AutoCarry then if SkillQ:Ready() then SkillQ:Cast(Target) end if SkillE:Ready() then SkillE:Cast(Target) end if SkillW:Ready() and Monitor.GetLowAlly() ~= nil then SkillW:Cast(Monitor.GetLowAlly()) elseif (myHero.health < myHero.maxHealth * (PluginMenu.wPercentage / 100)) then SkillW:Cast(myHero) elseif Monitor.GetAllyWithMostEnemies(750) ~= nil then SkillW:Cast(Monitor.GetAllyWithMostEnemies(750)) end if SkillR:Ready() and rGhost and GetTickCount() >= rDelay then SkillR:Cast(Target) rDelay = GetTickCount() + 1000 elseif not rGhost and SkillR:Ready() and DamageCalculation.CalculateRealDamage(Target) > Target.health then SkillR:Cast(Target) elseif not rGhost and getDmg("R", Target, myHero) >= Target.health then SkillR:Cast(Target) end end end
gpl-2.0
nasomi/darkstar
scripts/globals/abilities/alacrity.lua
28
1151
----------------------------------- -- Ability: Alacrity -- Reduces the casting and the recast time of your next black magic spell by 50%. -- Obtained: Scholar Level 25 -- Recast Time: Stratagem Charge -- Duration: 1 black magic spell or 60 seconds, whichever occurs first. -- -- Level |Charges |Recharge Time per Charge -- ----- -------- --------------- -- 10 |1 |4:00 minutes -- 30 |2 |2:00 minutes -- 50 |3 |1:20 minutes -- 70 |4 |1:00 minute -- 90 |5 |48 seconds ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if player:hasStatusEffect(EFFECT_ALACRITY) then return MSGBASIC_EFFECT_ALREADY_ACTIVE, 0; end return 0,0; end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) player:addStatusEffect(EFFECT_ALACRITY,1,0,60); return EFFECT_ALACRITY; end;
gpl-3.0
iuser99/BoL
Common/SidasAutoCarryPlugin - Vladimir.lua
2
1609
--[[ SAC Vladimir plugin Features - Basic combo - Q > E > W > R Version 1.0 - Initial release Version 1.2 - Converted to iFoundation_v2 --]] require "iFoundation_v2" local SkillQ = Caster(_Q, 600, SPELL_TARGETED) local SkillW = Caster(_W, math.huge, SPELL_SELF) local SkillE = Caster(_E, 600, SPELL_SELF) local SkillR = Caster(_R, 700, SPELL_CIRCLE) local eTick = 0 function PluginOnLoad() AutoCarry.SkillsCrosshair.range = 700 MainMenu = AutoCarry.MainMenu PluginMenu = AutoCarry.PluginMenu PluginMenu:addParam("sep1", "-- Spell Cast Options --", SCRIPT_PARAM_INFO, "") PluginMenu:addParam("eStack", "Stack E", SCRIPT_PARAM_ONOFF, true) PluginMenu:addParam("rAmount", "Amount of people to use R on",SCRIPT_PARAM_SLICE, 3, 0, 5, 0) AutoShield.Instance(SkillW.range, SkillW) end function PluginOnTick() Target = AutoCarry.GetAttackTarget() if SkillE:Ready() and not Monitor.IsTeleporting() and PluginMenu.eStack and GetTickCount() - eTick >= 9500 then eTick = GetTickCount() SkillE:Cast(Target) end if Target and MainMenu.AutoCarry then if SkillQ:Ready() then SkillQ:Cast(Target) end if SkillE:Ready() then SkillE:Cast(Target) end if SkillR:Ready() then if ((DamageCalculation.CalculateRealDamage(Target) > Target.health) or (getDmg("R", Target, myHero) > Target.health)) then SkillR:Cast(Target) elseif Monitor.CountEnemies(Target, SkillR.width) >= PluginMenu.rAmount then SkilLR:Cast(Target) end end end if MainMenu.LastHit or MainMenu.LaneClear then if not Target then Combat.LastHit(SkillQ, SkillQ.range) end end end
gpl-2.0
thesabbir/luci
applications/luci-app-multiwan/luasrc/controller/multiwan.lua
62
1929
module("luci.controller.multiwan", package.seeall) function index() local fs = require "nixio.fs" if not fs.access("/etc/config/multiwan") then return end local page page = entry({"admin", "network", "multiwan"}, cbi("multiwan/multiwan"), _("Multi-WAN")) page.dependent = true entry({"admin", "network", "multiwan", "status"}, call("multiwan_status")) page = entry({"mini", "network", "multiwan"}, cbi("multiwan/multiwanmini", {autoapply=true}), _("Multi-WAN")) page.dependent = true end function multiwan_status() local nfs = require "nixio.fs" local cachefile = "/tmp/.mwan/cache" local rv = { } cachefile = nfs.readfile(cachefile) if cachefile then local ntm = require "luci.model.network".init() _, _, wan_if_map = string.find(cachefile, "wan_if_map=\"([^\"]*)\"") _, _, wan_fail_map = string.find(cachefile, "wan_fail_map=\"([^\"]*)\"") _, _, wan_recovery_map = string.find(cachefile, "wan_recovery_map=\"([^\"]*)\"") rv.wans = { } wansid = {} for wanname, wanifname in string.gfind(wan_if_map, "([^%[]+)%[([^%]]+)%]") do local wanlink = ntm:get_interface(wanifname) wanlink = wanlink and wanlink:get_network() wanlink = wanlink and wanlink:adminlink() or "#" wansid[wanname] = #rv.wans + 1 rv.wans[wansid[wanname]] = { name = wanname, link = wanlink, ifname = wanifname, status = "ok", count = 0 } end for wanname, failcount in string.gfind(wan_fail_map, "([^%[]+)%[([^%]]+)%]") do if failcount == "x" then rv.wans[wansid[wanname]].status = "ko" else rv.wans[wansid[wanname]].status = "failing" rv.wans[wansid[wanname]].count = failcount end end for wanname, recoverycount in string.gfind(wan_recovery_map, "([^%[]+)%[([^%]]+)%]") do rv.wans[wansid[wanname]].status = "recovering" rv.wans[wansid[wanname]].count = recoverycount end end luci.http.prepare_content("application/json") luci.http.write_json(rv) end
apache-2.0
iassael/learning-to-communicate
code/module/rmsprop.lua
1
1911
--[[ An implementation of RMSprop ARGS: - 'opfunc' : a function that takes a single input (X), the point of a evaluation, and returns f(X) and df/dX - 'x' : the initial point - 'config` : a table with configuration parameters for the optimizer - 'config.learningRate' : learning rate - 'config.alpha' : smoothing constant - 'config.epsilon' : value with which to initialise m - 'config.weightDecay' : weight decay - 'state' : a table describing the state of the optimizer; after each call the state is modified - 'state.m' : leaky sum of squares of parameter gradients, - 'state.tmp' : and the square root (with epsilon smoothing) RETURN: - `x` : the new x vector - `f(x)` : the function, evaluated before the update ]] function optim.rmsprop(opfunc, x, config, state) -- (0) get/update state local config = config or {} local state = state or config local lr = config.learningRate or 1e-2 local alpha = config.alpha or 0.99 local epsilon = config.epsilon or 1e-8 local wd = config.weightDecay or 0 -- (1) evaluate f(x) and df/dx local fx, dfdx = opfunc(x) -- (2) weight decay if wd ~= 0 then dfdx:add(wd, x) end -- (3) initialize mean square values and square gradient storage if not state.m then -- This line kills the performance -- state.m = torch.Tensor():typeAs(x):resizeAs(dfdx):fill(1) state.m = torch.Tensor():typeAs(x):resizeAs(dfdx):zero() state.tmp = torch.Tensor():typeAs(x):resizeAs(dfdx) end -- (4) calculate new (leaky) mean squared values state.m:mul(alpha) state.m:addcmul(1.0-alpha, dfdx, dfdx) -- (5) perform update state.tmp:sqrt(state.m):add(epsilon) x:addcdiv(-lr, dfdx, state.tmp) -- return x*, f(x) before optimization return x, {fx} end
apache-2.0
nasomi/darkstar
scripts/zones/Bastok_Markets_[S]/TextIDs.lua
9
1074
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 11199; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6384; -- Obtained: <item> GIL_OBTAINED = 6385; -- Obtained <number> gil KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7043; -- You can't fish here -- Other Texts KARLOTTE_DELIVERY_DIALOG = 10839; -- I am here to help with all your parcel delivery needs. WELDON_DELIVERY_DIALOG = 10840; -- Do you have something you wish to send? -- Shop Texts BLINGBRIX_SHOP_DIALOG = 7188; -- Blingbrix good Gobbie from Boodlix's! Boodlix's Emporium help fighting fighters and maging mages. Gil okay, okay SILKE_SHOP_DIALOG = 12780; -- You wouldn't happen to be a fellow scholar, by any chance? The contents of these pages are beyond me, but perhaps you might glean something from them. They could be yours...for a nominal fee. -- Porter Moogle RETRIEVE_DIALOG_ID = 14689; -- You retrieve a <item> from the porter moogle's care.
gpl-3.0
nasomi/darkstar
scripts/globals/abilities/pets/grand_fall.lua
25
1294
--------------------------------------------------- -- Geocrush --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); require("scripts/globals/magic"); --------------------------------------------------- function onAbilityCheck(player, target, ability) return 0,0; end; function onPetAbility(target, pet, skill) local dINT = math.floor(pet:getStat(MOD_INT) - target:getStat(MOD_INT)); local tp = skill:getTP(); local master = pet:getMaster(); local merits = 0; if (master ~= nil and master:isPC()) then merits = master:getMerit(MERIT_GRANDFALL); end tp = tp + (merits - 40); if (tp > 300) then tp = 300; end --note: this formula is only accurate for level 75 - 76+ may have a different intercept and/or slope local damage = math.floor(512 + 1.72*(tp+1)); damage = damage + (dINT * 1.5); damage = MobMagicalMove(pet,target,skill,damage,ELE_WATER,1,TP_NO_EFFECT,0); damage = mobAddBonuses(pet, nil, target, damage.dmg, ELE_WATER); damage = AvatarFinalAdjustments(damage,pet,skill,target,MOBSKILL_MAGICAL,MOBPARAM_NONE,1); target:delHP(damage); target:updateEnmityFromDamage(pet,damage); return damage; end
gpl-3.0
shangjiyu/luci-with-extra
libs/luci-lib-nixio/docsrc/nixio.File.lua
173
4457
--- Large File Object. -- Large file operations are supported up to 52 bits if the Lua number type is -- double (default). -- @cstyle instance module "nixio.File" --- Write to the file descriptor. -- @class function -- @name File.write -- @usage <strong>Warning:</strong> It is not guaranteed that all data -- in the buffer is written at once especially when dealing with pipes. -- You have to check the return value - the number of bytes actually written - -- or use the safe IO functions in the high-level IO utility module. -- @usage Unlike standard Lua indexing the lowest offset and default is 0. -- @param buffer Buffer holding the data to be written. -- @param offset Offset to start reading the buffer from. (optional) -- @param length Length of chunk to read from the buffer. (optional) -- @return number of bytes written --- Read from a file descriptor. -- @class function -- @name File.read -- @usage <strong>Warning:</strong> It is not guaranteed that all requested data -- is read at once especially when dealing with pipes. -- You have to check the return value - the length of the buffer actually read - -- or use the safe IO functions in the high-level IO utility module. -- @usage The length of the return buffer is limited by the (compile time) -- nixio buffersize which is <em>nixio.const.buffersize</em> (8192 by default). -- Any read request greater than that will be safely truncated to this value. -- @param length Amount of data to read (in Bytes). -- @return buffer containing data successfully read --- Reposition read / write offset of the file descriptor. -- The seek will be done either from the beginning of the file or relative -- to the current position or relative to the end. -- @class function -- @name File.seek -- @usage This function calls lseek(). -- @param offset File Offset -- @param whence Starting point [<strong>"set"</strong>, "cur", "end"] -- @return new (absolute) offset position --- Return the current read / write offset of the file descriptor. -- @class function -- @name File.tell -- @usage This function calls lseek() with offset 0 from the current position. -- @return offset position --- Synchronizes the file with the storage device. -- Returns when the file is successfully written to the disk. -- @class function -- @name File.sync -- @usage This function calls fsync() when data_only equals false -- otherwise fdatasync(), on Windows _commit() is used instead. -- @usage fdatasync() is only supported by Linux and Solaris. For other systems -- the <em>data_only</em> parameter is ignored and fsync() is always called. -- @param data_only Do not synchronize the metadata. (optional, boolean) -- @return true --- Apply or test a lock on the file. -- @class function -- @name File.lock -- @usage This function calls lockf() on POSIX and _locking() on Windows. -- @usage The "lock" command is blocking, "tlock" is non-blocking, -- "ulock" unlocks and "test" only tests for the lock. -- @usage The "test" command is not available on Windows. -- @usage Locks are by default advisory on POSIX, but mandatory on Windows. -- @param command Locking Command ["lock", "tlock", "ulock", "test"] -- @param length Amount of Bytes to lock from current offset (optional) -- @return true --- Get file status and attributes. -- @class function -- @name File.stat -- @param field Only return a specific field, not the whole table (optional) -- @usage This function calls fstat(). -- @return Table containing: <ul> -- <li>atime = Last access timestamp</li> -- <li>blksize = Blocksize (POSIX only)</li> -- <li>blocks = Blocks used (POSIX only)</li> -- <li>ctime = Creation timestamp</li> -- <li>dev = Device ID</li> -- <li>gid = Group ID</li> -- <li>ino = Inode</li> -- <li>modedec = Mode converted into a decimal number</li> -- <li>modestr = Mode as string as returned by `ls -l`</li> -- <li>mtime = Last modification timestamp</li> -- <li>nlink = Number of links</li> -- <li>rdev = Device ID (if special file)</li> -- <li>size = Size in bytes</li> -- <li>type = ["reg", "dir", "chr", "blk", "fifo", "lnk", "sock"]</li> -- <li>uid = User ID</li> -- </ul> --- Close the file descriptor. -- @class function -- @name File.close -- @return true --- Get the number of the filedescriptor. -- @class function -- @name File.fileno -- @return file descriptor number --- (POSIX) Set the blocking mode of the file descriptor. -- @class function -- @name File.setblocking -- @param blocking (boolean) -- @return true
apache-2.0
nasomi/darkstar
scripts/globals/items/sleepshroom.lua
35
1191
----------------------------------------- -- ID: 4374 -- Item: sleepshroom -- Food Effect: 5Min, All Races ----------------------------------------- -- Strength -3 -- Mind 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4374); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, -3); target:addMod(MOD_MND, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, -3); target:delMod(MOD_MND, 1); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Selbina/npcs/Porter_Moogle.lua
41
1520
----------------------------------- -- Area: Selbina -- NPC: Porter Moogle -- Type: Storage Moogle -- @zone 248 -- @pos TODO ----------------------------------- package.loaded["scripts/zones/Selbina/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Selbina/TextIDs"); require("scripts/globals/porter_moogle_util"); local e = { TALK_EVENT_ID = 1137, STORE_EVENT_ID = 1138, RETRIEVE_EVENT_ID = 1139, ALREADY_STORED_ID = 1140, MAGIAN_TRIAL_ID = 1141 }; ----------------------------------- -- 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
nasomi/darkstar
scripts/zones/Kazham/npcs/Ronta-Onta.lua
19
4061
----------------------------------- -- Area: Kazham -- NPC: Ronta-Onta -- Starts and Finishes Quest: Trial by Fire -- @pos 100 -15 -97 250 ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) TrialByFire = player:getQuestStatus(OUTLANDS,TRIAL_BY_FIRE); WhisperOfFlames = player:hasKeyItem(WHISPER_OF_FLAMES); realday = tonumber(os.date("%j")); -- %M for next minute, %j for next day if ((TrialByFire == QUEST_AVAILABLE and player:getFameLevel(KAZHAM) >= 6) or (TrialByFire == QUEST_COMPLETED and realday ~= player:getVar("TrialByFire_date"))) then player:startEvent(0x010e,0,TUNING_FORK_OF_FIRE); -- Start and restart quest "Trial by Fire" elseif (TrialByFire == QUEST_ACCEPTED and player:hasKeyItem(TUNING_FORK_OF_FIRE) == false and WhisperOfFlames == false) then player:startEvent(0x011d,0,TUNING_FORK_OF_FIRE); -- Defeat against Ifrit : Need new Fork elseif (TrialByFire == QUEST_ACCEPTED and WhisperOfFlames == false) then player:startEvent(0x010f,0,TUNING_FORK_OF_FIRE,0); elseif (TrialByFire == QUEST_ACCEPTED and WhisperOfFlames) then numitem = 0; if (player:hasItem(17665)) then numitem = numitem + 1; end -- Ifrits Blade if (player:hasItem(13241)) then numitem = numitem + 2; end -- Fire Belt if (player:hasItem(13560)) then numitem = numitem + 4; end -- Fire Ring if (player:hasItem(1203)) then numitem = numitem + 8; end -- Egil's Torch if (player:hasSpell(298)) then numitem = numitem + 32; end -- Ability to summon Ifrit player:startEvent(0x0111,0,TUNING_FORK_OF_FIRE,0,0,numitem); else player:startEvent(0x0112); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x010e and option == 1) then if (player:getQuestStatus(OUTLANDS,TRIAL_BY_FIRE) == QUEST_COMPLETED) then player:delQuest(OUTLANDS,TRIAL_BY_FIRE); end player:addQuest(OUTLANDS,TRIAL_BY_FIRE); player:setVar("TrialByFire_date", 0); player:addKeyItem(TUNING_FORK_OF_FIRE); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_FIRE); elseif (csid == 0x011d) then player:addKeyItem(TUNING_FORK_OF_FIRE); player:messageSpecial(KEYITEM_OBTAINED,TUNING_FORK_OF_FIRE); elseif (csid == 0x0111) then item = 0; if (option == 1) then item = 17665; -- Ifrits Blade elseif (option == 2) then item = 13241; -- Fire Belt elseif (option == 3) then item = 13560; -- Fire Ring elseif (option == 4) then item = 1203; -- Egil's Torch end if (player:getFreeSlotsCount() == 0 and (option ~= 5 or option ~= 6)) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,item); else if (option == 5) then player:addGil(GIL_RATE*10000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*10000); -- Gil elseif (option == 6) then player:addSpell(298); -- Ifrit Spell player:messageSpecial(IFRIT_UNLOCKED,0,0,0); else player:addItem(item); player:messageSpecial(ITEM_OBTAINED,item); -- Item end player:addTitle(HEIR_OF_THE_GREAT_FIRE); player:delKeyItem(WHISPER_OF_FLAMES); player:setVar("TrialByFire_date", os.date("%j")); -- %M for next minute, %j for next day player:addFame(KAZHAM,WIN_FAME*30); player:completeQuest(OUTLANDS,TRIAL_BY_FIRE); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Lufaise_Meadows/npcs/Chilaumme_RK.lua
30
3055
----------------------------------- -- Area: Lufaise Meadows -- NPC: Chilaumme, R.K. -- Border Conquest Guards -- @pos 414.659 0.905 -52.417 24 ----------------------------------- package.loaded["scripts/zones/Lufaise_Meadows/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Lufaise_Meadows/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 4; -- 1: city, 2: foreign, 3: outpost, 4: border local region = TAVNAZIANARCH; local csid = 0x7ffa; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
nicholas-leonard/nn
SpatialAdaptiveMaxPooling.lua
9
1199
local SpatialAdaptiveMaxPooling, parent = torch.class('nn.SpatialAdaptiveMaxPooling', 'nn.Module') function SpatialAdaptiveMaxPooling:__init(W, H) parent.__init(self) self.W = W self.H = H end function SpatialAdaptiveMaxPooling:updateOutput(input) self.indices = self.indices or torch.LongTensor() if torch.typename(input):find('torch%.Cuda.*Tensor') then self.indices = torch.CudaLongTensor and self.indices:cudaLong() or self.indices else self.indices = self.indices:long() end input.THNN.SpatialAdaptiveMaxPooling_updateOutput( input:cdata(), self.output:cdata(), self.indices:cdata(), self.W, self.H ) return self.output end function SpatialAdaptiveMaxPooling:updateGradInput(input, gradOutput) input.THNN.SpatialAdaptiveMaxPooling_updateGradInput( input:cdata(), gradOutput:cdata(), self.gradInput:cdata(), self.indices:cdata() ) return self.gradInput end -- for backward compat function SpatialAdaptiveMaxPooling:empty() self:clearState() end function SpatialAdaptiveMaxPooling:clearState() if self.indices then self.indices:set() end return parent.clearState(self) end
bsd-3-clause
nasomi/darkstar
scripts/zones/Crawlers_Nest/npcs/Treasure_Chest.lua
17
3197
----------------------------------- -- Area: Crawler Nest -- NPC: Treasure Chest -- Involved In Quest: Enveloped in Darkness -- @pos 41 0.1 -314 197 ----------------------------------- package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/zones/Crawlers_Nest/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1040,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if ((trade:hasItemQty(1040,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: AF2 RDM QUEST ----------- if (player:getVar("needs_crawler_blood") == 1) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if (pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if (success ~= -2) then player:tradeComplete(); if (math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if (questItemNeeded == 1) then player:addKeyItem(CRAWLER_BLOOD); player:messageSpecial(KEYITEM_OBTAINED,CRAWLER_BLOOD); -- Crawler Blood (KI) player:setVar("needs_crawler_blood",0); else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if (loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1040); 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/Apollyon/mobs/Grave_Digger.lua
33
1024
----------------------------------- -- Area: Apollyon SE -- NPC: Grave_Digger ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) GetMobByID(16933021):updateEnmity(target); GetMobByID(16933022):updateEnmity(target); GetMobByID(16933023):updateEnmity(target); GetMobByID(16933024):updateEnmity(target); GetMobByID(16933025):updateEnmity(target); GetMobByID(16933026):updateEnmity(target); GetMobByID(16933027):updateEnmity(target); GetMobByID(16933028):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) end;
gpl-3.0
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/applications/luci-asterisk/luasrc/model/cbi/asterisk/trunk_sip.lua
80
2561
--[[ LuCI - Lua Configuration Interface Copyright 2008 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ast = require("luci.asterisk") -- -- SIP trunk info -- if arg[2] == "info" then form = SimpleForm("asterisk", "SIP Trunk Information") form.reset = false form.submit = "Back to overview" local info, keys = ast.sip.peer(arg[1]) local data = { } for _, key in ipairs(keys) do data[#data+1] = { key = key, val = type(info[key]) == "boolean" and ( info[key] and "yes" or "no" ) or ( info[key] == nil or #info[key] == 0 ) and "(none)" or tostring(info[key]) } end itbl = form:section(Table, data, "SIP Trunk %q" % arg[1]) itbl:option(DummyValue, "key", "Key") itbl:option(DummyValue, "val", "Value") function itbl.parse(...) luci.http.redirect( luci.dispatcher.build_url("admin", "asterisk", "trunks") ) end return form -- -- SIP trunk config -- elseif arg[1] then cbimap = Map("asterisk", "Edit SIP Trunk") peer = cbimap:section(NamedSection, arg[1]) peer.hidden = { type = "peer", qualify = "yes", } back = peer:option(DummyValue, "_overview", "Back to trunk overview") back.value = "" back.titleref = luci.dispatcher.build_url("admin", "asterisk", "trunks") sipdomain = peer:option(Value, "host", "SIP Domain") sipport = peer:option(Value, "port", "SIP Port") function sipport.cfgvalue(...) return AbstractValue.cfgvalue(...) or "5060" end username = peer:option(Value, "username", "Authorization ID") password = peer:option(Value, "secret", "Authorization Password") password.password = true outboundproxy = peer:option(Value, "outboundproxy", "Outbound Proxy") outboundport = peer:option(Value, "outboundproxyport", "Outbound Proxy Port") register = peer:option(Flag, "register", "Register with peer") register.enabled = "yes" register.disabled = "no" regext = peer:option(Value, "registerextension", "Extension to register (optional)") regext:depends({register="1"}) didval = peer:option(ListValue, "_did", "Number of assigned DID numbers") didval:value("", "(none)") for i=1,24 do didval:value(i) end dialplan = peer:option(ListValue, "context", "Dialplan Context") dialplan:value(arg[1] .. "_inbound", "(default)") cbimap.uci:foreach("asterisk", "dialplan", function(s) dialplan:value(s['.name']) end) return cbimap end
gpl-2.0
cristiandonosoc/unexperiments
dotaoh/main.lua
1
1796
-- WE IMPORT THE HELPER LIBRARIES Vector = require "lib.hump.vector" Camera = require "lib.hump.camera" Timer = require "lib.hump.timer" Class = require "lib.hump.class" Gamestate = require "lib.hump.gamestate" Shapes = require "lib.hardon_collider.shapes" ATL = {} ATL.Loader = require "lib.advanced_tile_loader.Loader" ATL.Loader.path = "maps/" Grid = require "lib.advanced_tile_loader.Grid" require "lib.require.require" require "lib.vardump" Anim8 = require "lib.anim8" require "lib.Beetle" -- EXTENSIONS require "lib.custom.Grid" -- GENERAL INPUT require "input" -- CUSTOM CLASSES Gamegrid = require "lib.custom.Gamegrid" require.tree "classes" -- HELPERS require "lib.custom.helper" _sprites = {} _spriteSheets = {} _states = {} local function loadSprites() -- SPRITES _sprites.field = love.graphics.newImage("images/field.jpg") _sprites.warrior = love.graphics.newImage("images/warrior.png") _sprites.yellow_circle = love.graphics.newImage("images/yellow_circle.png") -- SPRITESHEETS local ibh = love.graphics.newImage("images/spritesheets/ice_blaster_hit.png") _spriteSheets.ice_blast = { image = ibh, grid = Anim8.newGrid(200, 200, ibh:getWidth(), ibh:getHeight()) } end local function loadStates() _states.main = require("states/mainState") end function love.load() loadStates() loadSprites() beetle.load() beetle.add("player", _northId) beetle.setKey("m") _camera = Camera(100,400,1.3,0) Gamestate.registerEvents() Gamestate.switch(_states.main) _gameEngine = GameEngine() _gameEngine.current_player = _northId _gameEngine:testMinions() _gameEngine:gameFunction("print") end function love.update(dt) Timer.update(dt) Gamestate.updateInput(dt) _gameEngine:update(dt) end function love.draw() beetle.draw() end
mit
appaquet/torch-android
src/pkg/torch/torchcwrap.lua
54
15111
local wrap = require 'cwrap' local types = wrap.types types.Tensor = { helpname = function(arg) if arg.dim then return string.format("Tensor~%dD", arg.dim) else return "Tensor" end end, declare = function(arg) local txt = {} table.insert(txt, string.format("THTensor *arg%d = NULL;", arg.i)) if arg.returned then table.insert(txt, string.format("int arg%d_idx = 0;", arg.i)); end return table.concat(txt, '\n') end, check = function(arg, idx) if arg.dim then return string.format("(arg%d = luaT_toudata(L, %d, torch_Tensor)) && (arg%d->nDimension == %d)", arg.i, idx, arg.i, arg.dim) else return string.format("(arg%d = luaT_toudata(L, %d, torch_Tensor))", arg.i, idx) end end, read = function(arg, idx) if arg.returned then return string.format("arg%d_idx = %d;", arg.i, idx) end end, init = function(arg) if type(arg.default) == 'boolean' then return string.format('arg%d = THTensor_(new)();', arg.i) elseif type(arg.default) == 'number' then return string.format('arg%d = %s;', arg.i, arg.args[arg.default]:carg()) else error('unknown default tensor type value') end end, carg = function(arg) return string.format('arg%d', arg.i) end, creturn = function(arg) return string.format('arg%d', arg.i) end, precall = function(arg) local txt = {} if arg.default and arg.returned then table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) table.insert(txt, string.format('else')) if type(arg.default) == 'boolean' then -- boolean: we did a new() table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i)) else -- otherwise: point on default tensor --> retain table.insert(txt, string.format('{')) table.insert(txt, string.format('THTensor_(retain)(arg%d);', arg.i)) -- so we need a retain table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i)) table.insert(txt, string.format('}')) end elseif arg.default then -- we would have to deallocate the beast later if we did a new -- unlikely anyways, so i do not support it for now if type(arg.default) == 'boolean' then error('a tensor cannot be optional if not returned') end elseif arg.returned then table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) end return table.concat(txt, '\n') end, postcall = function(arg) local txt = {} if arg.creturned then -- this next line is actually debatable table.insert(txt, string.format('THTensor_(retain)(arg%d);', arg.i)) table.insert(txt, string.format('luaT_pushudata(L, arg%d, torch_Tensor);', arg.i)) end return table.concat(txt, '\n') end } types.Generator = { helpname = function(arg) return "Generator" end, declare = function(arg) return string.format("THGenerator *arg%d = NULL;", arg.i) end, check = function(arg, idx) return string.format("(arg%d = luaT_toudata(L, %d, torch_Generator))", arg.i, idx) end, read = function(arg, idx) end, init = function(arg) local text = {} -- If no generator is supplied, pull the default out of the torch namespace. table.insert(text, 'lua_getglobal(L,"torch");') table.insert(text, string.format('arg%d = luaT_getfieldcheckudata(L, -1, "_gen", torch_Generator);', arg.i)) table.insert(text, 'lua_pop(L, 2);') return table.concat(text, '\n') end, carg = function(arg) return string.format('arg%d', arg.i) end, creturn = function(arg) return string.format('arg%d', arg.i) end, precall = function(arg) end, postcall = function(arg) end } types.IndexTensor = { helpname = function(arg) return "LongTensor" end, declare = function(arg) local txt = {} table.insert(txt, string.format("THLongTensor *arg%d = NULL;", arg.i)) if arg.returned then table.insert(txt, string.format("int arg%d_idx = 0;", arg.i)); end return table.concat(txt, '\n') end, check = function(arg, idx) return string.format('(arg%d = luaT_toudata(L, %d, "torch.LongTensor"))', arg.i, idx) end, read = function(arg, idx) local txt = {} if not arg.noreadadd then table.insert(txt, string.format("THLongTensor_add(arg%d, arg%d, -1);", arg.i, arg.i)); end if arg.returned then table.insert(txt, string.format("arg%d_idx = %d;", arg.i, idx)) end return table.concat(txt, '\n') end, init = function(arg) return string.format('arg%d = THLongTensor_new();', arg.i) end, carg = function(arg) return string.format('arg%d', arg.i) end, creturn = function(arg) return string.format('arg%d', arg.i) end, precall = function(arg) local txt = {} if arg.default and arg.returned then table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) table.insert(txt, string.format('else')) -- means we did a new() table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongTensor");', arg.i)) elseif arg.default then error('a tensor cannot be optional if not returned') elseif arg.returned then table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) end return table.concat(txt, '\n') end, postcall = function(arg) local txt = {} if arg.creturned or arg.returned then table.insert(txt, string.format("THLongTensor_add(arg%d, arg%d, 1);", arg.i, arg.i)); end if arg.creturned then -- this next line is actually debatable table.insert(txt, string.format('THLongTensor_retain(arg%d);', arg.i)) table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongTensor");', arg.i)) end return table.concat(txt, '\n') end } for _,typename in ipairs({"ByteTensor", "CharTensor", "ShortTensor", "IntTensor", "LongTensor", "FloatTensor", "DoubleTensor"}) do types[typename] = { helpname = function(arg) if arg.dim then return string.format('%s~%dD', typename, arg.dim) else return typename end end, declare = function(arg) local txt = {} table.insert(txt, string.format("TH%s *arg%d = NULL;", typename, arg.i)) if arg.returned then table.insert(txt, string.format("int arg%d_idx = 0;", arg.i)); end return table.concat(txt, '\n') end, check = function(arg, idx) if arg.dim then return string.format('(arg%d = luaT_toudata(L, %d, "torch.%s")) && (arg%d->nDimension == %d)', arg.i, idx, typename, arg.i, arg.dim) else return string.format('(arg%d = luaT_toudata(L, %d, "torch.%s"))', arg.i, idx, typename) end end, read = function(arg, idx) if arg.returned then return string.format("arg%d_idx = %d;", arg.i, idx) end end, init = function(arg) if type(arg.default) == 'boolean' then return string.format('arg%d = TH%s_new();', arg.i, typename) elseif type(arg.default) == 'number' then return string.format('arg%d = %s;', arg.i, arg.args[arg.default]:carg()) else error('unknown default tensor type value') end end, carg = function(arg) return string.format('arg%d', arg.i) end, creturn = function(arg) return string.format('arg%d', arg.i) end, precall = function(arg) local txt = {} if arg.default and arg.returned then table.insert(txt, string.format('if(arg%d_idx)', arg.i)) -- means it was passed as arg table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) table.insert(txt, string.format('else')) if type(arg.default) == 'boolean' then -- boolean: we did a new() table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename)) else -- otherwise: point on default tensor --> retain table.insert(txt, string.format('{')) table.insert(txt, string.format('TH%s_retain(arg%d);', typename, arg.i)) -- so we need a retain table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename)) table.insert(txt, string.format('}')) end elseif arg.default then -- we would have to deallocate the beast later if we did a new -- unlikely anyways, so i do not support it for now if type(arg.default) == 'boolean' then error('a tensor cannot be optional if not returned') end elseif arg.returned then table.insert(txt, string.format('lua_pushvalue(L, arg%d_idx);', arg.i)) end return table.concat(txt, '\n') end, postcall = function(arg) local txt = {} if arg.creturned then -- this next line is actually debatable table.insert(txt, string.format('TH%s_retain(arg%d);', typename, arg.i)) table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.%s");', arg.i, typename)) end return table.concat(txt, '\n') end } end types.LongArg = { vararg = true, helpname = function(arg) return "(LongStorage | dim1 [dim2...])" end, declare = function(arg) return string.format("THLongStorage *arg%d = NULL;", arg.i) end, init = function(arg) if arg.default then error('LongArg cannot have a default value') end end, check = function(arg, idx) return string.format("torch_islongargs(L, %d)", idx) end, read = function(arg, idx) return string.format("arg%d = torch_checklongargs(L, %d);", arg.i, idx) end, carg = function(arg, idx) return string.format('arg%d', arg.i) end, creturn = function(arg, idx) return string.format('arg%d', arg.i) end, precall = function(arg) local txt = {} if arg.returned then table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongStorage");', arg.i)) end return table.concat(txt, '\n') end, postcall = function(arg) local txt = {} if arg.creturned then -- this next line is actually debatable table.insert(txt, string.format('THLongStorage_retain(arg%d);', arg.i)) table.insert(txt, string.format('luaT_pushudata(L, arg%d, "torch.LongStorage");', arg.i)) end if not arg.returned and not arg.creturned then table.insert(txt, string.format('THLongStorage_free(arg%d);', arg.i)) end return table.concat(txt, '\n') end } types.charoption = { helpname = function(arg) if arg.values then return "(" .. table.concat(arg.values, '|') .. ")" end end, declare = function(arg) local txt = {} table.insert(txt, string.format("const char *arg%d = NULL;", arg.i)) if arg.default then table.insert(txt, string.format("char arg%d_default = '%s';", arg.i, arg.default)) end return table.concat(txt, '\n') end, init = function(arg) return string.format("arg%d = &arg%d_default;", arg.i, arg.i) end, check = function(arg, idx) local txt = {} local txtv = {} table.insert(txt, string.format('(arg%d = lua_tostring(L, %d)) && (', arg.i, idx)) for _,value in ipairs(arg.values) do table.insert(txtv, string.format("*arg%d == '%s'", arg.i, value)) end table.insert(txt, table.concat(txtv, ' || ')) table.insert(txt, ')') return table.concat(txt, '') end, read = function(arg, idx) end, carg = function(arg, idx) return string.format('arg%d', arg.i) end, creturn = function(arg, idx) end, precall = function(arg) end, postcall = function(arg) end }
bsd-3-clause
MatthewDwyer/botman
mudlet/profiles/newbot/scripts/startup_bot.lua
1
10022
--[[ 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 --]] debugger = require "debug" mysql = require "luasql.mysql" local debug if not telnetLogFileName then telnetLogFileName = homedir .. "/telnet_logs/" .. os.date("%Y-%m-%d#%H-%M") .. ".txt" telnetLogFile = io.open(telnetLogFileName, "a") end function dbugi(text) -- send text to the special debug irc channel if server ~= nil then irc_chat(server.ircMain .. "_debug", text) end end function dbug(text) -- send text to the debug window we created in Mudlet. if type(server) ~= "table" then display(text .. "\n") return end if not server.enableWindowMessages then server.enableWindowMessages = true end if server.windowLists then windowMessage(server.windowLists, text .. "\n") end end function checkData() if botman.botDisabled or botman.botOffline then return end if server.botName == nil then loadServer() botman.botStarted = nil login() end sendCommand("version") sendCommand("gt") if server.botman then if server.uptime == 0 then sendCommand("bm-uptime") end sendCommand("bm-resetregions list") --sendCommand("bm-change botname [" .. server.botNameColour .. "]" .. server.botName) sendCommand("bm-anticheat report") end if tablelength(shopCategories) == 0 then loadShopCategories() end if tonumber(server.ServerPort) == 0 then sendCommand("gg") else addOrRemoveSlots() end if tablelength(owners) == 0 then sendCommand("admin list") end end function getServerData(getAllPlayers) if botman.botDisabled or botman.botOffline then return end if getAllPlayers then reloadBot(getAllPlayers) else reloadBot() end end function login() local getAllPlayers = false local randomChannel, r debug = false debugdb = false startLogging(false) if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end -- disable some stuff we no longer use disableTrigger("le") disableTimer("GimmeReset") if type(botman) ~= "table" then botman = {} botman.botOffline = true botman.APIOffline = true botman.telnetOffline = true botman.playersOnline = 0 botman.botConnectedTimestamp = os.time() botman.botOfflineCount = 0 botman.telnetOfflineCount = 0 botman.lastServerResponseTimestamp = os.time() botman.lastTelnetResponseTimestamp = os.time() botman.serverRebooting = false botman.scheduledRestartPaused = false botman.scheduledRestartForced = false botman.scheduledRestart = false botman.scheduledRestartTimestamp = os.time() botman.lastBlockCommandOwner = 0 botman.initReservedSlots = true botman.webdavFolderWriteable = true end tempTimer( 40, [[checkData()]] ) if type(server) ~= "table" then server = {} getAllPlayers = true -- force the irc server to localhost so that we don't automatically join Freenode and the Mudlet channel if nothing else has been set. -- set some random irc channel name so that the bot should not join an existing channel with another bot in it if localhost has an irc server. math.randomseed(os.time()) r = math.random(900) + 100 randomChannel = "bot_" .. r server.ircServer = "127.0.0.1" server.ircMain = randomChannel server.ircAlerts = randomChannel .. "_alerts" server.ircWatch = randomChannel .. "_watch" server.ircPort = 6667 end if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end botman.userHome = string.sub(homedir, 1, string.find(homedir, ".config") - 2) if botman.sysExitID == nil then botman.sysExitID = registerAnonymousEventHandler("sysExitEvent", "onSysExit") botman.sysExitID = 0 end if botman.sysIrcStatusMessageID == nil then botman.sysIrcStatusMessageID = registerAnonymousEventHandler("sysIrcStatusMessage", "ircStatusMessage") botman.sysIrcStatusMessageID = 0 end if botman.sysDisconnectionID == nil then botman.sysDisconnectionID = registerAnonymousEventHandler("sysDisconnectionEvent", "onSysDisconnection") botman.sysDisconnectionID = 0 end if botman.sysDownloadDoneID == nil then botman.sysDownloadDoneID = registerAnonymousEventHandler("sysDownloadDone", "downloadHandler") botman.sysDownloadDoneID = 0 end if botman.sysDownloadErrorID == nil then botman.sysDownloadErrorID = registerAnonymousEventHandler("sysDownloadError", "failDownload") botman.sysDownloadErrorID = 0 end if botman.sysExitEventID == nil then botman.sysExitEventID = registerAnonymousEventHandler("sysExitEvent", "onCloseMudlet") botman.sysExitEventID = 0 end if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end if (botman.botStarted == nil) then botman.botStarted = os.time() telnetLogFileName = homedir .. "/telnet_logs/" .. os.date("%Y-%m-%d#%H-%M-%S", os.time()) .. ".txt" telnetLogFile = io.open(telnetLogFileName, "a") if reloadBotScripts == nil then dofile(homedir .. "/scripts/reload_bot_scripts.lua") reloadBotScripts(false, false, false) end if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end -- this must come after reload_bot_scripts above. fixTables() if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end initBot() -- this lives in edit_me.lua if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end openDB() -- this lives in edit_me.lua if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end openBotsDB() -- this lives in edit_me.lua if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end initDB() -- this lives in mysql.lua if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end botman.dbConnected = isDBConnected() botman.botsConnected = isDBBotsConnected() botman.initError = true botman.serverTime = "" botman.feralWarning = false botman.playersOnline = 0 loadServer(true) botman.ignoreAdmins = true if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end if server.botID == nil then server.botID = 0 end if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end botman.webdavFolderExists = true if botman.chatlogPath == nil then botman.chatlogPath = webdavFolder if botman.dbConnected then conn:execute("UPDATE server SET chatlogPath = '" .. escape(webdavFolder) .. "'") end end if not isDir(botman.chatlogPath) then botman.webdavFolderExists = false end openUserWindow(server.windowGMSG) openUserWindow(server.windowDebug) openUserWindow(server.windowLists) if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end if closeMudlet ~= nil or addCustomLine ~= nil then botman.customMudlet = true end if loadWindowLayout ~= nil then loadWindowLayout() end if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end -- add your steam id here so you can debug using your name Smegz0r = "76561197983251951" if (botman.ExceptionCount == nil) then botman.ExceptionCount = 0 end botman.announceBot = true botman.alertMods = true botman.faultyGimme = false botman.faultyGimmeNumber = 0 botman.faultyChat = false botman.gimmeHell = 0 botman.scheduledRestartPaused = false botman.scheduledRestart = false botman.ExceptionRebooted = false server.scanZombies = false server.lagged = false if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end checkForMissingTables() fixMissingStuff() if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end -- load tables loadTables() if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end -- set all players to offline in shared db cleanupBotsData() if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end botman.nextRebootTest = nil botman.initError = false getServerData(getAllPlayers) if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end -- Flag all players as offline if tonumber(server.botID) > 0 then if botman.botsConnected then connBots:execute("UPDATE players set online = 0 WHERE botID = " .. server.botID) end end if not server.telnetDisabled then if not server.readLogUsingTelnet then if botman.dbConnected then conn:execute("UPDATE server set readLogUsingTelnet = 1") end end server.readLogUsingTelnet = true end if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end end if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end if not isFile(homedir .. "/botman.ini") then --storeBotmanINI() end -- load the server API key if it exists readAPI() if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end -- join the irc server if botman.customMudlet then joinIRCServer() end if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end if server.botman then sendCommand("bm-readconfig") end if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end if custom_startup ~= nil then custom_startup() end if (debug) then display("debug login line " .. debugger.getinfo(1).currentline .. "\n") end -- special case where the bot will use telnet to monitor the server regardless of other API settings if server.readLogUsingTelnet then toggleTriggers("api offline") end if debug then display("debug login end\n") end end
gpl-3.0
nasomi/darkstar
scripts/zones/Southern_San_dOria_[S]/npcs/Wyatt.lua
17
1982
----------------------------------- -- Area: Southern SandOria [S] -- NPC: Wyatt -- @zone 80 -- @pos 124 0 84 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Southern_San_dOria_[S]/TextIDs"); require("scripts/globals/titles"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (trade:getItemCount() == 4 and trade:hasItemQty(2506,4)) then player:startEvent(0x0004); end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local seeingSpots = player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS); if (seeingSpots == QUEST_AVAILABLE) then player:startEvent(0x0002); elseif (seeingSpots == QUEST_ACCEPTED) then player:startEvent(0x0003); else player:showText(npc, WYATT_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0002) then player:addQuest(CRYSTAL_WAR,SEEING_SPOTS); elseif (csid == 0x0004) then player:tradeComplete(); if (player:getQuestStatus(CRYSTAL_WAR,SEEING_SPOTS) == QUEST_ACCEPTED) then player:addTitle(LADY_KILLER); player:addGil(GIL_RATE*3000); player:messageSpecial(GIL_OBTAINED,GIL_RATE*3000); player:completeQuest(CRYSTAL_WAR,SEEING_SPOTS); else player:addTitle(LADY_KILLER); player:addGil(GIL_RATE*1500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*1500); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Lower_Jeuno/npcs/Gurdern.lua
34
1374
----------------------------------- -- Area: Lower Jeuno -- NPC: Gurdern -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Lower_Jeuno/TextIDs"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,14) == false) then player:startEvent(10052); else player:startEvent(0x0070); 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 == 10052) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",14,true); end end;
gpl-3.0
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/modules/admin-full/luasrc/model/cbi/admin_system/fstab/swap.lua
84
1922
--[[ LuCI - Lua Configuration Interface Copyright 2010 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local util = require "nixio.util" local devices = {} util.consume((fs.glob("/dev/sd*")), devices) util.consume((fs.glob("/dev/hd*")), devices) util.consume((fs.glob("/dev/scd*")), devices) util.consume((fs.glob("/dev/mmc*")), devices) local size = {} for i, dev in ipairs(devices) do local s = tonumber((fs.readfile("/sys/class/block/%s/size" % dev:sub(6)))) size[dev] = s and math.floor(s / 2048) end m = Map("fstab", translate("Mount Points - Swap Entry")) m.redirect = luci.dispatcher.build_url("admin/system/fstab") if not arg[1] or m.uci:get("fstab", arg[1]) ~= "swap" then luci.http.redirect(m.redirect) return end mount = m:section(NamedSection, arg[1], "swap", translate("Swap Entry")) mount.anonymous = true mount.addremove = false mount:tab("general", translate("General Settings")) mount:tab("advanced", translate("Advanced Settings")) mount:taboption("general", Flag, "enabled", translate("Enable this swap")).rmempty = false o = mount:taboption("general", Value, "device", translate("Device"), translate("The device file of the memory or partition (<abbr title=\"for example\">e.g.</abbr> <code>/dev/sda1</code>)")) for i, d in ipairs(devices) do o:value(d, size[d] and "%s (%s MB)" % {d, size[d]}) end o = mount:taboption("advanced", Value, "uuid", translate("UUID"), translate("If specified, mount the device by its UUID instead of a fixed device node")) o = mount:taboption("advanced", Value, "label", translate("Label"), translate("If specified, mount the device by the partition label instead of a fixed device node")) return m
gpl-2.0
nasomi/darkstar
scripts/globals/items/plate_of_tuna_sushi.lua
35
1526
----------------------------------------- -- ID: 5150 -- Item: plate_of_tuna_sushi -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 20 -- Dexterity 3 -- Charisma 5 -- Accuracy % 15 -- Ranged ACC % 15 -- Sleep Resist 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5150); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_DEX, 3); target:addMod(MOD_CHR, 5); target:addMod(MOD_ACCP, 15); target:addMod(MOD_RACCP, 15); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_DEX, 3); target:delMod(MOD_CHR, 5); target:delMod(MOD_ACCP, 15); target:delMod(MOD_RACCP, 15); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
nikolauska/NCP
Info.lua
1
1235
-- Info.lua -- Implements the g_PluginInfo standard plugin description g_PluginInfo = { Name = "NCP", Version = "0.1", Description = [[Nikolauska Command Pack]], Commands = { ["/delhome"] = { Permission = "es.home", HelpString = "Delete a home.", Handler = HandleDeleteHomeCommand, ParameterCombinations = { { Params = "HomeName", Help = "Deletes specifies home", } } }, ["/home"] = { Permission = "es.home", HelpString = "Teleport to your home.", Handler = HandleHomeCommand, ParameterCombinations = { { Params = "HomeName", Help = "teleports you to the specified home", } } }, ["/sethome"] = { Permission = "es.home", HelpString = "Set your home.", Handler = HandleSetHomeCommand, ParameterCombinations = { { Params = "HomeName", Help = "teleports you to the specified home", } } }, }, Permissions = { ["es.home"] = { Description = "Allows players to use basic home commands.", RecommendedGroups = "mods, players", }, ["es.home.admin"] = { Description = "Allows admin mre advanced home commands.", RecommendedGroups = "admins", } } }
mit
luanorlandi/SwiftSpaceBattle
src/interface/game/gameInterface.lua
2
2345
require "interface/game/gameText" require "interface/game/lives" require "interface/game/borderHp" require "interface/game/scoreText" require "interface/game/gameOver" require "interface/game/buttons" GameInterface = {} GameInterface.__index = GameInterface function GameInterface:new(lives) local G = {} setmetatable(G, GameInterface) G.textSize = math.floor(40 * window.scale) G.font = MOAIFont.new() G.font:loadFromTTF("font//NotoSans-Regular.ttf", G.textSize, 72) G.threads = {} G.borderHp = BorderHp:new() table.insert(G.threads, G.borderHp.thread) G.lives = Lives:new(lives) -- configure score to be in the top right corner G.score = Score:new(0, Vector:new(0, 0), G.font) G.score.scoreText.text:setRect(-window.width/2, -window.height/2, window.width/2 - 0.1 * window.width/2, window.height/2 - 0.1 * window.width/2) G.score.scoreText.text:setAlignment(MOAITextBox.RIGHT_JUSTIFY, MOAITextBox.LEFT_JUSTIFY) G.combo = Score:new("x1", Vector:new(0, 0), G.font) G.combo.scoreText.text:setVisible(false) G.combo.scoreText.text:setRect(-window.width/2, -window.height/2, window.width/2 - 0.1 * window.width/2, window.height/2 - 0.25 * window.width/2) G.combo.scoreText.text:setAlignment(MOAITextBox.RIGHT_JUSTIFY, MOAITextBox.LEFT_JUSTIFY) G.scoreEarnedPos = Vector:new(window.width/2 - 0.55 * window.width/2, window.height/2 - 0.30 * window.width/2) G.scoreAnimTable = {} G.buttons = Buttons:new() G.buttons:showButtons() G.gameOver = nil return G end function GameInterface:scoreAnim(score, pos) scoreAnimThread = coroutine.create(function() showScoreAnim(score, pos, self.font) end) coroutine.resume(scoreAnimThread) table.insert(self.threads, scoreAnimThread) end function GameInterface:scoreEarnedAnim(score) scoreAnimThread = coroutine.create(function() showScoreEarnedAnim(score, self.font) end) coroutine.resume(scoreAnimThread) table.insert(self.threads, scoreAnimThread) end function GameInterface:showGameOver(score) self.gameOver = GameOver:new(score, self.font) end function GameInterface:clear() self.borderHp:clear() self.lives:clear() self.score:clear() self.combo:clear() self.buttons:clear() if self.gameOver ~= nil then self.gameOver:clear() end for i = 1, #self.scoreAnimTable, 1 do self.scoreAnimTable[i]:clear() end end
gpl-3.0
kenyh0926/DBProxy
examples/tutorial-tokenize.lua
4
1591
--[[ $%BEGINLICENSE%$ Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved. This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; version 2 of the License. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; if not, write to the Free Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA $%ENDLICENSE%$ --]] --[[ --]] local tokenizer = require("proxy.tokenizer") function read_query(packet) if packet:byte() == proxy.COM_QUERY then local tokens = tokenizer.tokenize(packet:sub(2)) -- just for debug for i = 1, #tokens do -- print the token and what we know about it local token = tokens[i] local txt = token["text"] if token["token_name"] == 'TK_STRING' then txt = string.format("%q", txt) end -- print(i .. ": " .. " { " .. token["token_name"] .. ", " .. token["text"] .. " }" ) print(i .. ": " .. " { " .. token["token_name"] .. ", " .. txt .. " }" ) end print("normalized query: " .. tokenizer.normalize(tokens)) print("") end end
gpl-2.0
jungomi/dotfiles
.config/nvim/lua/autocommands.lua
1
4160
-- lightbulb might not be installed yet, so make sure it doesn't fail local _, lightbulb = pcall(require, "nvim-lightbulb") local _, osc52 = pcall(require, "osc52") local autocmd_utils = require("utils.autocmd") local file_utils = require("utils.file") autocmd_utils.create_augroups({ config_filetype = { -- Disable comment continuation when using 'o' or 'O' { event = "FileType", pattern = "*", command = "setlocal formatoptions-=o", desc = "Disable comment continuation when using `o` or `O`", }, -- Activate spell checking for relevant files { event = "FileType", pattern = { "gitcommit", "markdown", "tex", "text" }, command = "setlocal spell", desc = "Enable spell check for relevant files", }, -- Prevent some unwanted indenting like if the previous line ended with a comma { event = "FileType", pattern = { "gitcommit", "markdown", "tex", "text", "csv" }, command = "setlocal nocindent", desc = "Prevent unwanted identing in certain files", }, -- Disable colour column in quickfix window { event = "FileType", pattern = "qf", command = "setlocal colorcolumn=", desc = "Disable colour column in quickfix", }, -- Tab settings { event = "FileType", pattern = "python", command = "setlocal shiftwidth=4 textwidth=88 softtabstop=4 expandtab", desc = "Tab settings for Python", }, { event = "FileType", pattern = "make", command = "setlocal tabstop=8 shiftwidth=8 softtabstop=8 noexpandtab", desc = "Tab settings for Makefile", }, { event = "FileType", pattern = "csv", command = "setlocal noexpandtab", desc = "Tab for CSV", }, -- Trigger completion with Tab in DAP REPL (to make it feel like a REPL) { event = "FileType", pattern = "dap-repl", command = "inoremap <buffer> <Tab> <C-x><C-o>", desc = "DAP REPL - Trigger completion with Tab", }, }, config_buffer = { -- Resize panes when the window is resized { event = "VimResized", pattern = "*", command = "wincmd =", desc = "Resize windows when Vim is resized", }, -- Highlight text that has been copied { event = "TextYankPost", pattern = "*", callback = function() vim.highlight.on_yank({ higroup = "Yank", timeout = 250 }) end, desc = "Highlight yanked text", }, -- Copy with OSCYank when using clipboard register { event = "TextYankPost", pattern = "*", callback = function() local event = vim.v.event if event and event.operator == "y" and event.regname == "+" then osc52.copy_register("+") end end, desc = "Copy to clipboard with OSCYank when using clipboard register", }, -- Clear highlighted references when moving the cursor { event = "CursorMoved", pattern = "*", callback = vim.lsp.buf.clear_references, desc = "Clear highlighted LSP references when cursor is moved", }, -- Close location list when the associated buffer is closed { event = "QuitPre", pattern = "*", command = "if empty(&buftype) | lclose | endif", desc = "Close location list when associated buffer is closed", }, { event = "BufWritePre", pattern = "*", callback = file_utils.mkdir_on_save, desc = "Ensure directories exist when saving a file", }, -- Refresh colours after any text change, it should do that on its own -- but after non-insert mode edits, such as undo, it doesn't. { event = "TextChanged", pattern = "*", command = "ColorizerAttachToBuffer", desc = "Refresh (CSS) colours when text changes", }, -- Update lightbulb sign { event = "CursorHold", pattern = "*", -- No-op if lightbulb has not been installed yet callback = lightbulb and lightbulb.update_lightbulb or function() end, desc = "Show a lightbulb sign if a code action is available for the current line", }, }, })
mit
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/applications/luci-olsr/luasrc/model/cbi/olsr/olsrdplugins.lua
54
7297
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ip = require "luci.ip" local fs = require "nixio.fs" if arg[1] then mp = Map("olsrd", translate("OLSR - Plugins")) p = mp:section(TypedSection, "LoadPlugin", translate("Plugin configuration")) p:depends("library", arg[1]) p.anonymous = true ign = p:option(Flag, "ignore", translate("Enable")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end lib = p:option(DummyValue, "library", translate("Library")) lib.default = arg[1] local function Range(x,y) local t = {} for i = x, y do t[#t+1] = i end return t end local function Cidr2IpMask(val) if val then for i = 1, #val do local cidr = ip.IPv4(val[i]) or ip.IPv6(val[i]) if cidr then val[i] = cidr:network():string() .. " " .. cidr:mask():string() end end return val end end local function IpMask2Cidr(val) if val then for i = 1, #val do local ip, mask = val[i]:gmatch("([^%s]+)%s+([^%s]+)")() local cidr if ip and mask and ip:match(":") then cidr = ip.IPv6(ip, mask) elseif ip and mask then cidr = ip.IPv4(ip, mask) end if cidr then val[i] = cidr:string() end end return val end end local knownPlParams = { ["olsrd_bmf.so.1.5.3"] = { { Value, "BmfInterface", "bmf0" }, { Value, "BmfInterfaceIp", "10.10.10.234/24" }, { Flag, "DoLocalBroadcast", "no" }, { Flag, "CapturePacketsOnOlsrInterfaces", "yes" }, { ListValue, "BmfMechanism", { "UnicastPromiscuous", "Broadcast" } }, { Value, "BroadcastRetransmitCount", "2" }, { Value, "FanOutLimit", "4" }, { DynamicList, "NonOlsrIf", "br-lan" } }, ["olsrd_dyn_gw.so.0.4"] = { { Value, "Interval", "40" }, { DynamicList, "Ping", "141.1.1.1" }, { DynamicList, "HNA", "192.168.80.0/24", IpMask2Cidr, Cidr2IpMask } }, ["olsrd_httpinfo.so.0.1"] = { { Value, "port", "80" }, { DynamicList, "Host", "163.24.87.3" }, { DynamicList, "Net", "0.0.0.0/0", Cidr2IpMask } }, ["olsrd_nameservice.so.0.3"] = { { DynamicList, "name", "my-name.mesh" }, { DynamicList, "hosts", "1.2.3.4 name-for-other-interface.mesh" }, { Value, "suffix", ".olsr" }, { Value, "hosts_file", "/path/to/hosts_file" }, { Value, "add_hosts", "/path/to/file" }, { Value, "dns_server", "141.1.1.1" }, { Value, "resolv_file", "/path/to/resolv.conf" }, { Value, "interval", "120" }, { Value, "timeout", "240" }, { Value, "lat", "12.123" }, { Value, "lon", "12.123" }, { Value, "latlon_file", "/var/run/latlon.js" }, { Value, "latlon_infile", "/var/run/gps.txt" }, { Value, "sighup_pid_file", "/var/run/dnsmasq.pid" }, { Value, "name_change_script", "/usr/local/bin/announce_new_hosts.sh" }, { DynamicList, "service", "http://me.olsr:80|tcp|my little homepage" }, { Value, "services_file", "/var/run/services_olsr" }, { Value, "services_change_script", "/usr/local/bin/announce_new_services.sh" }, { DynamicList, "mac", "xx:xx:xx:xx:xx:xx[,0-255]" }, { Value, "macs_file", "/path/to/macs_file" }, { Value, "macs_change_script", "/path/to/script" } }, ["olsrd_quagga.so.0.2.2"] = { { StaticList, "redistribute", { "system", "kernel", "connect", "static", "rip", "ripng", "ospf", "ospf6", "isis", "bgp", "hsls" } }, { ListValue, "ExportRoutes", { "only", "both" } }, { Flag, "LocalPref", "true" }, { Value, "Distance", Range(0,255) } }, ["olsrd_secure.so.0.5"] = { { Value, "Keyfile", "/etc/private-olsr.key" } }, ["olsrd_txtinfo.so.0.1"] = { { Value, "accept", "127.0.0.1" } }, ["olsrd_jsoninfo.so.0.0"] = { { Value, "accept", "127.0.0.1" }, { Value, "port", "9090" }, { Value, "UUIDFile", "/etc/olsrd/olsrd.uuid" }, }, ["olsrd_watchdog.so.0.1"] = { { Value, "file", "/var/run/olsrd.watchdog" }, { Value, "interval", "30" } }, ["olsrd_mdns.so.1.0.0"] = { { DynamicList, "NonOlsrIf", "lan" } }, ["olsrd_p2pd.so.0.1.0"] = { { DynamicList, "NonOlsrIf", "lan" }, { Value, "P2pdTtl", "10" } }, ["olsrd_arprefresh.so.0.1"] = {}, ["olsrd_dot_draw.so.0.3"] = {}, ["olsrd_dyn_gw_plain.so.0.4"] = {}, ["olsrd_pgraph.so.1.1"] = {}, ["olsrd_tas.so.0.1"] = {} } -- build plugin options with dependencies if knownPlParams[arg[1]] then for _, option in ipairs(knownPlParams[arg[1]]) do local otype, name, default, uci2cbi, cbi2uci = unpack(option) local values if type(default) == "table" then values = default default = default[1] end if otype == Flag then local bool = p:option( Flag, name, name ) if default == "yes" or default == "no" then bool.enabled = "yes" bool.disabled = "no" elseif default == "on" or default == "off" then bool.enabled = "on" bool.disabled = "off" elseif default == "1" or default == "0" then bool.enabled = "1" bool.disabled = "0" else bool.enabled = "true" bool.disabled = "false" end bool.optional = true bool.default = default bool:depends({ library = plugin }) else local field = p:option( otype, name, name ) if values then for _, value in ipairs(values) do field:value( value ) end end if type(uci2cbi) == "function" then function field.cfgvalue(self, section) return uci2cbi(otype.cfgvalue(self, section)) end end if type(cbi2uci) == "function" then function field.formvalue(self, section) return cbi2uci(otype.formvalue(self, section)) end end field.optional = true field.default = default --field:depends({ library = arg[1] }) end end end return mp else mpi = Map("olsrd", translate("OLSR - Plugins")) local plugins = {} mpi.uci:foreach("olsrd", "LoadPlugin", function(section) if section.library and not plugins[section.library] then plugins[section.library] = true end end ) -- create a loadplugin section for each found plugin for v in fs.dir("/usr/lib") do if v:sub(1, 6) == "olsrd_" then if not plugins[v] then mpi.uci:section( "olsrd", "LoadPlugin", nil, { library = v, ignore = 1 } ) end end end t = mpi:section( TypedSection, "LoadPlugin", translate("Plugins") ) t.anonymous = true t.template = "cbi/tblsection" t.override_scheme = true function t.extedit(self, section) local lib = self.map:get(section, "library") or "" return luci.dispatcher.build_url("admin", "services", "olsrd", "plugins") .. "/" .. lib end ign = t:option( Flag, "ignore", translate("Enabled") ) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end t:option( DummyValue, "library", translate("Library") ) return mpi end
gpl-2.0
nicholas-leonard/nn
L1Penalty.lua
16
1128
local L1Penalty, parent = torch.class('nn.L1Penalty','nn.Module') --This module acts as an L1 latent state regularizer, adding the --[gradOutput] to the gradient of the L1 loss. The [input] is copied to --the [output]. function L1Penalty:__init(l1weight, sizeAverage, provideOutput) parent.__init(self) self.l1weight = l1weight self.sizeAverage = sizeAverage or false if provideOutput == nil then self.provideOutput = true else self.provideOutput = provideOutput end end function L1Penalty:updateOutput(input) local m = self.l1weight if self.sizeAverage == true then m = m/input:nElement() end local loss = m*input:norm(1) self.loss = loss self.output = input return self.output end function L1Penalty:updateGradInput(input, gradOutput) local m = self.l1weight if self.sizeAverage == true then m = m/input:nElement() end self.gradInput:resizeAs(input):copy(input):sign():mul(m) if self.provideOutput == true then self.gradInput:add(gradOutput) end return self.gradInput end
bsd-3-clause
nasomi/darkstar
scripts/zones/Balgas_Dais/npcs/Burning_Circle.lua
17
2294
----------------------------------- -- Area: Balga's Dais -- NPC: Burning Circle -- Balga's Dais Burning Circle -- @pos 299 -123 345 146 ------------------------------------- package.loaded["scripts/zones/Balgas_Dais/TextIDs"] = nil; ------------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/bcnm"); require("scripts/zones/Balgas_Dais/TextIDs"); ---- 0: Rank 2 Final Mission for Bastok "The Emissary" and Sandy "Journey Abroad" ---- 1: Steamed Sprouts (BCNM 40, Star Orb) ---- 2: Divine Punishers (BCNM 60, Moon Orb) ---- 3: Saintly Invitation (Windurst mission 6-2) ---- 4: Treasure and Tribulations (BCNM 50, Comet Orb) ---- 5: Shattering Stars (MNK) ---- 6: Shattering Stars (WHM) ---- 7: Shattering Stars (SMN) ---- 8: Creeping Doom (BCNM 30, Sky Orb) ---- 9: Charming Trio (BCNM 20, Cloudy Orb) ---- 10: Harem Scarem (BCNM 30, Sky Orb) ---- 11: Early Bird Catches the Wyrm (KSNM 99, Themis Orb) ---- 12: Royal Succession (BCNM 40, Star Orb) ---- 13: Rapid Raptors (BCNM 50, Comet Orb) ---- 14: Wild Wild Whiskers (BCNM 60, Moon Orb) ---- 15: Season's Greetings (KSNM 30, Clotho Orb) ---- 16: Royale Ramble (KSNM 30, Lachesis Orb) ---- 17: Moa Constrictors (KSNM 30, Atropos Orb ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
nasomi/darkstar
scripts/globals/items/plate_of_barnacle_paella.lua
36
1576
----------------------------------------- -- ID: 5974 -- Item: Plate of Barnacle Paella -- Food Effect: 3 Hrs, All Races ----------------------------------------- -- HP 40 -- Vitality 5 -- Mind -1 -- Charisma -1 -- Defense % 25 Cap 150 -- Undead Killer 5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5974); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 40); target:addMod(MOD_VIT, 5); target:addMod(MOD_MND, -1); target:addMod(MOD_CHR, -1); target:addMod(MOD_FOOD_DEFP, 25); target:addMod(MOD_FOOD_DEF_CAP, 150); target:addMod(MOD_UNDEAD_KILLER, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 40); target:delMod(MOD_VIT, 5); target:delMod(MOD_MND, -1); target:delMod(MOD_CHR, -1); target:delMod(MOD_FOOD_DEFP, 25); target:delMod(MOD_FOOD_DEF_CAP, 150); target:delMod(MOD_UNDEAD_KILLER, 5); end;
gpl-3.0
RhenaudTheLukark/CreateYourFrisk
Assets/Mods/Examples 2/Lua/Monsters/posette.lua
1
2026
comments = {"Smells like stars and platinum.", "Posette is standing there quietly.", "Posette is flexing."} commands = {"Pose", "Stand", "Insult"} randomdialogue = {"Gimme\na\nbreak.", "...", "Ora\nOra\nOra\nOra"} sprite = "posette" --Always PNG. Extension is added automatically. name = "Posette" hp = 60 atk = 4 def = 2 check = "The next in a long line of\rrespected mannequins." dialogbubble = "right" -- See documentation for what bubbles you have available. xp = 90 gold = 100 this_must_be_the_work_of_an_enemy_stand = 0 -- Happens after the slash animation but before function HandleAttack(attackstatus) if attackstatus == -1 then currentdialogue = {"Weak."} else if hp > 30 then currentdialogue = {"I felt\nthat."} else currentdialogue = {"Now\nI'm\nangry."} end end end -- This handles the commands; all-caps versions of the commands list you have above. function HandleCustomCommand(command) if command == "POSE" then currentdialogue = {"It's\nalright."} BattleDialog({"You struck your best pose,[w:7]\rbut Posette remained unimpressed."}) elseif command == "STAND" then if this_must_be_the_work_of_an_enemy_stand == 0 then currentdialogue = {"Stand-\noff?\nAlright."} BattleDialog({"You just kind of stand there."}) elseif this_must_be_the_work_of_an_enemy_stand == 1 then currentdialogue = {"Agh..."} BattleDialog({"Your standing intensifies."}) else canspare = true table.insert(comments, "There's still a faint rumbling.") currentdialogue = {"I give\nup."} BattleDialog({"You stand there intently.\nYou hear a faint rumbling."}) end this_must_be_the_work_of_an_enemy_stand = this_must_be_the_work_of_an_enemy_stand + 1 elseif command == "INSULT" then currentdialogue = {"Awful."} BattleDialog({"You make a scathing remark about\rPosette's pose."}) end end
gpl-3.0
nasomi/darkstar
scripts/commands/addmission.lua
25
1173
--------------------------------------------------------------------------------------------------- -- func: @addmission <logID> <missionID> <player> -- desc: Adds a mission to the GM or target players log. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "iis" }; function onTrigger(player, logId, missionId, target) if (missionId == nil or logId == nil) then player:PrintToPlayer( "You must enter a valid log id and mission id!" ); player:PrintToPlayer( "@addmission <logID> <missionID> <player>" ); return; end if (target == nil) then target = player:getName(); end local targ = GetPlayerByName( target ); if (targ ~= nil) then targ:addMission( logId, missionId ); player:PrintToPlayer( string.format( "Added Mission for log %u with ID %u to %s", logId, missionId, target ) ); else player:PrintToPlayer( string.format( "Player named '%s' not found!", target ) ); player:PrintToPlayer( "@addmission <logID> <missionID> <player>" ); end end;
gpl-3.0
nasomi/darkstar
scripts/globals/weaponskills/wildfire.lua
29
1550
----------------------------------- -- Skill Level: N/A -- Description: Deals fire elemental damage. Enmity generation varies with TP. Armageddon: Aftermath. -- Acquired permanently by completing the appropriate Walk of Echoes Weapon Skill Trials. -- Can also be used by equipping Armageddon (85)/(90)/(95)/(99) or Bedlam +1/+2/+3. -- Aligned with the Soil Gorget & Shadow Gorget. -- Aligned with the Soil Belt & Shadow Belt. -- Element: Fire -- Skillchain Properties: Darkness/Gravitation -- Modifiers: AGI:60% -- Damage Multipliers by TP: -- 100%TP 200%TP 300%TP -- 5.5 5.5 5.5 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 5.5; params.ftp200 = 5.5; params.ftp300 = 5.5; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.6; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_FIRE; params.skill = SKILL_MRK; params.includemab = true; -- TODO: needs to give enmity down at varying tp percent's that is treated separately than the gear cap of -50% enmity http://www.bg-wiki.com/bg/Wildfire -- TODO: also needs aftermath effects added local damage, tpHits, extraHits = doMagicWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end;
gpl-3.0
nasomi/darkstar
scripts/zones/Port_San_dOria/npcs/Ilgusin.lua
38
1038
----------------------------------- -- Area: Port San d'Oria -- NPC: Ilgusin -- Type: Standard NPC -- @zone: 232 -- @pos -68.313 -6.5 -36.985 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x024f); 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/spells/cure.lua
18
3963
----------------------------------------- -- Spell: Cure -- Restores target's HP. -- Shamelessly stolen from http://members.shaw.ca/pizza_steve/cure/Cure_Calculator.html ----------------------------------------- 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) local divisor = 0; local constant = 0; local basepower = 0; local power = 0; local basecure = 0; local final = 0; local minCure = 10; if (USE_OLD_CURE_FORMULA == true) then power = getCurePowerOld(caster); divisor = 1; constant = -10; if (power > 100) then divisor = 57; constant = 29.125; elseif (power > 60) then divisor = 2; constant = 5; end else power = getCurePower(caster); if (power < 20) then divisor = 4; constant = 10; basepower = 0; elseif (power < 40) then divisor = 1.3333; constant = 15; basepower = 20; elseif (power < 125) then divisor = 8.5; constant = 30; basepower = 40; elseif (power < 200) then divisor = 15; constant = 40; basepower = 125; elseif (power < 600) then divisor = 20; constant = 40; basepower = 200; else divisor = 999999; constant = 65; basepower = 0; end end if (target:getAllegiance() == caster:getAllegiance() and (target:getObjType() == TYPE_PC or target:getObjType() == TYPE_MOB)) then if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCure(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); if (caster:hasStatusEffect(EFFECT_AFFLATUS_SOLACE) and target:hasStatusEffect(EFFECT_STONESKIN) == false) then local solaceStoneskin = 0; local equippedBody = caster:getEquipID(SLOT_BODY); if (equippedBody == 11186) then solaceStoneskin = math.floor(final * 0.30); elseif (equippedBody == 11086) then solaceStoneskin = math.floor(final * 0.35); else solaceStoneskin = math.floor(final * 0.25); end target:addStatusEffect(EFFECT_STONESKIN,solaceStoneskin,0,25); end; final = final + (final * (target:getMod(MOD_CURE_POTENCY_RCVD)/100)); --Applying server mods.... final = final * CURE_POWER; local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); target:wakeUp(); caster:updateEnmityFromCure(target,final); else -- no effect if player casted on mob if (target:isUndead()) then spell:setMsg(2); local dmg = calculateMagicDamage(minCure,1,caster,spell,target,HEALING_MAGIC_SKILL,MOD_MND,false)*0.5; local resist = applyResistance(caster,spell,target,caster:getStat(MOD_MND)-target:getStat(MOD_MND),HEALING_MAGIC_SKILL,1.0); dmg = dmg*resist; dmg = addBonuses(caster,spell,target,dmg); dmg = adjustForTarget(target,dmg,spell:getElement()); dmg = finalMagicAdjustments(caster,target,spell,dmg); final = dmg; target:delHP(final); target:updateEnmityFromDamage(caster,final); elseif (caster:getObjType() == TYPE_PC) then spell:setMsg(75); else -- e.g. monsters healing themselves. if (USE_OLD_CURE_FORMULA == true) then basecure = getBaseCureOld(power,divisor,constant); else basecure = getBaseCure(power,divisor,constant,basepower); end final = getCureFinal(caster,spell,basecure,minCure,false); local diff = (target:getMaxHP() - target:getHP()); if (final > diff) then final = diff; end target:addHP(final); end end return final; end;
gpl-3.0
nasomi/darkstar
scripts/zones/Bastok_Mines/npcs/Aulavia.lua
30
1603
----------------------------------- -- Area: Bastok Mines -- NPC: Aulavia -- Regional Marchant NPC -- Only sells when Bastok controls Vollbow. ----------------------------------- require("scripts/globals/events/harvest_festivals"); require("scripts/globals/shop"); require("scripts/globals/conquest"); package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) onHalloweenTrade(player,trade,npc) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) RegionOwner = GetRegionOwner(VOLLBOW); if (RegionOwner ~= BASTOK) then player:showText(npc,AULAVIA_CLOSED_DIALOG); else player:showText(npc,AULAVIA_OPEN_DIALOG); stock = { 0x27c, 119, --Chamomile 0x360, 88, --Fish Scales 0x3a8, 14, --Rock Salt 0x582, 1656 --Sweet William } showShop(player,BASTOK,stock); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
znek/xupnpd
src/profiles/samsung.lua
2
1521
sec_dlna_org_extras_none='*;DLNA.ORG_OP=00;DLNA.ORG_CI=0;DLNA.ORG_FLAGS=01700000000000000000000000000000' profiles['Samsung-AllShare']= { ['desc']='Samsung AllShare uPnP/DLNA', -- SEC_HHP_[TV]UE32ES6757/1.0 DLNADOC/1.50 ['match']=function(user_agent) if string.find(user_agent,'DLNADOC/1.50',1,true) or string.find(user_agent,'SEC_HHP_',1,true) then return true else return false end end, ['options']= { ['upnp_feature_list']= '<?xml version="1.0" encoding="utf-8"?>'.. '<Features xmlns="urn:schemas-upnp-org:av:avs" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" '.. 'xsi:schemaLocation="urn:schemas-upnp-org:av:avs http://www.upnp.org/schemas/av/avs.xsd">'.. '<Feature name="samsung.com_BASICVIEW" version="1">'.. '<container id="1" type="object.item.audioItem"/>'.. '<container id="2" type="object.item.videoItem"/>'.. '<container id="3" type="object.item.imageItem"/>'.. '</Feature>'.. '</Features>', ['upnp_albumart']=3, -- <res protocolInfo="http-get:*:image/jpeg:DLNA.ORG_PN=JPEG_TN">http://127.0.0.1:4044/logo?s=0%2F1%2F14%2F33</res> ['sec_extras']=true }, ['mime_types']= { ['mp4'] = { upnp_type.video, upnp_class.video, 'video/mp4', upnp_proto.mp4, sec_dlna_org_extras_none }, ['mkv'] = { upnp_type.video, upnp_class.video, 'video/x-mkv', upnp_proto.mkv, sec_dlna_org_extras_none } } }
gpl-2.0
Etehadmarg/margbot
bot/utils.lua
239
13499
URL = require "socket.url" http = require "socket.http" https = require "ssl.https" ltn12 = require "ltn12" serpent = require "serpent" feedparser = require "feedparser" json = (loadfile "./libs/JSON.lua")() mimetype = (loadfile "./libs/mimetype.lua")() redis = (loadfile "./libs/redis.lua")() http.TIMEOUT = 10 function get_receiver(msg) if msg.to.type == 'user' then return 'user#id'..msg.from.id end if msg.to.type == 'chat' then return 'chat#id'..msg.to.id end if msg.to.type == 'encr_chat' then return msg.to.print_name end end function is_chat_msg( msg ) if msg.to.type == 'chat' then return true end return false end function string.random(length) local str = ""; for i = 1, length do math.random(97, 122) str = str..string.char(math.random(97, 122)); end return str; end function string:split(sep) local sep, fields = sep or ":", {} local pattern = string.format("([^%s]+)", sep) self:gsub(pattern, function(c) fields[#fields+1] = c end) return fields end -- DEPRECATED function string.trim(s) print("string.trim(s) is DEPRECATED use string:trim() instead") return s:gsub("^%s*(.-)%s*$", "%1") end -- Removes spaces function string:trim() return self:gsub("^%s*(.-)%s*$", "%1") end function get_http_file_name(url, headers) -- Eg: foo.var local file_name = url:match("[^%w]+([%.%w]+)$") -- Any delimited alphanumeric on the url file_name = file_name or url:match("[^%w]+(%w+)[^%w]+$") -- Random name, hope content-type works file_name = file_name or str:random(5) local content_type = headers["content-type"] local extension = nil if content_type then extension = mimetype.get_mime_extension(content_type) end if extension then file_name = file_name.."."..extension end local disposition = headers["content-disposition"] if disposition then -- attachment; filename=CodeCogsEqn.png file_name = disposition:match('filename=([^;]+)') or file_name end return file_name end -- Saves file to /tmp/. If file_name isn't provided, -- will get the text after the last "/" for filename -- and content-type for extension function download_to_file(url, file_name) print("url to download: "..url) local respbody = {} local options = { url = url, sink = ltn12.sink.table(respbody), redirect = true } -- nil, code, headers, status local response = nil if url:starts('https') then options.redirect = false response = {https.request(options)} else response = {http.request(options)} end local code = response[2] local headers = response[3] local status = response[4] if code ~= 200 then return nil end file_name = file_name or get_http_file_name(url, headers) local file_path = "/tmp/"..file_name print("Saved to: "..file_path) file = io.open(file_path, "w+") file:write(table.concat(respbody)) file:close() return file_path end function vardump(value) print(serpent.block(value, {comment=false})) end -- taken from http://stackoverflow.com/a/11130774/3163199 function scandir(directory) local i, t, popen = 0, {}, io.popen for filename in popen('ls -a "'..directory..'"'):lines() do i = i + 1 t[i] = filename end return t end -- http://www.lua.org/manual/5.2/manual.html#pdf-io.popen function run_command(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end -- User has privileges function is_sudo(msg) local var = false -- Check users id in config for v,user in pairs(_config.sudo_users) do if user == msg.from.id then var = true end end return var end -- Returns the name of the sender function get_name(msg) local name = msg.from.first_name if name == nil then name = msg.from.id end return name end -- Returns at table of lua files inside plugins function plugins_names( ) local files = {} for k, v in pairs(scandir("plugins")) do -- Ends with .lua if (v:match(".lua$")) then table.insert(files, v) end end return files end -- Function name explains what it does. function file_exists(name) local f = io.open(name,"r") if f ~= nil then io.close(f) return true else return false end end -- Save into file the data serialized for lua. -- Set uglify true to minify the file. function serialize_to_file(data, file, uglify) file = io.open(file, 'w+') local serialized if not uglify then serialized = serpent.block(data, { comment = false, name = '_' }) else serialized = serpent.dump(data) end file:write(serialized) file:close() end -- Returns true if the string is empty function string:isempty() return self == nil or self == '' end -- Returns true if the string is blank function string:isblank() self = self:trim() return self:isempty() end -- DEPRECATED!!!!! function string.starts(String, Start) print("string.starts(String, Start) is DEPRECATED use string:starts(text) instead") return Start == string.sub(String,1,string.len(Start)) end -- Returns true if String starts with Start function string:starts(text) return text == string.sub(self,1,string.len(text)) end -- Send image to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_photo(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function, cb_extra = cb_extra } -- Call to remove with optional callback send_photo(receiver, file_path, cb_function, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_photo_from_url(receiver, url, cb_function, cb_extra) -- If callback not provided cb_function = cb_function or ok_cb cb_extra = cb_extra or false local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, cb_function, cb_extra) else print("File path: "..file_path) _send_photo(receiver, file_path, cb_function, cb_extra) end end -- Same as send_photo_from_url but as callback function function send_photo_from_url_callback(cb_extra, success, result) local receiver = cb_extra.receiver local url = cb_extra.url local file_path = download_to_file(url, false) if not file_path then -- Error local text = 'Error downloading the image' send_msg(receiver, text, ok_cb, false) else print("File path: "..file_path) _send_photo(receiver, file_path, ok_cb, false) end end -- Send multiple images asynchronous. -- param urls must be a table. function send_photos_from_url(receiver, urls) local cb_extra = { receiver = receiver, urls = urls, remove_path = nil } send_photos_from_url_callback(cb_extra) end -- Use send_photos_from_url. -- This function might be difficult to understand. function send_photos_from_url_callback(cb_extra, success, result) -- cb_extra is a table containing receiver, urls and remove_path local receiver = cb_extra.receiver local urls = cb_extra.urls local remove_path = cb_extra.remove_path -- The previously image to remove if remove_path ~= nil then os.remove(remove_path) print("Deleted: "..remove_path) end -- Nil or empty, exit case (no more urls) if urls == nil or #urls == 0 then return false end -- Take the head and remove from urls table local head = table.remove(urls, 1) local file_path = download_to_file(head, false) local cb_extra = { receiver = receiver, urls = urls, remove_path = file_path } -- Send first and postpone the others as callback send_photo(receiver, file_path, send_photos_from_url_callback, cb_extra) end -- Callback to remove a file function rmtmp_cb(cb_extra, success, result) local file_path = cb_extra.file_path local cb_function = cb_extra.cb_function or ok_cb local cb_extra = cb_extra.cb_extra if file_path ~= nil then os.remove(file_path) print("Deleted: "..file_path) end -- Finally call the callback cb_function(cb_extra, success, result) end -- Send document to user and delete it when finished. -- cb_function and cb_extra are optionals callback function _send_document(receiver, file_path, cb_function, cb_extra) local cb_extra = { file_path = file_path, cb_function = cb_function or ok_cb, cb_extra = cb_extra or false } -- Call to remove with optional callback send_document(receiver, file_path, rmtmp_cb, cb_extra) end -- Download the image and send to receiver, it will be deleted. -- cb_function and cb_extra are optionals callback function send_document_from_url(receiver, url, cb_function, cb_extra) local file_path = download_to_file(url, false) print("File path: "..file_path) _send_document(receiver, file_path, cb_function, cb_extra) end -- Parameters in ?a=1&b=2 style function format_http_params(params, is_get) local str = '' -- If is get add ? to the beginning if is_get then str = '?' end local first = true -- Frist param for k,v in pairs (params) do if v then -- nil value if first then first = false str = str..k.. "="..v else str = str.."&"..k.. "="..v end end end return str end -- Check if user can use the plugin and warns user -- Returns true if user was warned and false if not warned (is allowed) function warns_user_not_allowed(plugin, msg) if not user_allowed(plugin, msg) then local text = 'This plugin requires privileged user' local receiver = get_receiver(msg) send_msg(receiver, text, ok_cb, false) return true else return false end end -- Check if user can use the plugin function user_allowed(plugin, msg) if plugin.privileged and not is_sudo(msg) then return false end return true end function send_order_msg(destination, msgs) local cb_extra = { destination = destination, msgs = msgs } send_order_msg_callback(cb_extra, true) end function send_order_msg_callback(cb_extra, success, result) local destination = cb_extra.destination local msgs = cb_extra.msgs local file_path = cb_extra.file_path if file_path ~= nil then os.remove(file_path) print("Deleted: " .. file_path) end if type(msgs) == 'string' then send_large_msg(destination, msgs) elseif type(msgs) ~= 'table' then return end if #msgs < 1 then return end local msg = table.remove(msgs, 1) local new_cb_extra = { destination = destination, msgs = msgs } if type(msg) == 'string' then send_msg(destination, msg, send_order_msg_callback, new_cb_extra) elseif type(msg) == 'table' then local typ = msg[1] local nmsg = msg[2] new_cb_extra.file_path = nmsg if typ == 'document' then send_document(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'image' or typ == 'photo' then send_photo(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'audio' then send_audio(destination, nmsg, send_order_msg_callback, new_cb_extra) elseif typ == 'video' then send_video(destination, nmsg, send_order_msg_callback, new_cb_extra) else send_file(destination, nmsg, send_order_msg_callback, new_cb_extra) end end end -- Same as send_large_msg_callback but friendly params function send_large_msg(destination, text) local cb_extra = { destination = destination, text = text } send_large_msg_callback(cb_extra, true) end -- If text is longer than 4096 chars, send multiple msg. -- https://core.telegram.org/method/messages.sendMessage function send_large_msg_callback(cb_extra, success, result) local text_max = 4096 local destination = cb_extra.destination local text = cb_extra.text local text_len = string.len(text) local num_msg = math.ceil(text_len / text_max) if num_msg <= 1 then send_msg(destination, text, ok_cb, false) else local my_text = string.sub(text, 1, 4096) local rest = string.sub(text, 4096, text_len) local cb_extra = { destination = destination, text = rest } send_msg(destination, my_text, send_large_msg_callback, cb_extra) end end -- Returns a table with matches or nil function match_pattern(pattern, text, lower_case) if text then local matches = {} if lower_case then matches = { string.match(text:lower(), pattern) } else matches = { string.match(text, pattern) } end if next(matches) then return matches end end -- nil end -- Function to read data from files function load_from_file(file, default_data) local f = io.open(file, "r+") -- If file doesn't exists if f == nil then -- Create a new empty table default_data = default_data or {} serialize_to_file(default_data, file) print ('Created file', file) else print ('Data loaded from file', file) f:close() end return loadfile (file)() end -- See http://stackoverflow.com/a/14899740 function unescape_html(str) local map = { ["lt"] = "<", ["gt"] = ">", ["amp"] = "&", ["quot"] = '"', ["apos"] = "'" } new = string.gsub(str, '(&(#?x?)([%d%a]+);)', function(orig, n, s) var = map[s] or n == "#" and string.char(s) var = var or n == "#x" and string.char(tonumber(s,16)) var = var or orig return var end) return new end
gpl-2.0
nasomi/darkstar
scripts/zones/Qufim_Island/npcs/Pitoire_RK.lua
30
3053
----------------------------------- -- Area: Qufim Island -- NPC: Pitoire, R.K. -- Type: Outpost Conquest Guards -- @pos -245.366 -20.344 299.502 126 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ----------------------------------- require("scripts/globals/conquest"); require("scripts/zones/Qufim_Island/TextIDs"); local guardnation = SANDORIA; -- SANDORIA, BASTOK, WINDURST, 4 = jeuno local guardtype = 3; -- 1: city, 2: foreign, 3: outpost, 4: border local region = QUFIMISLAND; local csid = 0x7ffb; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) tradeConquestGuard(player,npc,trade,guardnation,guardtype); end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(getSupplyKey(region)) and player:getNation() == guardnation) then if (supplyRunFresh(player) == 1) then player:startEvent(csid,16,0,0,0,1,0,0,255); -- you have brought us supplies ! else player:showText(npc, CONQUEST - 1); -- "Hmm... These supplies you have brought us are too old to be of any use." player:delKeyItem(getSupplyKey(region)); player:messageSpecial(KEYITEM_OBTAINED + 1, getSupplyKey(region)); player:setVar("supplyQuest_region",0); end else local arg1 = getArg1(guardnation, player) - 1; if (arg1 >= 1792) then -- foreign, non-allied player:startEvent(csid,1808,0,0,0,0,player:getRank(),0,0); else -- citizen or allied player:startEvent(csid,arg1,0,0x3F0000,0,0,getArg6(player),0,0); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("OPTION: %u",option); if (option == 1) then local duration = (player:getRank() + getNationRank(player:getNation()) + 3) * 3600; player:delStatusEffect(EFFECT_SIGIL); player:delStatusEffect(EFFECT_SANCTION); player:delStatusEffect(EFFECT_SIGNET); player:addStatusEffect(EFFECT_SIGNET,0,0,duration); -- Grant Signet elseif (option == 2) then player:delKeyItem(getSupplyKey(region)); player:addCP(supplyReward[region + 1]) player:messageSpecial(CONQUEST); -- "You've earned conquest points!" if (hasOutpost(player, region+5) == 0) then local supply_quests = 2^(region+5); player:addNationTeleport(guardnation,supply_quests); player:setVar("supplyQuest_region",0); end elseif (option == 4) then if (player:delGil(giltosetHP(guardnation,player))) then player:setHomePoint(); player:messageSpecial(CONQUEST + 94); -- "Your home point has been set." else player:messageSpecial(CONQUEST + 95); -- "You do not have enough gil to set your home point here." end end end;
gpl-3.0
nasomi/darkstar
scripts/globals/weaponskills/frostbite.lua
30
1231
----------------------------------- -- Frostbite -- Great Sword weapon skill -- Skill Level: 70 -- Delivers an ice elemental attack. Damage varies with TP. -- Aligned with the Snow Gorget. -- Aligned with the Snow Belt. -- Element: Ice -- Modifiers: STR:20% ; INT:20% -- 100%TP 200%TP 300%TP -- 1.00 2.00 2.50 ----------------------------------- require("scripts/globals/magic"); require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.ele = ELE_ICE; params.skill = SKILL_GSD; params.includemab = true; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 0.4; params.int_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Maliv/SecretBot
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
nasomi/darkstar
scripts/globals/items/coeurl_sub.lua
35
1832
----------------------------------------- -- ID: 5166 -- Item: coeurl_sub -- Food Effect: 30Min, All Races ----------------------------------------- -- Magic 10 -- Strength 5 -- Agility 1 -- Intelligence -2 -- Health Regen While Healing 1 -- Attack % 20 -- Attack Cap 75 -- Ranged ATT % 20 -- Ranged ATT Cap 75 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5166); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 10); target:addMod(MOD_STR, 5); target:addMod(MOD_AGI, 1); target:addMod(MOD_INT, -2); target:addMod(MOD_HPHEAL, 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); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 10); target:delMod(MOD_STR, 5); target:delMod(MOD_AGI, 1); target:delMod(MOD_INT, -2); target:delMod(MOD_HPHEAL, 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); end;
gpl-3.0
aqasaeed/zeus
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Taulenne.lua
34
4855
----------------------------------- -- Area: Northern San d'Oria -- NPC: Taulenne -- Armor Storage NPC ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; package.loaded["scripts/globals/armorstorage"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/armorstorage"); require("scripts/zones/Northern_San_dOria/TextIDs"); Deposit = 0x0304; Withdrawl = 0x0305; ArraySize = table.getn(StorageArray); G1 = 0; G2 = 0; G3 = 0; G4 = 0; G5 = 0; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) 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; for SetId = 1,ArraySize,11 do TradeCount = trade:getItemCount(); T1 = trade:hasItemQty(StorageArray[SetId + 5],1); if (T1 == true) then if (player:hasKeyItem(StorageArray[SetId + 10]) == false) then if (TradeCount == StorageArray[SetId + 3]) then T2 = trade:hasItemQty(StorageArray[SetId + 4],1); T3 = trade:hasItemQty(StorageArray[SetId + 6],1); T4 = trade:hasItemQty(StorageArray[SetId + 7],1); T5 = trade:hasItemQty(StorageArray[SetId + 8],1); if (StorageArray[SetId + 4] == 0) then T2 = true; end; if (StorageArray[SetId + 6] == 0) then T3 = true; end; if (StorageArray[SetId + 7] == 0) then T4 = true; end; if (StorageArray[SetId + 8] == 0) then T5 = true; end; if (T2 == true and T3 == true and T4 == true and T5 == true) then player:startEvent(Deposit,0,0,0,0,0,StorageArray[SetId + 9]); player:addKeyItem(StorageArray[SetId + 10]); player:messageSpecial(KEYITEM_OBTAINED,StorageArray[SetId + 10]); break; end; end; end; end; end; end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) CurrGil = player:getGil(); for KeyItem = 11,ArraySize,11 do if player:hasKeyItem(StorageArray[KeyItem]) then if StorageArray[KeyItem - 9] == 1 then G1 = G1 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 2 then G2 = G2 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 3 then G3 = G3 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 4 then G4 = G4 + StorageArray[KeyItem - 8]; elseif StorageArray[KeyItem - 9] == 6 then G5 = G5 + StorageArray[KeyItem - 8]; end; end; end; player:startEvent(Withdrawl,G1,G2,G3,G4,CurrGil,G5); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) if (csid == Withdrawl) then player:updateEvent(StorageArray[option * 11 - 6], StorageArray[option * 11 - 5], StorageArray[option * 11 - 4], StorageArray[option * 11 - 3], StorageArray[option * 11 - 2], StorageArray[option * 11 - 1]); end; end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if (csid == Withdrawl) then if (option > 0 and option <= StorageArray[ArraySize] - 10) then if (player:getFreeSlotsCount() >= StorageArray[option * 11 - 7]) then for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:addItem(StorageArray[option * 11 - Item],1); player:messageSpecial(ITEM_OBTAINED,StorageArray[option * 11 - Item]); end; end; player:delKeyItem(StorageArray[option * 11]); player:setGil(player:getGil() - StorageArray[option * 11 - 1]); else for Item = 2,6,1 do if (StorageArray[option * 11 - Item] > 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,StorageArray[option * 11 - Item]); end; end; end; end; end; if (csid == Deposit) then player:tradeComplete(); end; end;
gpl-3.0
EricssonResearch/scott-eu
simulation-ros/src/turtlebot2i/turtlebot2i_description/v-rep_model/warehouse_scene/vrep_scripts/ShelfBody.lua
1
8978
-- DO NOT WRITE CODE OUTSIDE OF THE if-then-end SECTIONS BELOW!! (unless the code is a function definition) -- Shelf functions -- http://www.coppeliarobotics.com/helpFiles/en/accessingGeneralObjects.htm -- List all products on this shelf getObjectName = function(intArg, fltArg, strArg, byteArg) objectHandle = intArg[1] objectName=sim.getObjectName(objectHandle) return {},{},{objectName},'' end getListOfProducts = function () shelfHandle=sim.getObjectAssociatedWithScript(sim.handle_self) shelfName=sim.getObjectName(shelfHandle) objects = sim.getObjectsInTree(sim.handle_scene,0,0) numberOfObjectsOfTypeShape=table.getn(objects) cp=1 cs=1 products={} shelves={} for i=1,numberOfObjectsOfTypeShape,1 do objectName=sim.getObjectName(objects[i]) -- p=sim.getObjectPosition(objects[i],shelfHandle) -- relative position --distance=math.sqrt(p[1]*p[1]+p[2]*p[2]+p[3]*p[3]) if string.match(objectName, "product") then products[cp]=objects[i] cp=cp+1 elseif string.match(objectName, "ShelfBody") then shelves[cs]=objects[i] cs=cs+1 end end shelfContent={} counter=1 for p=1,cp-1,1 do product=products[p] closestShelf=shelves[1] p=sim.getObjectPosition(product,closestShelf) -- relative position distance=math.sqrt(p[1]*p[1]+p[2]*p[2]+p[3]*p[3]) for s=1,cs-1,1 do p=sim.getObjectPosition(product,shelves[s]) -- relative position distance_new=math.sqrt(p[1]*p[1]+p[2]*p[2]+p[3]*p[3]) if(distance_new<distance)then closestShelf=shelves[s] distance=distance_new end end if(closestShelf==shelfHandle and distance <= shelf_bound_box_radius)then shelfContent[counter]=sim.getObjectName(product) --print(shelfName,' ',sim.getObjectName(shelfContent[counter])) counter=counter+1 end end return shelfContent end --------------------------- -- Adds Product to Shelf -- Returns {1},{},{},"" if successful and {0},{},{},"" if it fails addProduct=function(inInts, inFloats, inStrings, inBuff) productType = inStrings[1] --[[ local initial_t = sim.getSimulationTime() local dt=0 while(dt<1000)do t=sim.getSimulationTime() if(t~=nil)then dt=t-initial_t end --print("dt: ",dt) end ]]-- --locks the simulation --sim.wait(1000, true) -- only works with threaded scripts if((productType=='productGreen') or (productType=='productRed') or (productType=='productYellow'))then greenPosition={-.35,.1,.3} redPosition={-.35,0,.3} yellowPosition={-.35,-.1,.3} if(productType=='productGreen')then h=proximitySensorInputGreenHandle position=greenPosition elseif(productType=='productRed')then h=proximitySensorInputRedHandle position=redPosition elseif(productType=='productYellow')then h=proximitySensorInputYellowHandle position=yellowPosition end --Check if there is enough room for it counter_of_product_type=0; shelfContent=getListOfProducts() -- print('======') for i = 1,table.getn(shelfContent),1 do -- print("-> ",shelfContent[i]) if(string.match(shelfContent[i], productType))then counter_of_product_type=counter_of_product_type+1; end end -- print('======') --print("counter_of_product_type(",productType,"): ",counter_of_product_type) if(counter_of_product_type<maximum_number_of_products_per_collumn)then -- Check if position is free before creating a new one local res,dist,pt,obj=sim.handleProximitySensor(h) if obj then local fullnm=sim.getObjectName(obj) local suffix,nm=sim.getNameSuffix(fullnm) print("Couldn't create a new ",nm,". There is already ",fullnm," in this position. ") return {0},{},{},"" else string_to_avoid_dynamic_naming=productType .. '#' objectHandle=sim.getObjectHandle(string_to_avoid_dynamic_naming) copiedObjectHandles=sim.copyPasteObjects({objectHandle},1) shelfHandle=sim.getObjectAssociatedWithScript(sim.handle_self) copiedObjectHandle=copiedObjectHandles[1] sim.setObjectOrientation(copiedObjectHandle,shelfHandle,{0,0,0}) sim.setObjectPosition(copiedObjectHandle,shelfHandle,position) sim.setObjectInt32Parameter(copiedObjectHandle,sim.shapeintparam_static,0) -- ,0) for dynamic and ,1) for static sim.setObjectParent(copiedObjectHandle, shelfHandle, true) end else print("Product creation error. There are too many (",counter_of_product_type,") ",productType," units in this shelf.") return {0},{},{"full shelf"},"" end else print('Product creation error. Product type ',productType,' does not exist.') return {0},{},{"product not found"},"" end return {1},{},{"True"},""; end -- Return a list with all currrent pickable products getListOfPickableProducts = function(inInts, inFloats, inStrings, inBuff) psg=sim.getObjectPosition(positionSensorGreenHandle,-1) -- position in space of the green sensor psr=sim.getObjectPosition(positionSensorRedHandle,-1) -- position in space of the red sensor psy=sim.getObjectPosition(positionSensorYellowHandle,-1) -- position in space of the yellow sensor shelfContent=getListOfProducts() pickable={"None", "None", "None"} for i = 1,table.getn(shelfContent),1 do --print(shelfContent[i]) p=sim.getObjectPosition(sim.getObjectHandle(shelfContent[i]),-1) -- for this product to be pickable, it should be bellow (in z) its sensor if(string.match(shelfContent[i], "Yellow"))then if(p[3]<psr[3])then pickable[1]=shelfContent[i] end elseif(string.match(shelfContent[i], "Red"))then if(p[3]<psg[3])then pickable[2]=shelfContent[i] end elseif(string.match(shelfContent[i], "Green"))then if(p[3]<psy[3])then pickable[3]=shelfContent[i] end else print('Product ID error in child script.') end end return {1}, {}, pickable, "" end if (sim_call_type==sim.syscb_init) then end if (sim_call_type==sim.syscb_actuation) then if (firstRun==nil) then sim.setThreadSwitchTiming(100) -- Default timing for automatic thread switching maximum_number_of_products_per_collumn=10 --Arbitrary parameter shelf_bound_box_radius = 0.6 --NOTE: must be carefull not to put other products too close to this shelf. positionSensorGreenHandle=sim.getObjectHandle('PositionSensorGreen') positionSensorRedHandle=sim.getObjectHandle('PositionSensorRed') positionSensorYellowHandle=sim.getObjectHandle('PositionSensorYellow') proximitySensorInputGreenHandle=sim.getObjectHandle('proximitySensorInputGreen') proximitySensorInputRedHandle=sim.getObjectHandle('proximitySensorInputRed') proximitySensorInputYellowHandle=sim.getObjectHandle('proximitySensorInputYellow') num_red_products = sim.getScriptSimulationParameter(sim.handle_self,'num_red_products') num_green_products = sim.getScriptSimulationParameter(sim.handle_self,'num_green_products') num_yellow_products = sim.getScriptSimulationParameter(sim.handle_self,'num_yellow_products') fill_shelf_on_start = sim.getScriptSimulationParameter(sim.handle_self,'fill_shelf_on_start') count_red_products = 0 count_green_products = 0 count_yellow_products = 0 t0=os.clock() dt=2 firstRun=false end if(os.clock() - t0 >= dt)then t0 = os.clock() if fill_shelf_on_start then if count_red_products < num_red_products then ret = addProduct({}, {}, {'productRed'}, '') if ret[1] == 1 then count_red_products = count_red_products + 1 end end if count_green_products < num_green_products then ret = addProduct({}, {}, {'productGreen'}, '') if ret[1] == 1 then count_green_products = count_green_products + 1 end end if count_yellow_products < num_yellow_products then ret = addProduct({}, {}, {'productYellow'}, '') if ret[1] == 1 then count_yellow_products = count_yellow_products + 1 end end end end end if (sim_call_type==sim.syscb_sensing) then end if (sim_call_type==sim.syscb_cleanup) then end
apache-2.0
ngeiswei/ardour
share/scripts/_pong.lua
4
7075
ardour { ["type"] = "dsp", name = "Pong", category = "Toy", license = "MIT", author = "Ardour Team", description = [[A console classic for your console]] } -- return possible i/o configurations function dsp_ioconfig () -- -1, -1 = any number of channels as long as input and output count matches return { [1] = { audio_in = -1, audio_out = -1}, } end -- control port(s) function dsp_params () return { { ["type"] = "input", name = "Bar", min = 0, max = 1, default = 0.5 }, { ["type"] = "input", name = "Reset", min = 0, max = 1, default = 0, toggled = true }, { ["type"] = "input", name = "Difficulty", min = 1, max = 10, default = 3}, } end -- Game State (for this instance) -- NOTE: these variables are for the DSP part (not shared with the GUI instance) local sample_rate -- sample-rate local fps -- audio samples per game-step local game_time -- counts up to fps local game_score local ball_x, ball_y -- ball position [0..1] local dx, dy -- current ball speed local lost_sound -- audio-sample counter for game-over [0..3*fps] local ping_sound -- audio-sample counter for ping-sound [0..fps] local ping_phase -- ping note phase-difference per sample local ping_pitch function dsp_init (rate) -- allocate a "shared memory" area to transfer state to the GUI self:shmem ():allocate (3) self:shmem ():clear () -- initialize some variables sample_rate = rate fps = rate / 25 ping_pitch = 752 / rate ball_x = 0.5 ball_y = 0 dx = 0.00367 dy = 0.01063 game_score = 0 game_time = fps -- start the ball immediately (notify GUI) ping_sound = fps -- set to end of synth cycle lost_sound = 3 * fps end function queue_beep () -- queue 'ping' sound (unless one is already playing to prevent clicks) if (ping_sound >= fps) then -- major scale, 2 octaves local scale = { 0, 2, 4, 5, 7, 9, 11, 12, 14, 16, 17, 19, 21, 23, 24 } local midi_note = 60 + scale[1 + math.floor (math.random () * 14)] ping_pitch = (440 / 32) * 2^((midi_note - 10.0) / 12.0) / sample_rate ping_sound = 0 ping_phase = 0 end end -- callback: process "n_samples" of audio -- ins, outs are http://manual.ardour.org/lua-scripting/class_reference/#C:FloatArray -- pointers to the audio buffers function dsp_run (ins, outs, n_samples) local ctrl = CtrlPorts:array () -- get control port array (read/write) local changed = false -- flag to notify GUI on every game-step game_time = game_time + n_samples -- reset (allow to write automation from a given start-point) -- ctrl[2] corresponds to the "Reset" input control if ctrl[2] > 0 then game_time = 0 ball_x = 0.5 ball_y = 0 dx = 0.00367 dy = 0.01063 game_score = 0 end -- simple game engine while game_time > fps and ctrl[2] <= 0 do changed = true game_time = game_time - fps -- move the ball ball_x = ball_x + dx * ctrl[3] ball_y = ball_y + dy * ctrl[3] -- reflect left/right if ball_x >= 1 or ball_x <= 0 then dx = -dx queue_beep () end -- single player (reflect top) -- TODO "stereo" version, 2 ctrls :) if ball_y <= 0 then dy = - dy y = 0 queue_beep () end -- keep the ball in the field at all times if ball_x >= 1 then ball_x = 1 end if ball_x <= 0 then ball_x = 0 end -- bottom edge if ball_y > 1 then local bar = ctrl[1] -- get bar position if math.abs (bar - ball_x) < 0.1 then -- reflect the ball dy = - dy ball_y = 1.0 dx = dx - 0.04 * (bar - ball_x) -- make sure it's moving (not stuck on borders) if math.abs (dx) < 0.0001 then dx = 0.0001 end game_score = game_score + 1 queue_beep () else -- game over, reset game lost_sound = 0 -- re-start noise ball_y = 0 game_score = 0 dx = 0.00367 end end end -- forward audio if processing is not in-place for c = 1,#outs do -- check if output and input buffers for this channel are identical -- http://manual.ardour.org/lua-scripting/class_reference/#C:FloatArray if ins[c] ~= outs[c] then -- fast (accelerated) copy -- http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:DSP ARDOUR.DSP.copy_vector (outs[c], ins[c], n_samples) end end -- simple synth -- TODO Optimize if ping_sound < fps then -- cache audio data buffers for direct access, later local abufs = {} for c = 1,#outs do abufs[c] = outs[c]:array() end -- simple sine synth with a sine-envelope for s = 1, n_samples do ping_sound = ping_sound + 1 ping_phase = ping_phase + ping_pitch local snd = 0.7 * math.sin(6.283185307 * ping_phase) * math.sin (3.141592 * ping_sound / fps) -- add synthesized sound to all channels for c = 1,#outs do abufs[c][s] = abufs[c][s] + snd end -- break out of the loop when the sound finished if ping_sound >= fps then goto ping_end end end ::ping_end:: end if lost_sound < 3 * fps then local abufs = {} for c = 1,#outs do abufs[c] = outs[c]:array() end for s = 1, n_samples do lost_sound = lost_sound + 1 -- -12dBFS white noise local snd = 0.5 * (math.random () - 0.5) for c = 1,#outs do abufs[c][s] = abufs[c][s] + snd end if lost_sound >= 3 * fps then goto noise_end end end ::noise_end:: end if changed then -- notify the GUI local shmem = self:shmem () -- get the shared memory region local state = shmem:to_float (0):array () -- "cast" into lua-table -- update data.. state[1] = ball_x state[2] = ball_y state[3] = game_score -- ..and wake up the UI self:queue_draw () end end ------------------------------------------------------------------------------- --- inline display local txt = nil -- cache font description (in GUI context) function render_inline (ctx, w, max_h) local ctrl = CtrlPorts:array () -- control port array local shmem = self:shmem () -- shared memory region (game state from DSP) local state = shmem:to_float (0):array () -- cast to lua-table if (w > max_h) then h = max_h else h = w end -- prepare text rendering if not txt then -- allocate PangoLayout and set font --http://manual.ardour.org/lua-scripting/class_reference/#Cairo:PangoLayout txt = Cairo.PangoLayout (ctx, "Mono 10px") end -- ctx is-a http://manual.ardour.org/lua-scripting/class_reference/#Cairo:Context -- 2D vector graphics http://cairographics.org/ -- clear background ctx:rectangle (0, 0, w, h) ctx:set_source_rgba (.2, .2, .2, 1.0) ctx:fill () -- print the current score if (state[3] > 0) then txt:set_text (string.format ("%.0f", state[3])); local tw, th = txt:get_pixel_size () ctx:set_source_rgba (1, 1, 1, 1.0) ctx:move_to (w - tw - 3, 3) txt:show_in_cairo_context (ctx) end -- prepare line and dot rendering ctx:set_line_cap (Cairo.LineCap.Round) ctx:set_line_width (3.0) ctx:set_source_rgba (.8, .8, .8, 1.0) -- display bar local bar_width = w * .1 local bar_space = w - bar_width ctx:move_to (bar_space * ctrl[1], h - 3) ctx:rel_line_to (bar_width, 0) ctx:stroke () -- display ball ctx:move_to (1 + state[1] * (w - 3), state[2] * (h - 5)) ctx:close_path () ctx:stroke () return {w, h} end
gpl-2.0
renyaoxiang/QSanguosha-For-Hegemony
extension-doc/18-Beta.lua
15
3217
--[[ 本文档用于介绍在 beta 版中引入的更新 本文档针对的 beta 版本为 20120203(V0.7 Beta 1) 本文档假定阅读者已经有一定的编写 AI 的基础,仅作十分简略的介绍。 新的函数与表使得 AI 的可扩展性大大增强。 * sgs.ai_slash_prohibit:表,由 SmartAI.slashProhibit 载入 % 元素名称:技能名 % 元素:function(self, to, card) %% self: SmartAI %% to: ServerPlayer*,拥有元素名称所描述的技能 %% card: Card* %% 返回值:布尔值,true表明在策略上不宜对 to 使用【杀】 card。 本表设置后,以后编写技能将基本不需修改 SmartAI.slashProhibit * sgs.ai_cardneed:表,由 SmartAI.getCardNeedPlayer (新函数,见下面的描述) 载入 % 元素名称:技能名 % 元素;function(friend, card, self) %% friend:ServerPlayer*,拥有元素名称所描述的技能 %% card: Card* %% self: SmartAI %% 返回值:布尔值,true 表明友方玩家 friend 需要卡牌 card 标准元素:sgs.ai_cardneed.equip 和 sgs.ai_cardneed.bignumber,详见 smart-ai.lua * SmartAI:getCardNeedPlayer(cards);在 cards 中找到一张用于仁德/遗计/任意类似技能的卡牌及使用对象 % cards:表,包含可用的卡牌 % 返回值:一个二元组 Card*, ServerPlayer*,表示卡牌及其使用对象。 引入这一个表和一个函数之后,以后想要刘备认识您编写的新技能而按照您的需要仁德卡牌给您,就变得十分简单了。 * sgs.ai_skill_pindian:表,用于 SmartAI.askForPindian % 元素名称:reason % 元素:function(minusecard, self, requstor, maxcard, mincard) %% minusecard:自己手牌中使用价值最小的卡牌 %% self:SmartAI %% requestor:ServerPlayer*,请求来源 %% maxcard:手牌中使用价值低于 6 的卡牌中点数最大者 %% mincard:手牌中使用价值低于 6 的卡牌中点数最小者 %% 返回值:Card*,一般可以直接用参数中的一个返回。 若为 nil,表示采用默认策略。 默认策略即:若 requestor 是友方,返回 mincard,否则返回 maxcard。 因此一般只要指明何时返回 minusecard 即可。 * sgs.ai_skill_suit:表,用于 SmartAI.askForSuit % 元素名称:reason(新修改的源代码中加入了这一参数,如果需要用到本表请自行编译源码) % 元素:function(self) %% 返回值:Card::Suit * sgs.ai_trick_prohibit:表,用于 SmartAI.trickProhibit % 元素名称:技能名 % 元素:function(card, self, to) %% 返回值:布尔值,表示是否存在由锦囊牌 card 对含有由元素名称所描述的技能的对象 to 的禁止技 加入这一表之后,随着日后 AI 的进一步完善,帷幕等技能将不用修改 SmartAI(目前仍存在一定的缺陷) * sgs.ai_slash_weaponfilter:表,用于 SmartAI.useCardSlash % 元素名称:武器的对象名 % 元素:function(to, self) %% 返回值:布尔值,表示如果准备对 to 使用【杀】,是否应该首先安装由元素名称描述的武器。 这一个表是装备牌 AI DIY 接口的开端。 上面这些表的例子基本上可以在 smart-ai.lua,standard-ai.lua 和 standard_cards-ai.lua 找到,从略。]]
gpl-3.0
minaevmike/rspamd
test/lua/unit/html.lua
3
1472
context("HTML processing", function() local rspamd_util = require("rspamd_util") local logger = require("rspamd_logger") test("Extract text from HTML", function() local cases = { {[[ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> </head> <body> <!-- page content --> Hello, world! <b>test</b> <p>data<> </P> <b>stuff</p>? </body> </html> ]], "Hello, world! test data\r\nstuff?"}, {[[ <?xml version="1.0" encoding="iso-8859-1"?> <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd"> <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en" lang="en"> <head> <title> Wikibooks </title> </head> <body> <p> Hello, world! </p> </body> </html>]], 'Hello, world!\r\n'}, {[[ <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>title</title> <link rel="stylesheet" href="style.css"> <script src="script.js"></script> <style><!-- - -a -a -a -- --- - --></head> <body> <!-- page content --> Hello, world! </body> </html> ]], 'Hello, world!'}, } for _,c in ipairs(cases) do local t = rspamd_util.parse_html(c[1]) assert_not_nil(t) assert_equal(c[2], tostring(t)) end end) end)
apache-2.0
appaquet/torch-android
src/3rdparty/nn/TemporalSubSampling.lua
44
1378
local TemporalSubSampling, parent = torch.class('nn.TemporalSubSampling', 'nn.Module') function TemporalSubSampling:__init(inputFrameSize, kW, dW) parent.__init(self) dW = dW or 1 self.inputFrameSize = inputFrameSize self.kW = kW self.dW = dW self.weight = torch.Tensor(inputFrameSize) self.bias = torch.Tensor(inputFrameSize) self.gradWeight = torch.Tensor(inputFrameSize) self.gradBias = torch.Tensor(inputFrameSize) self:reset() end function TemporalSubSampling:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function TemporalSubSampling:updateOutput(input) return input.nn.TemporalSubSampling_updateOutput(self, input) end function TemporalSubSampling:updateGradInput(input, gradOutput) if self.gradInput then return input.nn.TemporalSubSampling_updateGradInput(self, input, gradOutput) end end function TemporalSubSampling:accGradParameters(input, gradOutput, scale) return input.nn.TemporalSubSampling_accGradParameters(self, input, gradOutput, scale) end
bsd-3-clause
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/applications/luci-openvpn/luasrc/model/cbi/openvpn.lua
65
3316
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local fs = require "nixio.fs" local sys = require "luci.sys" local uci = require "luci.model.uci".cursor() local m = Map("openvpn", translate("OpenVPN")) local s = m:section( TypedSection, "openvpn", translate("OpenVPN instances"), translate("Below is a list of configured OpenVPN instances and their current state") ) s.template = "cbi/tblsection" s.template_addremove = "openvpn/cbi-select-input-add" s.addremove = true s.add_select_options = { } s.extedit = luci.dispatcher.build_url( "admin", "services", "openvpn", "basic", "%s" ) uci:load("openvpn_recipes") uci:foreach( "openvpn_recipes", "openvpn_recipe", function(section) s.add_select_options[section['.name']] = section['_description'] or section['.name'] end ) function s.parse(self, section) local recipe = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".select" ) if recipe and not s.add_select_options[recipe] then self.invalid_cts = true else TypedSection.parse( self, section ) end end function s.create(self, name) local recipe = luci.http.formvalue( luci.cbi.CREATE_PREFIX .. self.config .. "." .. self.sectiontype .. ".select" ) if name and not name:match("[^a-zA-Z0-9_]") then uci:section( "openvpn", "openvpn", name, uci:get_all( "openvpn_recipes", recipe ) ) uci:delete("openvpn", name, "_role") uci:delete("openvpn", name, "_description") uci:save("openvpn") luci.http.redirect( self.extedit:format(name) ) else self.invalid_cts = true end end s:option( Flag, "enabled", translate("Enabled") ) local active = s:option( DummyValue, "_active", translate("Started") ) function active.cfgvalue(self, section) local pid = fs.readfile("/var/run/openvpn-%s.pid" % section) if pid and #pid > 0 and tonumber(pid) ~= nil then return (sys.process.signal(pid, 0)) and translatef("yes (%i)", pid) or translate("no") end return translate("no") end local updown = s:option( Button, "_updown", translate("Start/Stop") ) updown._state = false function updown.cbid(self, section) local pid = fs.readfile("/var/run/openvpn-%s.pid" % section) self._state = pid and #pid > 0 and sys.process.signal(pid, 0) self.option = self._state and "stop" or "start" return AbstractValue.cbid(self, section) end function updown.cfgvalue(self, section) self.title = self._state and "stop" or "start" self.inputstyle = self._state and "reset" or "reload" end function updown.write(self, section, value) if self.option == "stop" then luci.sys.call("/etc/init.d/openvpn down %s" % section) else luci.sys.call("/etc/init.d/openvpn up %s" % section) end end local port = s:option( DummyValue, "port", translate("Port") ) function port.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) return val or "1194" end local proto = s:option( DummyValue, "proto", translate("Protocol") ) function proto.cfgvalue(self, section) local val = AbstractValue.cfgvalue(self, section) return val or "udp" end return m
gpl-2.0
nasomi/darkstar
scripts/globals/weaponskills/hard_slash.lua
25
1564
----------------------------------- -- Hard Slash -- Great Sword weapon skill -- Skill level: 5 -- Delivers a single-hit attack. Damage varies with TP. -- Modifiers: STR:30% -- 100%TP 200%TP 300%TP -- 1.5 1.75 2.0 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/weaponskills"); function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; --ftp damage mods (for Damage Varies with TP; lines are calculated in the function params.ftp100 = 1.5; params.ftp200 = 1.75; params.ftp300 = 2.0; --wscs are in % so 0.2=20% params.str_wsc = 0.3; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; --critical mods, again in % (ONLY USE FOR params.critICAL HIT VARIES WITH TP) params.crit100 = 0.0; params.crit200=0.0; params.crit300=0.0; params.canCrit = false; --accuracy mods (ONLY USE FOR accURACY VARIES WITH TP) , should be the acc at those %s NOT the penalty values. Leave 0 if acc doesnt vary with tp. params.acc100 = 0; params.acc200=0; params.acc300=0; --attack multiplier (only some WSes use this, this varies the actual ratio value, see Tachi: Kasha) 1 is default. params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
TeamHypersomnia/Augmentations
hypersomnia/content/official/gfx/kek9_magazine.meta.lua
2
2066
return { extra_loadables = { enabled_generate_neon_map = { alpha_multiplier = 1, amplification = 120, light_colors = { "0 255 255 255", "81 1 161 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 = 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 }, strafe_facing_offset = 0 } }, usage_as_button = { bbox_expander = { x = 0, y = 0 }, flip = { horizontally = false, vertically = false } } }
agpl-3.0
EnjoyHacking/nn
VolumetricConvolution.lua
39
1702
local VolumetricConvolution, parent = torch.class('nn.VolumetricConvolution', 'nn.Module') function VolumetricConvolution:__init(nInputPlane, nOutputPlane, kT, kW, kH, dT, dW, dH) parent.__init(self) dT = dT or 1 dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kT = kT self.kW = kW self.kH = kH self.dT = dT self.dW = dW self.dH = dH self.weight = torch.Tensor(nOutputPlane, nInputPlane, kT, kH, kW) self.bias = torch.Tensor(nOutputPlane) self.gradWeight = torch.Tensor(nOutputPlane, nInputPlane, kT, kH, kW) self.gradBias = torch.Tensor(nOutputPlane) -- temporary buffers for unfolding (CUDA) self.finput = torch.Tensor() self.fgradInput = torch.Tensor() self:reset() end function VolumetricConvolution:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kT*self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end function VolumetricConvolution:updateOutput(input) return input.nn.VolumetricConvolution_updateOutput(self, input) end function VolumetricConvolution:updateGradInput(input, gradOutput) return input.nn.VolumetricConvolution_updateGradInput(self, input, gradOutput) end function VolumetricConvolution:accGradParameters(input, gradOutput, scale) return input.nn.VolumetricConvolution_accGradParameters(self, input, gradOutput, scale) end
bsd-3-clause
ZuoGuocai/Atlas
lib/active-queries.lua
40
3780
--[[ $%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%$ --]] -- proxy.auto-config will pick them up local commands = require("proxy.commands") local auto_config = require("proxy.auto-config") --- init the global scope if not proxy.global.active_queries then proxy.global.active_queries = {} end if not proxy.global.max_active_trx then proxy.global.max_active_trx = 0 end -- default config for this script if not proxy.global.config.active_queries then proxy.global.config.active_queries = { show_idle_connections = false } end --- -- track the active queries and dump all queries at each state-change -- function collect_stats() local num_conns = 0 local active_conns = 0 for k, v in pairs(proxy.global.active_queries) do num_conns = num_conns + 1 if v.state ~= "idle" then active_conns = active_conns + 1 end end if active_conns > proxy.global.max_active_trx then proxy.global.max_active_trx = active_conns end return { active_conns = active_conns, num_conns = num_conns, max_active_trx = proxy.global.max_active_trx } end --- -- dump the state of the current queries -- function print_stats(stats) local o = "" for k, v in pairs(proxy.global.active_queries) do if v.state ~= "idle" or proxy.global.config.active_queries.show_idle_connections then local cmd_query = "" if v.cmd then cmd_query = string.format("(%s) %q", v.cmd.type_name, v.cmd.query or "") end o = o .." ["..k.."] (".. v.username .."@".. v.db ..") " .. cmd_query .." (state=" .. v.state .. ")\n" end end -- prepend the data and the stats about the number of connections and trx o = os.date("%Y-%m-%d %H:%M:%S") .. "\n" .. " #connections: " .. stats.num_conns .. ", #active trx: " .. stats.active_conns .. ", max(active trx): ".. stats.max_active_trx .. "\n" .. o print(o) end --- -- enable tracking the packets function read_query(packet) local cmd = commands.parse(packet) local r = auto_config.handle(cmd) if r then return r end proxy.queries:append(1, packet) -- add the query to the global scope local connection_id = proxy.connection.server.thread_id proxy.global.active_queries[connection_id] = { state = "started", cmd = cmd, db = proxy.connection.client.default_db or "", username = proxy.connection.client.username or "" } print_stats(collect_stats()) return proxy.PROXY_SEND_QUERY end --- -- statement is done, track the change function read_query_result(inj) local connection_id = proxy.connection.server.thread_id proxy.global.active_queries[connection_id].state = "idle" proxy.global.active_queries[connection_id].cmd = nil if inj.resultset then local res = inj.resultset if res.flags.in_trans then proxy.global.active_queries[connection_id].state = "in_trans" end end print_stats(collect_stats()) end --- -- remove the information about the connection -- function disconnect_client() local connection_id = proxy.connection.server.thread_id if connection_id then proxy.global.active_queries[connection_id] = nil print_stats(collect_stats()) end end
gpl-2.0
nasomi/darkstar
scripts/zones/Metalworks/npcs/Lucius.lua
19
1882
----------------------------------- -- Area: Metalworks -- NPC: Lucius -- Involved in Mission: Bastok 3-3 -- Involved in Quest: Riding on the Clouds -- @pos 59.959 -17.39 -42.321 237 ----------------------------------- package.loaded["scripts/zones/Metalworks/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Metalworks/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 8) then if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal player:setVar("ridingOnTheClouds_2",0); player:tradeComplete(); player:addKeyItem(SMILING_STONE); player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(BASTOK) == JEUNO_MISSION and player:getVar("MissionStatus") == 0) then player:startEvent(0x0142); else player:startEvent(0x0140); 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 == 0x0142) then player:setVar("MissionStatus",1); player:addKeyItem(LETTER_TO_THE_AMBASSADOR); player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_AMBASSADOR); end end;
gpl-3.0
appaquet/torch-android
src/3rdparty/nn/Reshape.lua
42
1801
local Reshape, parent = torch.class('nn.Reshape', 'nn.Module') function Reshape:__init(...) parent.__init(self) local arg = {...} self.size = torch.LongStorage() self.batchsize = torch.LongStorage() if torch.type(arg[#arg]) == 'boolean' then self.batchMode = arg[#arg] table.remove(arg, #arg) end local n = #arg if n == 1 and torch.typename(arg[1]) == 'torch.LongStorage' then self.size:resize(#arg[1]):copy(arg[1]) else self.size:resize(n) for i=1,n do self.size[i] = arg[i] end end self.nelement = 1 self.batchsize:resize(#self.size+1) for i=1,#self.size do self.nelement = self.nelement * self.size[i] self.batchsize[i+1] = self.size[i] end -- only used for non-contiguous input or gradOutput self._input = torch.Tensor() self._gradOutput = torch.Tensor() end function Reshape:updateOutput(input) if not input:isContiguous() then self._input:resizeAs(input) self._input:copy(input) input = self._input end if (self.batchMode == false) or ( (self.batchMode == nil) and (input:nElement() == self.nelement and input:size(1) ~= 1) ) then self.output:view(input, self.size) else self.batchsize[1] = input:size(1) self.output:view(input, self.batchsize) end return self.output end function Reshape:updateGradInput(input, gradOutput) if not gradOutput:isContiguous() then self._gradOutput:resizeAs(gradOutput) self._gradOutput:copy(gradOutput) gradOutput = self._gradOutput end self.gradInput:viewAs(gradOutput, input) return self.gradInput end function Reshape:__tostring__() return torch.type(self) .. '(' .. table.concat(self.size:totable(), 'x') .. ')' end
bsd-3-clause
nasomi/darkstar
scripts/zones/Chateau_dOraguille/npcs/_6h4.lua
17
3614
----------------------------------- -- Area: Chateau d'Oraguille -- Door: Great Hall -- Involved in Missions: 3-3, 5-2, 6-1, 8-2, 9-1 -- @pos 0 -1 13 233 ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; package.loaded["scripts/globals/missions"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Chateau_dOraguille/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local currentMission = player:getCurrentMission(SANDORIA); local MissionStatus = player:getVar("MissionStatus"); -- Mission San D'Oria 9-2 The Heir to the Light if (currentMission == THE_HEIR_TO_THE_LIGHT and MissionStatus == 5) then player:startEvent(0x0008); -- Mission San D'Oria 9-1 Breaking Barriers elseif (currentMission == BREAKING_BARRIERS and MissionStatus == 4) then if (player:hasKeyItem(FIGURE_OF_TITAN) and player:hasKeyItem(FIGURE_OF_GARUDA) and player:hasKeyItem(FIGURE_OF_LEVIATHAN)) then player:startEvent(0x004c); end elseif (currentMission == BREAKING_BARRIERS and MissionStatus == 0) then player:startEvent(0x0020); -- Mission San D'Oria 8-2 Lightbringer elseif (currentMission == LIGHTBRINGER and MissionStatus == 6) then player:startEvent(0x0068); elseif (currentMission == LIGHTBRINGER and MissionStatus == 0) then player:startEvent(0x0064); -- Mission San D'Oria 6-1 Leaute's Last Wishes elseif (currentMission == LEAUTE_S_LAST_WISHES and MissionStatus == 1) then player:startEvent(87); -- Mission San D'Oria 5-2 The Shadow Lord elseif (currentMission == THE_SHADOW_LORD and MissionStatus == 5) then player:startEvent(0x003D); -- Mission San D'Oria 3-3 Appointment to Jeuno elseif (currentMission == APPOINTMENT_TO_JEUNO and MissionStatus == 2) then player:startEvent(0x0219); else player:startEvent(0x202); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0219) then player:setVar("MissionStatus",3); player:addKeyItem(LETTER_TO_THE_AMBASSADOR); player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_AMBASSADOR); elseif (csid == 0x003D) then finishMissionTimeline(player,3,csid,option); elseif (csid == 87) then player:setVar('MissionStatus',2); elseif (csid == 0x0064) then player:setVar("Mission8-1Completed",0) -- dont need this var anymore. JP midnight is done and prev mission completed. player:setVar("MissionStatus",1); elseif (csid == 0x0068) then player:setVar("Mission8-2Kills",0); finishMissionTimeline(player,3,csid,option); elseif (csid == 0x0008) then player:setVar("MissionStatus",6); elseif (csid == 0x0020) then player:setVar("Cutscenes_8-2",0); -- dont need this var now that mission is flagged and cs have been triggered to progress player:setVar("MissionStatus",1); elseif (csid == 0x004c) then finishMissionTimeline(player,3,csid,option); end end;
gpl-3.0
Hello23-Ygopro/ygopro-ds
expansions/script/c27004165.lua
1
1024
--EX03-13 Son Goku local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableLeaderAttribute(c) ds.AddSetcode(c,CHARACTER_SON_GOKU,SPECIAL_TRAIT_SAIYAN,SPECIAL_TRAIT_UNIVERSE_7,CHARACTER_INCLUDES_SON_GOKU,SPECIAL_TRAIT_INCLUDES_UNIVERSE) --warrior of universe 7 ds.EnableWarriorofUniverse7(c) --draw (bond) ds.EnableBond(c) ds.AddSingleAutoAttack(c,0,nil,ds.hinttg,scard.drop,nil,scard.drcon) --awaken ds.EnableAwaken(c,4,0,2) end scard.dragon_ball_super_card=true scard.leader_back=sid+1 function scard.bondfilter(c) return c:IsBattle() and c:IsSpecialTrait(SPECIAL_TRAIT_UNIVERSE_7) end function scard.drcon(e,tp,eg,ep,ev,re,r,rp) return ds.atlccon(e,tp,eg,ep,ev,re,r,rp) and ds.BondCondition(1,scard.bondfilter)(e,tp,eg,ep,ev,re,r,rp) end function scard.drop(e,tp,eg,ep,ev,re,r,rp) Duel.Draw(tp,1,DS_REASON_SKILL) local c=e:GetHandler() if not c:IsRelateToSkill(e) or c:IsFacedown() then return end --power up ds.GainSkillUpdatePower(c,c,1,5000) end
gpl-3.0
sugao516/gltron-code
levels/movie.lua
1
1310
directions = { random = -1, up = 2, down = 0, right = 1, left = 3 } level = { version = 71, -- scale the level after loading by scale_factor = 1, -- spawn points -- (they don't have to be sorted, they will be randomized anyway) spawn_is_relative = 1, -- relative to bounding box spawn = { { x = .25, y = .5, dir = directions.random }, { x = .5, y = .25, dir = directions.random }, { x = .5, y = .75, dir = directions.random }, { x = .75, y = .5, dir = directions.random } }, floor = { shading = { lit = 0, -- no lighting, only diffuse texture is applied textures = { diffuse = { file = "grey_floor.png", -- file = "uv-debug.png", -- 0: nearest, 1: linear, mag_filter = 1, -- also for min_filter: -- 2: linear_mipmap_nearest -- 3: linear_mipmap_linear min_filter = 3, -- 0: clamp, 1: clamp to edge, 2: repeat wrap_s = 2, wrap_t = 2, -- 1: no filtering, 64: a lot of filtering anisotropic_filtering = 8, texture_scale = 40, } } }, model = "floor.obj", }, arena = { shading = { lit = 1, -- with lighting -- no texture -- passes = 1, -- no outline... passes = 2, -- draws a white/grey outline around the sharp edges }, model = "arena.obj" } } -- level end
gpl-2.0
nasomi/darkstar
scripts/globals/weaponskills/dancing_edge.lua
30
1413
----------------------------------- -- Dancing Edge -- Dagger weapon skill -- Skill level: 200 -- Delivers a fivefold attack. params.accuracy varies with TP. -- Will stack with Sneak Attack. -- Will stack with Trick Attack. -- Aligned with the Breeze Gorget & Soil Gorget. -- Aligned with the Breeze Belt & Soil Belt. -- Element: None -- Modifiers: DEX:30% ; CHR:40% -- 100%TP 200%TP 300%TP -- 1.19 1.19 1.19 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 5; params.ftp100 = 1.1875; params.ftp200 = 1.1875; params.ftp300 = 1.1875; params.str_wsc = 0.0; params.dex_wsc = 0.3; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.4; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.8; params.acc200= 0.9; params.acc300= 1; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.dex_wsc = 0.4; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
nasomi/darkstar
scripts/zones/Horlais_Peak/bcnms/rank_2_mission.lua
17
2321
----------------------------------- -- Area: Horlais Peak -- Name: Mission Rank 2 -- @pos -509 158 -211 139 ----------------------------------- package.loaded["scripts/zones/Horlais_Peak/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Horlais_Peak/TextIDs"); ----------------------------------- -- Maat Battle in Horlais Peak -- EXAMPLE SCRIPT -- -- What should go here: -- giving key items, playing ENDING cutscenes -- -- What should NOT go here: -- Handling of "battlefield" status, spawning of monsters, -- putting loot into treasure pool, -- enforcing ANY rules (SJ/number of people/etc), moving -- chars around, playing entrance CSes (entrance CSes go in bcnm.lua) -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompletedMission(player:getNation(),5)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,0,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then if ((player:getCurrentMission(BASTOK) == THE_EMISSARY_SANDORIA2 or player:getCurrentMission(WINDURST) == THE_THREE_KINGDOMS_SANDORIA2) and player:getVar("MissionStatus") == 9) then player:addKeyItem(KINDRED_CREST); player:messageSpecial(KEYITEM_OBTAINED,KINDRED_CREST); player:setVar("MissionStatus",10); end end end;
gpl-3.0
phcosta29/rstats
lib/socket/tp.lua
51
3766
----------------------------------------------------------------------------- -- Unified SMTP/FTP subsystem -- LuaSocket toolkit. -- Author: Diego Nehab ----------------------------------------------------------------------------- ----------------------------------------------------------------------------- -- Declare module and import dependencies ----------------------------------------------------------------------------- local base = _G local string = require("string") local socket = require("socket") local ltn12 = require("ltn12") socket.tp = {} local _M = socket.tp ----------------------------------------------------------------------------- -- Program constants ----------------------------------------------------------------------------- _M.TIMEOUT = 60 ----------------------------------------------------------------------------- -- Implementation ----------------------------------------------------------------------------- -- gets server reply (works for SMTP and FTP) local function get_reply(c) local code, current, sep local line, err = c:receive() local reply = line if err then return nil, err end code, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) if not code then return nil, "invalid server reply" end if sep == "-" then -- reply is multiline repeat line, err = c:receive() if err then return nil, err end current, sep = socket.skip(2, string.find(line, "^(%d%d%d)(.?)")) reply = reply .. "\n" .. line -- reply ends with same code until code == current and sep == " " end return code, reply end -- metatable for sock object local metat = { __index = {} } function metat.__index:getpeername() return self.c:getpeername() end function metat.__index:getsockname() return self.c:getpeername() end function metat.__index:check(ok) local code, reply = get_reply(self.c) if not code then return nil, reply end if base.type(ok) ~= "function" then if base.type(ok) == "table" then for i, v in base.ipairs(ok) do if string.find(code, v) then return base.tonumber(code), reply end end return nil, reply else if string.find(code, ok) then return base.tonumber(code), reply else return nil, reply end end else return ok(base.tonumber(code), reply) end end function metat.__index:command(cmd, arg) cmd = string.upper(cmd) if arg then return self.c:send(cmd .. " " .. arg.. "\r\n") else return self.c:send(cmd .. "\r\n") end end function metat.__index:sink(snk, pat) local chunk, err = self.c:receive(pat) return snk(chunk, err) end function metat.__index:send(data) return self.c:send(data) end function metat.__index:receive(pat) return self.c:receive(pat) end function metat.__index:getfd() return self.c:getfd() end function metat.__index:dirty() return self.c:dirty() end function metat.__index:getcontrol() return self.c end function metat.__index:source(source, step) local sink = socket.sink("keep-open", self.c) local ret, err = ltn12.pump.all(source, sink, step or ltn12.pump.step) return ret, err end -- closes the underlying c function metat.__index:close() self.c:close() return 1 end -- connect with server and return c object function _M.connect(host, port, timeout, create) local c, e = (create or socket.tcp)() if not c then return nil, e end c:settimeout(timeout or _M.TIMEOUT) local r, e = c:connect(host, port) if not r then c:close() return nil, e end return base.setmetatable({c = c}, metat) end return _M
gpl-3.0
nasomi/darkstar
scripts/globals/items/pogaca.lua
35
1247
----------------------------------------- -- ID: 5637 -- Item: pogaca -- Food Effect: 5Min, All Races ----------------------------------------- -- HP Recovered While Healing 4 -- 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,300,5637); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HPHEAL, 4); target:addMod(MOD_MPHEAL, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HPHEAL, 4); target:delMod(MOD_MPHEAL, 4); end;
gpl-3.0
nasomi/darkstar
scripts/zones/Gustav_Tunnel/mobs/Goblin_Mercenary.lua
23
1026
---------------------------------- -- Area: Gustav Tunnel -- MOB: Goblin Mercenary -- Note: Place holder Wyvernpoacher Drachlox ----------------------------------- require("scripts/zones/Gustav_Tunnel/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) checkGoVregime(killer,mob,764,3); checkGoVregime(killer,mob,765,3); local mob = mob:getID(); if (Wyvernpoacher_Drachlox_PH[mob] ~= nil) then local ToD = GetServerVariable("[POP]Wyvernpoacher_Drachlox"); if (ToD <= os.time(t) and GetMobAction(Wyvernpoacher_Drachlox) == 0) then if (math.random((1),(20)) == 5) then UpdateNMSpawnPoint(Wyvernpoacher_Drachlox); GetMobByID(Wyvernpoacher_Drachlox):setRespawnTime(GetMobRespawnTime(mob)); SetServerVariable("[PH]Wyvernpoacher_Drachlox", mob); DeterMob(mob, true); end end end end;
gpl-3.0
Wouterz90/SuperSmashDota
Game/scripts/vscripts/abilities/batrider.lua
1
12202
batrider_special_side = class({}) function batrider_special_side:OnAbilityPhaseStart() if not self:GetCaster():CanCast(self) then return false end if not self:IsCooldownReady() then return false end local caster = self:GetCaster() caster:EmitSound("Hero_Batrider.Flamebreak") StartAnimation(self:GetCaster(), {duration=self:GetCastPoint(), activity=ACT_DOTA_CAST_ABILITY_2, rate=1}) return true end function batrider_special_side:OnAbilityPhaseInterrupted() -- Cancel animations! local caster = self:GetCaster() caster:StopSound("Hero_Batrider.Flamebreak") EndAnimation(caster) end function batrider_special_side:OnSpellStart() local caster = self:GetCaster() local direction = self.mouseVectorDistance local ability = self StoreSpecialKeyValues(self) local projectile = { --EffectName = "particles/test_particle/ranged_tower_good.vpcf", EffectName = "particles/batrider/batrider_flamebreak.vpcf", --EffectName = "particles/units/heroes/hero_puck/puck_illusory_orb.vpcf", --EeffectName = "", --vSpawnOrigin = caster:GetAbsOrigin(), vSpawnOrigin = {unit=caster, attach="attach_attack1"}, fDistance = (direction *ability.projectile_range):Length(), fStartRadius = ability.projectile_radius, fEndRadius = ability.projectile_radius, Source = caster, fExpireTime = ability.projectile_range/ability.projectile_speed, vVelocity = ability.mouseVector * ability.projectile_speed, -- RandomVector(1000), UnitBehavior = PROJECTILES_DESTROY, bMultipleHits = false, bIgnoreSource = true, TreeBehavior = PROJECTILES_NOTHING, bCutTrees = false, bTreeFullCollision = false, WallBehavior = PROJECTILES_DESTROY, GroundBehavior = PROJECTILES_DESTROY, fGroundOffset = 0, nChangeMax = 1, bRecreateOnChange = true, bZCheck = true, bGroundLock = false, bProvidesVision = true, iVisionRadius = 0, iVisionTeamNumber = caster:GetTeam(), bFlyingVision = false, fVisionTickTime = .1, fVisionLingerDuration = 1, draw = false,-- draw = {alpha=1, color=Vector(200,0,0)}, UnitTest = function(self, unit) return unit:GetUnitName() ~= "npc_dummy_unit" and unit:GetTeamNumber() ~= caster:GetTeamNumber() end, OnUnitHit = function(self, unit) end, OnFinish = function(self,pos) caster:EmitSound("Hero_Batrider.Flamebreak.Impact") self.particle = ParticleManager:CreateParticle("particles/batrider/batrider_flamebreak_explosion.vpcf",PATTACH_ABSORIGIN,caster) ParticleManager:SetParticleControl( self.particle, 3, pos) --ParticleManager:SetParticleControl( self.particle, 2, Vector(ability.explosion_radius*100,0,0)) Timers:CreateTimer(1,function() ParticleManager:DestroyParticle(self.particle,false) ParticleManager:ReleaseParticleIndex(self.particle) end) local units = FindUnitsInRadius(caster:GetTeam(), pos, nil, ability.explosion_radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, 0, false) units = FilterUnitsBasedOnHeight(units,pos,ability.explosion_radius) for k,v in pairs(units) do local damageTable = { victim = v, attacker = caster, damage = ability:GetSpecialValueFor("damage") + RandomInt(0,ability:GetSpecialValueFor("damage_offset")), damage_type = DAMAGE_TYPE_MAGICAL, ability = ability, } local casterLoc = caster:GetAbsOrigin() caster:SetAbsOrigin(pos) ApplyDamage(damageTable) caster:SetAbsOrigin(casterLoc) end end, } Projectiles:CreateProjectile(projectile) end LinkLuaModifier("modifier_batrider_lasso_smash","abilities/batrider.lua",LUA_MODIFIER_MOTION_NONE) batrider_special_bottom = class({}) function batrider_special_bottom:OnAbilityPhaseStart() if not self:GetCaster():CanCast(self) then return false end if not self:IsCooldownReady() then return false end local caster = self:GetCaster() caster:EmitSound("Hero_Batrider.FlamingLasso.Loop") StartAnimation(self:GetCaster(), {duration=self:GetCastPoint(), activity=ACT_DOTA_CAST_ABILITY_2, rate=1}) return true end function batrider_special_bottom:OnAbilityPhaseInterrupted() -- Cancel animations! local caster = self:GetCaster() caster:StopSound("Hero_Batrider.FlamingLasso.Loop") EndAnimation(caster) end function batrider_special_bottom:OnSpellStart() local caster = self:GetCaster() local direction = self.mouseVector local ability = self StoreSpecialKeyValues(self) caster:StopSound("Hero_Batrider.FlamingLasso.Loop") local dummy = CreateUnitByName("npc_dummy_unit",caster:GetAbsOrigin(),false,caster,caster:GetOwner(),caster:GetTeamNumber()) Physics:Unit(dummy) local modifier = dummy:AddNewModifier(caster,self,"modifier_batrider_lasso_smash",{duration = self.search_duration}) dummy:SetAbsOrigin(caster:GetAbsOrigin()) dummy:AddNewModifier(dummy,nil,"modifier_basic",{}) dummy:FindAbilityByName("dummy_unit"):SetLevel(1) modifier.dummy = dummy end modifier_batrider_lasso_smash = class({}) function modifier_batrider_lasso_smash:OnCreated() if IsServer() then StoreSpecialKeyValues(self,self:GetAbility()) self:StartIntervalThink(FrameTime()) self:GetParent():AddNewModifier(self:GetCaster(),self:GetAbility(),"modifier_smash_stun",{}) self.particle = ParticleManager:CreateParticle("particles/units/heroes/hero_batrider/batrider_flaming_lasso.vpcf", PATTACH_CUSTOMORIGIN, self:GetCaster()) ParticleManager:SetParticleControlEnt(self.particle, 0, self:GetCaster(), PATTACH_POINT_FOLLOW, "attach_attack1", self:GetCaster():GetAbsOrigin() + Vector(0,0,50), true) ParticleManager:SetParticleControlEnt(self.particle, 1, self:GetParent(), PATTACH_POINT_FOLLOW, "attach_hitloc", self:GetParent():GetAbsOrigin() + Vector(0,0,0), true) --self:OnIntervalThink() end end function modifier_batrider_lasso_smash:OnIntervalThink() -- If the distance is too big, break_range if (self:GetParent():GetAbsOrigin() - self:GetCaster():GetAbsOrigin()):Length() > self.break_range then self:Destroy() print("DES") return end if (self:GetParent():GetAbsOrigin() - self:GetCaster():GetAbsOrigin()):Length() > self.pull_range then local direction = (self:GetParent():GetAbsOrigin() - self:GetCaster():GetAbsOrigin()):Normalized() self:GetParent():SetStaticVelocity("batrider_lasso",self:GetCaster():GetStaticVelocity() ) --print(self:GetCaster():GetStaticVelocity()) --self:GetParent():SetAbsOrigin(self:GetCaster():GetAbsOrigin() + direction*self.pull_range) end if self:GetParent():GetUnitName() ~= "npc_dummy_unit" then self:GetParent():AddNewModifier(self:GetCaster(),self:GetAbility(),"modifier_no_gravity",{duration = 2* FrameTime()}) --jumpModifiers[self:GetName()] = false -- Damage self.count = (self.count or 5 ) +1 --self.count = self.count +1 if self.count == 6 then local damageTable = { victim = self:GetParent(), attacker = self:GetCaster(), damage = self:GetAbility():GetSpecialValueFor("damage") + RandomInt(0,self:GetAbility():GetSpecialValueFor("damage_offset")), damage_type = DAMAGE_TYPE_MAGICAL, ability = self:GetAbility(), } ApplyDamage(damageTable) self.count = 0 end else -- Search for units to catch --jumpModifiers[self:GetName()] = true local caster = self:GetCaster() local units = FindUnitsInRadius(caster:GetTeam(), self:GetParent():GetAbsOrigin(), nil, self.search_radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, FIND_CLOSEST, false) units = FilterUnitsBasedOnHeight(units,self:GetParent():GetAbsOrigin(),self.search_radius) if units and units[1] then units[1]:EmitSound("Hero_Batrider.FlamingLasso.Cast") units[1]:AddNewModifier(caster,self:GetAbility(),"modifier_batrider_lasso_smash",{duration = self.lasso_duration}) self:Destroy() end end end function modifier_batrider_lasso_smash:OnDestroy() if IsServer() then self:GetParent():RemoveModifierByName("modifier_smash_stun") ParticleManager:DestroyParticle(self.particle,false) ParticleManager:ReleaseParticleIndex(self.particle) self:GetParent():SetStaticVelocity("batrider_lasso",Vector(0,0,0)) if self:GetParent():GetUnitName() == "npc_dummy_unit" then UTIL_Remove(self:GetParent()) end end end LinkLuaModifier("modifier_batrider_firefly_smash","abilities/batrider.lua",LUA_MODIFIER_MOTION_NONE) batrider_special_top = class({}) function batrider_special_top:OnAbilityPhaseStart() if not self:GetCaster():CanCast(self) then return false end if not self:IsCooldownReady() then return false end if self:GetCaster().jumps > 3 then return end local caster = self:GetCaster() caster:EmitSound("Hero_Batrider.Firefly.Cast") StartAnimation(self:GetCaster(), {duration=self:GetCastPoint()*1, activity=ACT_DOTA_CAST_ABILITY_2, rate=1}) return true end function batrider_special_top:OnAbilityPhaseInterrupted() local caster = self:GetCaster() caster:StopSound("Hero_Batrider.Firefly.Cast") EndAnimation(caster) end function batrider_special_top:OnSpellStart() local caster = self:GetCaster() local radius = self:GetSpecialValueFor("radius") StoreSpecialKeyValues(self) caster:AddNewModifier(caster,self,"modifier_batrider_firefly_smash",{duration = self.duration}) caster.jumps = 0 caster:AddNewModifier(caster,self,"modifier_jump",{duration = 1.75}) end modifier_batrider_firefly_smash = class({}) function modifier_batrider_firefly_smash:OnCreated() if IsServer() then StoreSpecialKeyValues(self,self:GetAbility()) self.dummies = {} self:StartIntervalThink(1/30) self:GetCaster():EmitSound("Hero_Batrider.Firefly.loop") end end function modifier_batrider_firefly_smash:OnIntervalThink() local caster = self:GetCaster() local dummy = CreateUnitByName("npc_dummy_unit",caster:GetAbsOrigin(),false,caster,caster:GetOwner(),caster:GetTeamNumber()) dummy:SetAbsOrigin(caster:GetAbsOrigin() + Vector(0,0,150)) dummy:FindAbilityByName("dummy_unit"):SetLevel(1) dummy.particle = ParticleManager:CreateParticle("particles/batrider/batrider_firefly.vpcf",PATTACH_CUSTOMORIGIN,self:GetCaster()) table.insert(self.dummies, dummy) self.targets = {} for k,v in pairs(self.dummies) do ParticleManager:SetParticleControl(dummy.particle,0,dummy:GetAbsOrigin()) local units = FindUnitsInRadius(caster:GetTeam(), v:GetAbsOrigin(), nil, self.radius, DOTA_UNIT_TARGET_TEAM_ENEMY, DOTA_UNIT_TARGET_HERO + DOTA_UNIT_TARGET_BASIC, 0, 0, false) units = FilterUnitsBasedOnHeight(units,v:GetAbsOrigin(),self.radius) for _,unit in pairs(units) do if not self.targets[unit] then self.targets[unit] = true local damageTable = { victim = unit, attacker = self:GetCaster(), damage = 1,--self:GetAbility():GetSpecialValueFor("damage") + RandomInt(0,self:GetAbility():GetSpecialValueFor("damage_offset")), damage_type = DAMAGE_TYPE_MAGICAL, ability = self:GetAbility(), } ApplyDamage(damageTable) local pfx = ParticleManager:CreateParticle("particles/units/heroes/hero_batrider/batrider_firefly_debuff.vpcf",PATTACH_ABSORIGIN_FOLLOW, caster) end end end if not caster:HasModifier("modifier_jump") and not caster:HasModifier("modifier_drop") then Timers:CreateTimer(self.fire_linger_duration,function() if IsValidEntity(self) then self:Destroy() end end) end end function modifier_batrider_firefly_smash:OnDestroy() if IsServer() then self:GetCaster():StopSound("Hero_Batrider.Firefly.loop") for k,v in pairs(self.dummies) do ParticleManager:DestroyParticle(v.particle,false) ParticleManager:ReleaseParticleIndex(v.particle) UTIL_Remove(v) end end end function modifier_batrider_firefly_smash:GetEffectName() return "particles/units/heroes/hero_batrider/batrider_firefly_ember.vpcf" end function modifier_batrider_firefly_smash:GetEffectAttachType() return PATTACH_ABSORIGIN_FOLLOW end
mit
cesarmarinhorj/cgit
filters/gentoo-ldap-authentication.lua
5
7507
-- This script may be used with the auth-filter. Be sure to configure it as you wish. -- -- Requirements: -- luacrypto >= 0.3 -- <http://mkottman.github.io/luacrypto/> -- lualdap >= 1.2 -- <http://git.zx2c4.com/lualdap/about/> -- -- -- -- Configure these variables for your settings. -- -- -- A list of password protected repositories, with which gentooAccess -- group is allowed to access each one. local protected_repos = { glouglou = "infra", portage = "dev" } -- All cookies will be authenticated based on this secret. Make it something -- totally random and impossible to guess. It should be large. local secret = "BE SURE TO CUSTOMIZE THIS STRING TO SOMETHING BIG AND RANDOM" -- -- -- Authentication functions follow below. Swap these out if you want different authentication semantics. -- -- -- Sets HTTP cookie headers based on post and sets up redirection. function authenticate_post() local redirect = validate_value("redirect", post["redirect"]) if redirect == nil then not_found() return 0 end redirect_to(redirect) local groups = gentoo_ldap_user_groups(post["username"], post["password"]) if groups == nil then set_cookie("cgitauth", "") else -- One week expiration time set_cookie("cgitauth", secure_value("gentoogroups", table.concat(groups, ","), os.time() + 604800)) end html("\n") return 0 end -- Returns 1 if the cookie is valid and 0 if it is not. function authenticate_cookie() local required_group = protected_repos[cgit["repo"]] if required_group == nil then -- We return as valid if the repo is not protected. return 1 end local user_groups = validate_value("gentoogroups", get_cookie(http["cookie"], "cgitauth")) if user_groups == nil or user_groups == "" then return 0 end for group in string.gmatch(user_groups, "[^,]+") do if group == required_group then return 1 end end return 0 end -- Prints the html for the login form. function body() html("<h2>Gentoo LDAP Authentication Required</h2>") html("<form method='post' action='") html_attr(cgit["login"]) html("'>") html("<input type='hidden' name='redirect' value='") html_attr(secure_value("redirect", cgit["url"], 0)) html("' />") html("<table>") html("<tr><td><label for='username'>Username:</label></td><td><input id='username' name='username' autofocus /></td></tr>") html("<tr><td><label for='password'>Password:</label></td><td><input id='password' name='password' type='password' /></td></tr>") html("<tr><td colspan='2'><input value='Login' type='submit' /></td></tr>") html("</table></form>") return 0 end -- -- -- Gentoo LDAP support. -- -- local lualdap = require("lualdap") function gentoo_ldap_user_groups(username, password) -- Ensure the user is alphanumeric if username:match("%W") then return nil end local who = "uid=" .. username .. ",ou=devs,dc=gentoo,dc=org" local ldap, err = lualdap.open_simple { uri = "ldap://ldap1.gentoo.org", who = who, password = password, starttls = true, certfile = "/var/www/uwsgi/cgit/gentoo-ldap/star.gentoo.org.crt", keyfile = "/var/www/uwsgi/cgit/gentoo-ldap/star.gentoo.org.key", cacertfile = "/var/www/uwsgi/cgit/gentoo-ldap/ca.pem" } if ldap == nil then return nil end local group_suffix = ".group" local group_suffix_len = group_suffix:len() local groups = {} for dn, attribs in ldap:search { base = who, scope = "subtree" } do local access = attribs["gentooAccess"] if dn == who and access ~= nil then for i, v in ipairs(access) do local vlen = v:len() if vlen > group_suffix_len and v:sub(-group_suffix_len) == group_suffix then table.insert(groups, v:sub(1, vlen - group_suffix_len)) end end end end ldap:close() return groups end -- -- -- Wrapper around filter API, exposing the http table, the cgit table, and the post table to the above functions. -- -- local actions = {} actions["authenticate-post"] = authenticate_post actions["authenticate-cookie"] = authenticate_cookie actions["body"] = body function filter_open(...) action = actions[select(1, ...)] http = {} http["cookie"] = select(2, ...) http["method"] = select(3, ...) http["query"] = select(4, ...) http["referer"] = select(5, ...) http["path"] = select(6, ...) http["host"] = select(7, ...) http["https"] = select(8, ...) cgit = {} cgit["repo"] = select(9, ...) cgit["page"] = select(10, ...) cgit["url"] = select(11, ...) cgit["login"] = select(12, ...) end function filter_close() return action() end function filter_write(str) post = parse_qs(str) end -- -- -- Utility functions based on keplerproject/wsapi. -- -- function url_decode(str) if not str then return "" end str = string.gsub(str, "+", " ") str = string.gsub(str, "%%(%x%x)", function(h) return string.char(tonumber(h, 16)) end) str = string.gsub(str, "\r\n", "\n") return str end function url_encode(str) if not str then return "" end str = string.gsub(str, "\n", "\r\n") str = string.gsub(str, "([^%w ])", function(c) return string.format("%%%02X", string.byte(c)) end) str = string.gsub(str, " ", "+") return str end function parse_qs(qs) local tab = {} for key, val in string.gmatch(qs, "([^&=]+)=([^&=]*)&?") do tab[url_decode(key)] = url_decode(val) end return tab end function get_cookie(cookies, name) cookies = string.gsub(";" .. cookies .. ";", "%s*;%s*", ";") return string.match(cookies, ";" .. name .. "=(.-);") end -- -- -- Cookie construction and validation helpers. -- -- local crypto = require("crypto") -- Returns value of cookie if cookie is valid. Otherwise returns nil. function validate_value(expected_field, cookie) local i = 0 local value = "" local field = "" local expiration = 0 local salt = "" local hmac = "" if cookie == nil or cookie:len() < 3 or cookie:sub(1, 1) == "|" then return nil end for component in string.gmatch(cookie, "[^|]+") do if i == 0 then field = component elseif i == 1 then value = component elseif i == 2 then expiration = tonumber(component) if expiration == nil then expiration = -1 end elseif i == 3 then salt = component elseif i == 4 then hmac = component else break end i = i + 1 end if hmac == nil or hmac:len() == 0 then return nil end -- Lua hashes strings, so these comparisons are time invariant. if hmac ~= crypto.hmac.digest("sha1", field .. "|" .. value .. "|" .. tostring(expiration) .. "|" .. salt, secret) then return nil end if expiration == -1 or (expiration ~= 0 and expiration <= os.time()) then return nil end if url_decode(field) ~= expected_field then return nil end return url_decode(value) end function secure_value(field, value, expiration) if value == nil or value:len() <= 0 then return "" end local authstr = "" local salt = crypto.hex(crypto.rand.bytes(16)) value = url_encode(value) field = url_encode(field) authstr = field .. "|" .. value .. "|" .. tostring(expiration) .. "|" .. salt authstr = authstr .. "|" .. crypto.hmac.digest("sha1", authstr, secret) return authstr end function set_cookie(cookie, value) html("Set-Cookie: " .. cookie .. "=" .. value .. "; HttpOnly") if http["https"] == "yes" or http["https"] == "on" or http["https"] == "1" then html("; secure") end html("\n") end function redirect_to(url) html("Status: 302 Redirect\n") html("Cache-Control: no-cache, no-store\n") html("Location: " .. url .. "\n") end function not_found() html("Status: 404 Not Found\n") html("Cache-Control: no-cache, no-store\n\n") end
gpl-2.0
nasomi/darkstar
scripts/zones/Port_Bastok/npcs/_6k9.lua
34
1073
----------------------------------- -- Area: Port Bastok -- NPC: Door: Arrivals Entrance -- @pos -80 1 -26 236 ----------------------------------- package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Port_Bastok/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x008C); return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Hello23-Ygopro/ygopro-ds
expansions/script/c27004178.lua
1
1550
--EX03-24 Clownish Destruction Belmod local ds=require "expansions.utility_dbscg" local scard,sid=ds.GetID() function scard.initial_effect(c) ds.EnableBattleAttribute(c) ds.AddSetcode(c,SPECIAL_TRAIT_GOD,SPECIAL_TRAIT_UNIVERSE_11,SPECIAL_TRAIT_INCLUDES_UNIVERSE) ds.AddPlayProcedure(c,COLOR_YELLOW,2,2) --barrier ds.EnableBarrier(c) --double strike ds.EnableDoubleStrike(c) --to hand ds.AddSingleAutoPlay(c,0,nil,scard.thtg,scard.thop,DS_EFFECT_FLAG_CARD_CHOOSE) end scard.dragon_ball_super_card=true scard.combo_cost=0 function scard.thtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_DECK) and chkc:IsControler(tp) end if chk==0 then return true end Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription()) local g=Duel.GetDecktopGroup(tp,3) Duel.ConfirmCards(tp,g) Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TOHAND) local sg=g:FilterSelect(tp,Card.IsCanBeSkillTarget,0,1,nil,e) if sg:GetCount()>0 then e:SetLabel(0) Duel.SetTargetCard(sg) else Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_KO) local g=Duel.SelectTarget(tp,ds.BattleAreaFilter(Card.IsRest),tp,0,DS_LOCATION_BATTLE,0,1,nil) e:SetLabel(1) Duel.SetTargetCard(g) end end function scard.thop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if not tc or not tc:IsRelateToSkill(e) then return end local ct=0 if e:GetLabel()==0 then Duel.DisableShuffleCheck() ct=ct+Duel.SendtoHand(tc,PLAYER_OWNER,DS_REASON_SKILL) Duel.ShuffleHand(tp) Duel.SendDecktoptoDrop(tp,2-ct,DS_REASON_SKILL) else Duel.KO(tc,DS_REASON_SKILL) end end
gpl-3.0
nasomi/darkstar
scripts/globals/items/salmon_croute.lua
35
1351
----------------------------------------- -- ID: 4551 -- Item: salmon_croute -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 8 -- MP 8 -- Dexterity 2 -- MP recovered while healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4551); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 8); target:addMod(MOD_MP, 8); target:addMod(MOD_DEX, 2); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 8); target:delMod(MOD_MP, 8); target:delMod(MOD_DEX, 2); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
thesabbir/luci
protocols/luci-proto-relay/luasrc/model/cbi/admin_network/proto_relay.lua
70
1945
-- Copyright 2011 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local map, section, net = ... local ipaddr, network local forward_bcast, forward_dhcp, gateway, expiry, retry, table ipaddr = section:taboption("general", Value, "ipaddr", translate("Local IPv4 address"), translate("Address to access local relay bridge")) ipaddr.datatype = "ip4addr" network = s:taboption("general", DynamicList, "network", translate("Relay between networks")) network.widget = "checkbox" network.exclude = arg[1] network.template = "cbi/network_netlist" network.nocreate = true network.nobridges = true network.novirtual = true network:depends("proto", "relay") forward_bcast = section:taboption("advanced", Flag, "forward_bcast", translate("Forward broadcast traffic")) forward_bcast.default = forward_bcast.enabled forward_dhcp = section:taboption("advanced", Flag, "forward_dhcp", translate("Forward DHCP traffic")) forward_dhcp.default = forward_dhcp.enabled gateway = section:taboption("advanced", Value, "gateway", translate("Use DHCP gateway"), translate("Override the gateway in DHCP responses")) gateway.datatype = "ip4addr" gateway:depends("forward_dhcp", forward_dhcp.enabled) expiry = section:taboption("advanced", Value, "expiry", translate("Host expiry timeout"), translate("Specifies the maximum amount of seconds after which hosts are presumed to be dead")) expiry.placeholder = "30" expiry.datatype = "min(1)" retry = section:taboption("advanced", Value, "retry", translate("ARP retry threshold"), translate("Specifies the maximum amount of failed ARP requests until hosts are presumed to be dead")) retry.placeholder = "5" retry.datatype = "min(1)" table = section:taboption("advanced", Value, "table", translate("Use routing table"), translate("Override the table used for internal routes")) table.placeholder = "16800" table.datatype = "range(0,65535)"
apache-2.0
MatthewDwyer/botman
mudlet/profiles/newbot/scripts/timers/reconnect_timer.lua
1
5357
--[[ 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 --]] function reconnectTimer() local channels -- make sure our test vars exist if botman.APIOffline == nil then botman.APIOffline = true end if botman.APIOfflineCount == nil then botman.APIOfflineCount = 0 end if botman.botOffline == nil then botman.botOffline = true end if botman.botOfflineCount == nil then botman.botOfflineCount = 0 end if botman.telnetOffline == nil then botman.telnetOffline = true end if botman.telnetOfflineCount == nil then botman.telnetOfflineCount = 0 end if botman.lastAPIResponseTimestamp == nil then botman.lastAPIResponseTimestamp = os.time() end if botman.botConnectedTimestamp == nil then botman.botConnectedTimestamp = os.time() end if botman.lastServerResponseTimestamp == nil then botman.lastServerResponseTimestamp = os.time() end if botman.lastTelnetResponseTimestamp == nil then botman.lastTelnetResponseTimestamp = os.time() end -- continue testing if botman.telnetOffline and not server.telnetDisabled then botman.telnetOfflineCount = tonumber(botman.telnetOfflineCount) + 1 end if (server.useAllocsWebAPI and botman.APIOffline) and (tonumber(botman.telnetOfflineCount) > 1 and not server.telnetDisabled) and tonumber(botman.playersOnline) > 0 then botman.botOffline = true end if botman.botOffline then botman.botOfflineCount = tonumber(botman.botOfflineCount) + 1 end if (not botman.botOffline) and server.useAllocsWebAPI and (os.time() - botman.lastAPIResponseTimestamp > 60) and tonumber(server.webPanelPort) > 0 and server.allocs and tonumber(botman.playersOnline) > 0 then server.allocsWebAPIPassword = (rand(100000) * rand(5)) + rand(10000) send("webtokens add bot " .. server.allocsWebAPIPassword .. " 0") botman.lastBotCommand = "webtokens add bot" conn:execute("UPDATE server set allocsWebAPIUser = 'bot', allocsWebAPIPassword = '" .. escape(server.allocsWebAPIPassword) .. "', useAllocsWebAPI = 1") botman.APIOffline = false toggleTriggers("api online") end if (not botman.botOffline) and server.useAllocsWebAPI and tonumber(botman.APIOfflineCount) > 5 and tonumber(server.webPanelPort) > 0 and server.allocs then if server.telnetFallback then -- don't let the bot stop trying to use Alloc's web API unless telnetFallback is enabled. if botman.APIOffline and not server.telnetDisabled then -- switch to using telnet server.useAllocsWebAPI = false conn:execute("UPDATE server set useAllocsWebAPI = 0") toggleTriggers("api offline") end end end -- if (os.time() - botman.lastTelnetResponseTimestamp > 600) and not server.telnetDisabled then -- botman.telnetOffline = true -- end -- if (os.time() - botman.lastTelnetResponseTimestamp) > 540 and not server.telnetDisabled and not botman.worldGenerating then -- send("gt") -- end -- if tonumber(botman.botOfflineCount) > 180 then -- if server.allowBotRestarts then -- restartBot() -- return -- end -- end if (botman.telnetOffline or botman.botOffline) and not server.telnetDisabled then if botman.telnetOffline then irc_chat(server.ircMain, "Bot is not connected to telnet - attempting reconnection.") else irc_chat(server.ircMain, "Bot is offline - attempting reconnection.") end if tonumber(server.telnetPort) > 0 then connectToServer(server.IP, server.telnetPort) else reconnect() end return end -- if os.time() - botman.lastServerResponseTimestamp > 60 and botman.botOffline and not server.telnetDisabled then -- irc_chat(server.ircMain, "Bot is offline - attempting reconnection to telnet.") -- if tonumber(server.telnetPort) > 0 then -- connectToServer(server.IP, server.telnetPort) -- else -- reconnect() -- end -- return -- end -- if tonumber(botman.telnetOfflineCount) > 3 and not server.telnetDisabled then -- irc_chat(server.ircMain, "Bot is not connected to telnet - attempting reconnection.") -- if tonumber(server.telnetPort) > 0 then -- connectToServer(server.IP, server.telnetPort) -- else -- reconnect() -- end -- return -- end -- if tonumber(botman.botOfflineCount) > 0 then -- if tonumber(botman.botOfflineCount) < 16 then -- irc_chat(server.ircMain, "Bot is offline - attempting reconnection.") -- if tonumber(server.telnetPort) > 0 then -- connectToServer(server.IP, server.telnetPort) -- else -- reconnect() -- end -- else -- if (botman.botOfflineCount % 20 == 0) then -- irc_chat(server.ircMain, "Bot is offline - attempting reconnection.") -- if tonumber(server.telnetPort) > 0 then -- connectToServer(server.IP, server.telnetPort) -- else -- reconnect() -- end -- end -- end -- return -- end if server.useAllocsWebAPI and not botman.botOffline then botman.APIOfflineCount = tonumber(botman.APIOfflineCount) + 1 end if ircGetChannels ~= nil then channels = ircGetChannels() if channels == "" then joinIRCServer() return end end if type(server) == "table" and type(modVersions) ~= "table" then importModVersions() end end
gpl-3.0
sayakbiswas/CloudLang
CloudLangNeuralNets/Parsing/neural_net_model.lua
1
11292
require('torch') require('util') require('nn') require('math') require('optim') local PowConstant, parent = torch.class('nn.PowConstant', 'nn.Module') function PowConstant:__init(constant_scalar) parent.__init(self) assert(type(constant_scalar) == 'number', 'Power needs to be scalar') assert(constant_scalar > 1, 'Power should be > 1') self.constant_scalar = constant_scalar end function PowConstant:updateOutput(input) self.output:resizeAs(input) self.output:copy(input) self.output:pow(self.constant_scalar) return self.output end function PowConstant:updateGradInput(input, gradOutput) self.gradInput:resizeAs(gradOutput) self.gradInput:copy(gradOutput) self.gradInput:mul(self.constant_scalar) self.gradInput:cmul(torch.pow(input, self.constant_scalar-1)) return self.gradInput end local _LinearWithoutBias = torch.class('nn.LinearWithoutBias', 'nn.Linear') function _LinearWithoutBias:updateOutput(input) if input:dim() == 2 then local nframe = input:size(1) local nElement = self.output:nElement() self.output:resize(nframe, self.bias:size(1)) if self.output:nElement() ~= nElement then self.output:zero() end self.output:addmm(0, self.output, 1, input, self.weight:t()) else error('Wrong input') end return self.output end function _LinearWithoutBias:accGradParameters(input, gradOutput, scale) scale = scale or 1 if input:dim() == 2 then self.gradWeight:addmm(scale, gradOutput:t(), input) else error('Wrong Input') end end function _LinearWithoutBias:parameters() return {self.weight}, {self.gradWeight} end function transition_parser_neuralnet(label_num, embedding_dims, embedding_num, hidden_num, class_num, probabilistic, dropProb) local mlp = nn.Sequential() local lookup_table = nn.LookupTable(label_num, embedding_dims) mlp:add(lookup_table) local dims = embedding_dims*embedding_num mlp:add(nn.View(-1, dims)) if type(hidden_num) ~= 'table' then hidden_num = {hidden_num,} end local hidden_layers = {} local lastDims = dims for i = 1, #hidden_num do hidden_layers[i] = nn.Linear(lastDims, hidden_num[i]) mlp:add(hidden_layers[i]) mlp:add(nn.PowConstant(3)) lastDims = hidden_num[i] end if dropProb then mlp:add(nn.Dropout(dropProb)) end local output_layer = nn.LinearWithoutBias(lastDims, class_num) mlp:add(output_layer) if probabilistic then mlp:add(nn.LogSoftMax()) end mlp.get_lookup_table = function() return lookup_table end mlp.get_hidden_layers = function() return hidden_layers end mlp.get_output_layer = function() return output_layer end return mlp end local MaskLayer, Parent = torch.class('nn.MaskLayer', 'nn.Module') function MaskLayer:__init(masks, filler) Parent.__init(self) self.filler = filler or 0 self.masks = masks self.batch_masks = torch.ByteTensor() end function MaskLayer:updateOutput(input) local data = input[1] local states = input[2] self.batch_masks:index(self.masks, 1, states) self.output:resizeAs(data):fill(self.filler) self.output[self.batch_masks] = data[self.batch_masks] return self.output end function MaskLayer:updateGradInput(input, gradOutput) self.gradInput = {gradOutput} return self.gradInput end function MaskLayer:__tostring__() return string.format('%s(%f)', torch.type(self), self.filler) end function MaskLayer:type(type_, tensorCache) if type_ == 'torch.CudaTensor' then self.masks = self.masks:cuda() self.batch_masks = self.batch_masks:cuda() self.output = self.output:cuda() else self.masks = self.masks:byte() self.batch_masks = self.batch_masks:byte() self.output = self.output:type(type_) end end function mask_neural_net(core, masks, probabilistic) local mlp = nn.Sequential() local para = nn.ParallelTable() para:add(core) para:add(nn.Identity()) mlp:add(para) mlp:add(nn.MaskLayer(masks, -math.huge)) if probabilistic then mlp:add(nn.LogSoftMax()) end mlp.get_core = function() return core end mlp.get_lookup_table = function() return core:get_lookup_table() end mlp.get_hidden_layers = function() return core:get_hidden_layers() end mlp.get_output_layer = function() return core:get_output_layer() end return mlp end function shuffle_data(x, y, sx, sy) local indices = torch.randperm(y:size(1)):long() if torch.isTensor(x) then if sx then sx:index(x, 1, indices) else sx = x:index(1, indices) end else if sx then for k, v in pairs(x) do sx[k]:index(x[k], 1, indices) end else sx = {} for k, v in pairs(x) do sx[k] = x[k]:index(1, indices) end end end if sy then sy:index(y, 1, indices) else sy = y:index(1, indices) end return sx, sy end function narrow_tensors(x, dim, start, size) if type(x) == 'table' then local ret = {} for k = 1, #x do ret[k] = x[k]:narrow(1, start, size) end return ret end return x:narrow(1, start, size) end function batch_randomize(x, y, batch_size) local batch_start = torch.random(math.max(y:size(1)-batch_size+1, 1)) local actual_size = math.min(batch_size, y:size(1)-batch_start+1) local batch_x = narrow_tensors(x, 1, batch_start, actual_size) local batch_y = y:narrow(1, batch_start, actual_size) return batch_x, batch_y end function train_model(nn_config, train_x, train_y, valid_x, valid_y, initRange) print(string.format("Training %s...", nn_config.model_name)) local start = os.time() local example_count = 0 local batch_count = math.max(train_y:size(1)/nn_config.training_batch_size, 1) local best_valid_cost = nil local params, grad_params = nn_config.mlp:getParameters() local params2 = torch.Tensor():typeAs(params) local train_sx, train_sy local feval = function() nn_config.mlp:training() local batch_x, batch_y = batch_randomize(train_sx, train_sy, nn_config.training_batch_size) local cost = nn_config.criterion:forward(nn_config.mlp:forward(batch_x), batch_y) assert(tostring(cost) ~= 'nan' and not tostring(cost):find('inf')) grad_params:zero() nn_config.mlp:backward(batch_x, nn_config.criterion:backward(nn_config.mlp.output, batch_y)) if nn_config.l1_weight and nn_config.l1_weight > 0 then for _, h in ipairs(nn_config.mlp:get_hidden_layers()) do cost = cost + torch.abs(h.weight):sum() * nn_config.l1_weight h.gradWeight:add(nn_config.l1_weight, torch.sign(h.weight)) end end if nn_config.l2_weight and nn_config.l2_weight > 0 then cost = cost + params2:pow(params, 2):sum() * nn_config.l2_weight / 2 grad_params:add(nn_config.l2_weight, params) end if nn_config.max_grad and nn_config.max_grad > 0 then grad_params:clamp(-nn_config.max_grad, nn_config.max_grad) end return cost, grad_params end local compute_cost = function(x, y) nn_config.mlp:evaluate() local cost = 0 local batch_count = math.max(y:size(1)/nn_config.monitoring_batch_size, 1) for i = 1, batch_count do local batch_start = (i-1)*nn_config.monitoring_batch_size + 1 local actual_batch_size = math.min(nn_config.monitoring_batch_size, y:size(1) - batch_start + 1) local batch_x = narrow_tensors(x, 1, batch_start, actual_batch_size) local batch_y = y:narrow(1, batch_start, actual_batch_size) local c = nn_config.criterion:forward(nn_config.mlp:forward(batch_x), batch_y) cost = cost + c * actual_batch_size end cost = cost / y:size(1) if nn_config.l1_weight and nn_config.l1_weight > 0 then for _, h in ipairs(nn_config.mlp:get_hidden_layers()) do cost = cost + torch.abs(h.weight):sum() * nn_config.l1_weight end end if nn_config.l2_weight and nn_config.l2_weight > 0 then cost = cost + params2:pow(params, 2):sum() * nn_config.l2_weight / 2 end return cost end local optim_state = { learningRate = nn_config.learningRate, learningRateDecay = nn_config.learningRateDecay, weightDecay = 0, momentum = 0, } assert(optim_state.learningRate > 0) assert(optim_state.learningRateDecay >= 0) if initRange then params:uniform(-initRange, initRange) end for epoch_count = 1, nn_config.max_epochs do train_sx, train_sy = shuffle_data(train_x, train_y, train_sx, train_sy) for batch_no = 1, batch_count do optim.adagrad(feval, params, optim_state) example_count = example_count + nn_config.training_batch_size if nn_config.batch_reporting_frequency > 0 and batch_no % nn_config.batch_reporting_frequency == 0 then local speed = example_count / (os.time()-start) io.write(string.format("Batch %d, speed = %.2f examples/s\r", batch_no, speed)) end end if nn_config.batch_reporting_frequency > 0 and batch_count >= nn_config.batch_reporting_frequency then io.write('\n') end collectgarbage() if nn_config.epoch_reporting_frequency > 0 and epoch_count % nn_config.epoch_reporting_frequency == 0 then print(string.format("Epoch %d:", epoch_count)) print(string.format("\tTraining cost: %f", compute_cost(train_sx, train_sy))) if valid_x ~= nil and valid_y ~= nil then print(string.format("\tValidation cost: %f", compute_cost(valid_x, valid_y))) end print(string.format("\tTime elapsed: %d s", os.time()-start)) end if valid_x and valid_y and nn_config.best_path then local valid_cost = compute_cost(valid_x, valid_y) if best_valid_cost == nil or best_valid_cost > valid_cost then io.write(string.format('Saving best model until now to %s... ', nn_config.best_path)) torch.save(nn_config.best_path, nn_config.mlp) best_valid_cost = valid_cost print('Done.') end end end if valid_x ~= nil and valid_y ~= nil and nn_config.best_path ~= nil then io.write(string.format('Loading from %s... ', nn_config.best_path)) nn_config.best_mlp = torch.load(nn_config.best_path) print('Done.') end local stop = os.time() print(string.format("Training %s... Done (%.2f min).", nn_config.model_name, (stop-start)/60.0)) end
mit
anthillsocial/bicrophonic1
lib/random.lua
2
1528
-- Swamp Bike Opera embedded system for Kaffe Matthews -- Copyright (C) 2012 Wolfgang Hauptfleisch, Dave Griffiths -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 3 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. module("random", package.seeall) require 'posix' require 'socket' function by_probability(probability) local hey = math.random(1, 100) if hey <= probability then return true end return false end function now() local d = { HOUR_OF_DAY = tonumber(os.date("%H")) , DAY_OF_WEEK = tonumber(os.date("%w")) , DAY_OF_MONTH = tonumber(os.date("%d")) , MONTH_OF_YEAR = tonumber(os.date("%m")) } return d end function animal() local a = math.random(31, 39) return a end function channel() local a = math.random(1,2) local channel if a == 1 then channel = "left" else channel = "right" end return channel end --print(now().HOUR_OF_DAY) --print(now().DAY_OF_MONTH) --print(now().MONTH_OF_YEAR) --print(now().DAY_OF_WEEK)
gpl-2.0
icplus/OP-SDK
package/ramips/ui/luci-mtk/src/applications/luci-statistics/luasrc/model/cbi/luci_statistics/ping.lua
80
1397
--[[ Luci configuration model for statistics - collectd ping plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("Ping Plugin Configuration"), translate( "The ping plugin will send icmp echo replies to selected " .. "hosts and measure the roundtrip time for each host." )) -- collectd_ping config section s = m:section( NamedSection, "collectd_ping", "luci_statistics" ) -- collectd_ping.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_ping.hosts (Host) hosts = s:option( Value, "Hosts", translate("Monitor hosts"), translate ("Add multiple hosts separated by space.")) hosts.default = "127.0.0.1" hosts:depends( "enable", 1 ) -- collectd_ping.ttl (TTL) ttl = s:option( Value, "TTL", translate("TTL for ping packets") ) ttl.isinteger = true ttl.default = 128 ttl:depends( "enable", 1 ) -- collectd_ping.interval (Interval) interval = s:option( Value, "Interval", translate("Interval for pings"), translate ("Seconds") ) interval.isinteger = true interval.default = 30 interval:depends( "enable", 1 ) return m
gpl-2.0
nasomi/darkstar
scripts/zones/Davoi/npcs/_45j.lua
19
2049
----------------------------------- -- Area: Davoi -- NPC: Screaming Pond -- Used In Quest: Whence Blows the Wind -- @pos -219 0.1 -101 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(0x0035); 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 == 0x0035 and player:getVar("miniQuestForORB_CS") == 1) then local c = player:getVar("countRedPoolForORB"); if (c == 0) then player:setVar("countRedPoolForORB", c + 4); player:delKeyItem(WHITE_ORB); player:addKeyItem(PINK_ORB); player:messageSpecial(KEYITEM_OBTAINED, PINK_ORB); elseif (c == 1 or c == 2 or c == 8) then player:setVar("countRedPoolForORB", c + 4); player:delKeyItem(PINK_ORB); player:addKeyItem(RED_ORB); player:messageSpecial(KEYITEM_OBTAINED, RED_ORB); elseif (c == 3 or c == 9 or c == 10) then player:setVar("countRedPoolForORB", c + 4); player:delKeyItem(RED_ORB); player:addKeyItem(BLOOD_ORB); player:messageSpecial(KEYITEM_OBTAINED, BLOOD_ORB); elseif (c == 11) then player:setVar("countRedPoolForORB", c + 4); 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
haka-security/haka
lib/haka/lua/lua/list.lua
5
5137
-- This Source Code Form is subject to the terms of the Mozilla Public -- License, v. 2.0. If a copy of the MPL was not distributed with this -- file, You can obtain one at http://mozilla.org/MPL/2.0/. local module = {} local class = require('class') local check = require('check') local color = require('color') local list = class.class('list') local function format_list(headers, formatter, indent, print, content, extra) local column_size = {} local content_disp = {} local sep = ' | ' indent = indent or '' for i,_ in ipairs(content) do content_disp[i] = {} end if extra then content_disp[#content_disp+1] = {} end for _,h in ipairs(headers) do local max = #h local f = formatter and formatter[h] or tostring local value for i,r in ipairs(content) do value = f(r[h]) content_disp[i][h] = value local size = #value if size > max then max = size end end if extra then value = f(extra[h]) content_disp[#content_disp][h] = value local size = #value if size > max then max = size end end column_size[h] = max end local row = {} row[1] = '' for i,h in ipairs(headers) do row[1+3*i-2] = string.format("%s%s%s%s", color.blue, color.bold, h, color.clear) row[1+3*i-1] = string.rep(' ', column_size[h]-#h) row[1+3*i] = sep end print(table.concat(row)) row[1] = indent for _,r in ipairs(content_disp) do for i,h in ipairs(headers) do local value = r[h] row[1+3*i-2] = value row[1+3*i-1] = string.rep(' ', column_size[h]-#value) row[1+3*i] = sep end print(table.concat(row)) end end function list.method:__init() rawset(self, '_data', {}) end function list.method:__len(self) local data = rawget(self, '_data') if data then return #self._data end end function list.method:__pprint(indent, print) format_list(class.classof(self).field, class.classof(self).field_format, indent, print, self._data, self:_aggregate()) end function list.method:print() format_list(class.classof(self).field, class.classof(self).field_format, '', print, self._data, self:_aggregate()) end function list.method:filter(f) check.type(1, f, 'function') local newdata = {} for _,r in ipairs(rawget(self, '_data') or {}) do if f(r) then table.insert(newdata, r) end end self._data = newdata return self end function list.method:sort(order, invert) check.types(1, order, {'string', 'function'}) local data = rawget(self, '_data') if data then if type(order) == 'function' then if invert then table.sort(data, function (a, b) return not order(a, b) end) else table.sort(data, order) end else local found = false for _,field in ipairs(class.classof(self).field) do if field == order then found = true break end end if not found then check.error(string.format("order '%s' is not a valid key", order)) end if invert then table.sort(data, function(a, b) return a[order] > b[order] end) else table.sort(data, function(a, b) return a[order] < b[order] end) end end end return self end function list.method:add(data) table.append(rawget(self, '_data'), data) end function list.method:addall(data) for _,d in ipairs(data) do self:add(d) end end function list.method:_aggregate_one(field) local aggregator = class.classof(self).field_aggregate if aggregator and aggregator[field] then local values = {} for _,r in ipairs(self._data) do values[#values+1] = r[field] end return aggregator[field](values) end end function list.method:_aggregate() local aggregator = class.classof(self).field_aggregate local data = rawget(self, '_data') if aggregator and data and #data > 1 then local agg = {} for _,h in ipairs(class.classof(self).field) do agg[h] = self:_aggregate_one(h) or '' end return agg end end function list.method:get(name) check.types(1, name, {'string', 'number'}) local data = rawget(self, '_data') if data then local key = class.classof(self).key for _,r in ipairs(data) do if r[key] == name then local ret = class.classof(self):new() ret._data = { r } return ret end end end end function list.method:__index(name) local data = rawget(self, '_data') if data then if #data == 1 then return data[1][name] else return self:_aggregate_one(name) end end end function module.new(name) return class.class(name, list) end -- -- Formatter -- module.formatter = {} local num_units = { 'k', 'M', 'G', 'T' } function module.formatter.unit(num) if not num or num < 1000 then return tostring(num) end for _,u in ipairs(num_units) do num = num / 1000 if num < 1000 then return string.format("%.2f%s", num, u) end end return string.format("%.2f%s", num, num_units[#num_units]) end function module.formatter.optional(default) return function (val) if val then return val else return default end end end -- -- Aggregation -- module.aggregator = {} function module.aggregator.add(nums) local sum = 0 for _,n in ipairs(nums) do sum = sum + n end return sum end function module.aggregator.replace(value) return function (nums) return value end end return module
mpl-2.0
nasomi/darkstar
scripts/zones/Northern_San_dOria/npcs/Gilipese.lua
38
1026
----------------------------------- -- Area: Northern San d'Oria -- NPC: Gilipese -- Type: Standard Dialogue NPC -- @zone: 231 -- @pos -155.088 0.000 120.300 -- ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,GILIPESE_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Wouterz90/SuperSmashDota
Game/scripts/vscripts/examples/playground.lua
7
20225
--[[ This file is an example scenario showing a number of ways to make use of the containers.lua library. It works based on the "playground" map provided with barebones. This code creates several containers: 1) A backpack container for every hero in the game. This container has an item within their normal inventory which when used/cast opens/closes the corresponding container. 2) An equipment container for every hero in the game. This container has an item within their normal inventory which when used/cast opens/closes the corresponding container. There are 3 item slots in this container: a helmet slot, a chest armor slot, and a boots slot. Putting valid items into the correct slot will equip them and apply the passive associated with them (similar to the standard dota inventory). 3) Loot Boxes which are 2x2 boxes that spawn on the map and can be looted by each player. 4) Private Bank containers for each player, represented by a stone chest in the game world. Opening this container by right clicking it shows the private bank of the player that clicked it. 5) Shared Bank container represented by a wooden treasure chest. Opening and using this container is shared among all players. 6) Item-based Shop container represented by a golden treasure chest. This shop is availble to all players. 7) Team-based Unit-based shops. There is one team-shop for radiant (Ancient Apparition) and one for dire (Enigma). These shops can be inspected by left clicking them to select them from any distance. 8) Crafting Materials container represented by a wooden crate. 9) Crafting Station container represented by a workbench/table which allows for crafting things in a Minecraft-style. The only recipe built-in is branch+claymore+broadsword makes a battlefury (when properly oriented) ]] if GetMapName() == "playground" then if not PlayGround then PlayGround = {} end function RandomItem(owner) local id = RandomInt(1,29) local name = Containers.itemIDs[id] return CreateItem(name, owner, owner) end function CreateLootBox(loc) local phys = CreateItemOnPositionSync(loc:GetAbsOrigin(), nil) phys:SetForwardVector(Vector(0,-1,0)) phys:SetModelScale(1.5) local items = {} local slots = {1,2,3,4} for i=1,RandomInt(1,3) do items[table.remove(slots, RandomInt(1,#slots))] = RandomItem() end local cont = Containers:CreateContainer({ layout = {2,2}, --skins = {"Hourglass"}, headerText = "Loot Box", buttons = {"Take All"}, position = "entity", --"mouse",--"900px 200px 0px", OnClose = function(playerID, container) print("Closed") if next(container:GetAllOpen()) == nil and #container:GetAllItems() == 0 then container:GetEntity():RemoveSelf() container:Delete() loc.container = nil Timers:CreateTimer(7, function() CreateLootBox(loc) end) end end, OnOpen = function(playerID, container) print("Loot box opened") end, closeOnOrder= true, items = items, entity = phys, range = 150, --OnButtonPressedJS = "ExampleButtonPressed", OnButtonPressed = function(playerID, container, unit, button, buttonName) if button == 1 then local items = container:GetAllItems() for _,item in ipairs(items) do container:RemoveItem(item) Containers:AddItemToUnit(unit,item) end container:Close(playerID) end end, OnEntityOrder = function(playerID, container, unit, target) print("ORDER ACTION loot box: ", playerID) container:Open(playerID) unit:Stop() end }) loc.container = cont loc.phys = phys end function CreateShop(ii) local sItems = {} local prices = {} local stocks = {} for _,i in ipairs(ii) do item = CreateItem(i[1], unit, unit) local index = item:GetEntityIndex() sItems[#sItems+1] = item if i[2] ~= nil then prices[index] = i[2] end if i[3] ~= nil then stocks[index] = i[3] end end return sItems, prices, stocks end function PlayGround:OnFirstPlayerLoaded() Containers:SetItemLimit(100) -- default item limit is 24 for dota. Once a unit owns more items than that, they would be unable to buy them from the dota shops Containers:UsePanoramaInventory(true) -- create initial stuff lootSpawns = Entities:FindAllByName("loot_spawn") itemDrops = Entities:FindAllByName("item_drops") contShopRadEnt = Entities:FindByName(nil, "container_shop_radiant") contShopDireEnt = Entities:FindByName(nil, "container_shop_dire") privateBankEnt = Entities:FindByName(nil, "private_bank") sharedBankEnt = Entities:FindByName(nil, "shared_bank") itemShopEnt = Entities:FindByName(nil, "item_shop") craftingEnt = Entities:FindByName(nil, "crafting_station") craftingMatsEnt = Entities:FindByName(nil, "crafting_mats") privateBankEnt = CreateItemOnPositionSync(privateBankEnt:GetAbsOrigin(), nil) privateBankEnt:SetModel("models/props_debris/merchant_debris_chest002.vmdl") privateBankEnt:SetModelScale(1.8) privateBankEnt:SetForwardVector(Vector(-1,0,0)) craftingEnt = CreateItemOnPositionSync(craftingEnt:GetAbsOrigin(), nil) craftingEnt:SetModel("models/props_structures/bad_base_shop002.vmdl") craftingEnt:SetForwardVector(Vector(-1,0,0)) craftingMatsEnt = CreateItemOnPositionSync(craftingMatsEnt:GetAbsOrigin(), nil) craftingMatsEnt:SetModel("models/props_debris/shop_set_cage001.vmdl") craftingMatsEnt:SetForwardVector(Vector(1,0,0)) local all = {} for i=0,23 do all[#all+1] = i end sharedBankEnt = CreateItemOnPositionSync(sharedBankEnt:GetAbsOrigin(), nil) sharedBankEnt:SetModel("models/props_debris/merchant_debris_chest001.vmdl") sharedBankEnt:SetModelScale(2.3) sharedBankEnt:SetForwardVector(Vector(-1,0,0)) sharedBank = Containers:CreateContainer({ layout = {6,4,4,6}, headerText = "Shared Bank", pids = all, position = "entity", --"600px 400px 0px", entity = sharedBankEnt, closeOnOrder= true, range = 230, OnEntityOrder=function(playerID, container, unit, target) print("ORDER ACTION shared bank: ", playerID) container:Open(playerID) unit:Stop() end, OnEntityDrag= function(playerID, container, unit, target, fromContainer, item) print("Drag ACTION shared bank: ", playerID, unit, target, fromContainer, item) if IsValidEntity(target) and fromContainer:ContainsItem(item) then fromContainer:RemoveItem(item) if not container:AddItem(item) then CreateItemOnPositionSync(unit:GetAbsOrigin() + RandomVector(10), item) end end unit:Stop() end }) itemShopEnt = CreateItemOnPositionSync(itemShopEnt:GetAbsOrigin(), nil) itemShopEnt:SetModel("models/props_gameplay/treasure_chest001.vmdl") itemShopEnt:SetModelScale(2.7) itemShopEnt:SetForwardVector(Vector(-1,0,0)) local ii = {} for i=0,RandomInt(4,8) do local inner = {Containers.itemIDs[RandomInt(1,29)], RandomInt(8,200)*10} if RandomInt(0,1) == 1 then inner[3] = RandomInt(3,15) end table.insert(ii, inner) end local sItems,prices,stocks = CreateShop(ii) itemShop = Containers:CreateShop({ layout = {3,3,3}, skins = {}, headerText = "Item Shop", pids = {}, position = "entity", --"1000px 300px 0px", entity = itemShopEnt, items = sItems, prices = prices, stocks = stocks, closeOnOrder= true, range = 230, OnEntityOrder=function(playerID, container, unit, target) print("ORDER ACTION item shop", playerID) container:Open(playerID) unit:Stop() end, }) contShopRadEnt = CreateUnitByName("npc_dummy_unit", contShopRadEnt:GetAbsOrigin(), false, nil, nil, DOTA_TEAM_GOODGUYS) contShopRadEnt:AddNewModifier(viper, nil, "modifier_shopkeeper", {}) contShopRadEnt:SetModel("models/heroes/ancient_apparition/ancient_apparition.vmdl") contShopRadEnt:SetOriginalModel("models/heroes/ancient_apparition/ancient_apparition.vmdl") contShopRadEnt:StartGesture(ACT_DOTA_IDLE) contShopRadEnt:SetForwardVector(Vector(1,0,0)) sItems,prices,stocks = CreateShop({ {"item_quelling_blade", 150, 3}, {"item_quelling_blade"}, {"item_clarity"}, {"item_bfury", 9000}, }) sItems[3]:SetCurrentCharges(2) contRadiantShop = Containers:CreateShop({ layout = {2,2,2,2,2}, skins = {}, headerText = "Radiant Shop", pids = {}, position = "entity", --"1000px 300px 0px", entity = contShopRadEnt, items = sItems, prices = prices, stocks = stocks, closeOnOrder= true, range = 300, --OnCloseClickedJS = "ExampleCloseClicked", OnSelect = function(playerID, container, selected) print("Selected", selected:GetUnitName()) if PlayerResource:GetTeam(playerID) == DOTA_TEAM_GOODGUYS then container:Open(playerID) end end, OnDeselect = function(playerID, container, deselected) print("Deselected", deselected:GetUnitName()) if PlayerResource:GetTeam(playerID) == DOTA_TEAM_GOODGUYS then container:Close(playerID) end end, OnEntityOrder=function(playerID, container, unit, target) print("ORDER ACTION radiant shop", playerID) if PlayerResource:GetTeam(playerID) == DOTA_TEAM_GOODGUYS then container:Open(playerID) unit:Stop() else Containers:DisplayError(playerID, "#dota_hud_error_unit_command_restricted") end end, }) contShopDireEnt = CreateUnitByName("npc_dummy_unit", contShopDireEnt:GetAbsOrigin(), false, nil, nil, DOTA_TEAM_BADGUYS) contShopDireEnt:AddNewModifier(viper, nil, "modifier_shopkeeper", {}) contShopDireEnt:SetModel("models/heroes/enigma/enigma.vmdl") contShopDireEnt:SetOriginalModel("models/heroes/enigma/enigma.vmdl") contShopDireEnt:StartGesture(ACT_DOTA_IDLE) contShopDireEnt:SetForwardVector(Vector(-1,0,0)) sItems,prices,stocks = CreateShop({ {"item_quelling_blade", 150, 3}, {"item_quelling_blade"}, {"item_clarity"}, {"item_bfury", 9000}, }) sItems[3]:SetCurrentCharges(2) contShopDire = Containers:CreateShop({ layout = {2,2,2,2,2}, skins = {}, headerText = "Dire Shop", pids = {}, position = "entity", --"1000px 300px 0px", entity = contShopDireEnt, items = sItems, prices = prices, stocks = stocks, closeOnOrder= true, range = 300, OnSelect = function(playerID, container, selected) print("Selected", selected:GetUnitName()) if PlayerResource:GetTeam(playerID) == DOTA_TEAM_BADGUYS then container:Open(playerID) end end, OnDeselect = function(playerID, container, deselected) print("Deselected", deselected:GetUnitName()) if PlayerResource:GetTeam(playerID) == DOTA_TEAM_BADGUYS then container:Close(playerID) end end, OnEntityOrder=function(playerID, container, unit, target) print("ORDER ACTION dire shop", playerID) if PlayerResource:GetTeam(playerID) == DOTA_TEAM_BADGUYS then container:Open(playerID) unit:Stop() else Containers:DisplayError(playerID, "#dota_hud_error_unit_command_restricted") end end, }) crafting = Containers:CreateContainer({ layout = {3,3,3}, skins = {}, headerText = "Crafting Station", pids = {}, position = "entity", --"1000px 300px 0px", entity = craftingEnt, closeOnOrder= true, range = 200, buttons = {"Craft"}, OnEntityOrder=function(playerID, container, unit, target) print("ORDER ACTION crafting station", playerID) container:Open(playerID) unit:Stop() end, OnButtonPressed = function(playerID, container, unit, button, buttonName) if button == 1 then local all = container:GetAllItems() local branches = container:GetItemsByName("item_branches") local broadswords = container:GetItemsByName("item_broadsword") local claymores = container:GetItemsByName("item_claymore") print(#all, #branches, #broadswords, #claymores) if #all == 3 and #branches == 1 and #broadswords == 1 and #claymores == 1 then local row,col = container:GetRowColumnForItem(branches[1]) local row2,col2 = container:GetRowColumnForItem(broadswords[1]) local row3,col3 = container:GetRowColumnForItem(claymores[1]) print(row,col) print(row2,col2) print(row3,col3) if row == 3 and row2+row3 == 3 and col == col2 and col == col3 then for _,item in ipairs(all) do container:RemoveItem(item) end container:AddItem(CreateItem("item_bfury",unit,unit), 2, 2) end end end end, }) craftingMats = Containers:CreateContainer({ layout = {3,3,3}, skins = {}, headerText = "Materials", pids = {}, position = "entity", --"1000px 300px 0px", entity = craftingMatsEnt, closeOnOrder= true, range = 200, buttons = {}, OnEntityOrder=function(playerID, container, unit, target) print("ORDER ACTION crafting mats", playerID) container:Open(playerID) unit:Stop() end, }) item = CreateItem("item_branches", nil, nil) craftingMats:AddItem(item) item = CreateItem("item_branches", nil, nil) craftingMats:AddItem(item) item = CreateItem("item_broadsword", nil, nil) craftingMats:AddItem(item) item = CreateItem("item_branches", nil, nil) craftingMats:AddItem(item) item = CreateItem("item_claymore", nil, nil) craftingMats:AddItem(item) item = CreateItem("item_claymore", nil, nil) craftingMats:AddItem(item) item = CreateItem("item_branches", nil, nil) craftingMats:AddItem(item) for _,loc in ipairs(lootSpawns) do CreateLootBox(loc) end for _,loc in ipairs(itemDrops) do local phys = CreateItemOnPositionSync(loc:GetAbsOrigin(), RandomItem()) phys:SetForwardVector(Vector(0,-1,0)) loc.phys = phys end Timers:CreateTimer(.1, function() GameRules:GetGameModeEntity():SetCameraDistanceOverride( 1500 ) end) Timers:CreateTimer(function() for _,loc in ipairs(itemDrops) do if not IsValidEntity(loc.phys) then local phys = CreateItemOnPositionSync(loc:GetAbsOrigin(), RandomItem()) phys:SetForwardVector(Vector(0,-1,0)) loc.phys = phys end end return 15 end) end function PlayGround:OnHeroInGame(hero) -- create inventory print(pid, hero:GetName()) local pid = hero:GetPlayerID() local validItemsBySlot = { [1] = --helm {item_helm_of_iron_will= true, item_veil_of_discord= true}, [2] = --chest {item_chainmail= true, item_blade_mail= true}, [3] = --boots {item_boots= true, item_phase_boots= true}, } local c = Containers:CreateContainer({ layout = {3,4,4}, skins = {}, headerText = "Backpack", pids = {pid}, entity = hero, closeOnOrder =false, position = "75% 25%", OnDragWorld = true, OnRightClickJS = "SpecialContextMenu", OnRightClick = function(playerID, container, unit, item, slot) print("RIGHT CLICK") local armor = pidEquipment[playerID] for i,valid in pairs(validItemsBySlot) do for itemname,_ in pairs(valid) do if itemname == item:GetAbilityName() then Containers:OnDragFrom(playerID, container, unit, item, slot, armor, i) end end end end }) pidInventory[pid] = c local item = CreateItem("item_tango", hero, hero) c:AddItem(item, 4) item = CreateItem("item_tango", hero, hero) c:AddItem(item, 6) item = CreateItem("item_ring_of_basilius", hero, hero) c:AddItem(item, 8) item = CreateItem("item_phase_boots", hero, hero) c:AddItem(item, 9) item = CreateItem("item_force_staff", hero, hero) c:AddItem(item) item = CreateItem("item_blade_mail", hero, hero) c:AddItem(item) item = CreateItem("item_veil_of_discord", hero, hero) c:AddItem(item) privateBank[pid] = Containers:CreateContainer({ layout = {4,4,4,4}, headerText = "Private Bank", pids = {pid}, position = "entity", --"200px 200px 0px", entity = privateBankEnt, closeOnOrder= true, forceOwner = hero, forcePurchaser=hero, range = 250, OnEntityOrder =function(playerID, container, unit, target) print("ORDER ACTION private bank: ", playerID) if privateBank[playerID] then privateBank[playerID]:Open(playerID) end unit:Stop() end, }) defaultInventory[pid] = true Containers:SetDefaultInventory(hero, c) local pack = CreateItem("item_containers_lua_pack", hero, hero) pack.container = c hero:AddItem(pack) c = Containers:CreateContainer({ layout = {1,1,1}, skins = {"Hourglass"}, headerText = "Armor", pids = {pid}, entity = hero, closeOnOrder =false, position = "200px 500px 0px", equipment = true, layoutFile = "file://{resources}/layout/custom_game/containers/alt_container_example.xml", OnDragWithin = false, OnRightClickJS = "ExampleRightClick", OnMouseOverJS = "ExampleMouseOver", AddItemFilter = function(container, item, slot) print("Armor, AddItemFilter: ", container, item, slot) if slot ~= -1 and validItemsBySlot[slot][item:GetAbilityName()] then return true end return false end, }) pidEquipment[pid] = c item = CreateItem("item_helm_of_iron_will", hero, hero) c:AddItem(item, 1) item = CreateItem("item_chainmail", hero, hero) c:AddItem(item, 2) item = CreateItem("item_boots", hero, hero) c:AddItem(item, 3) pack = CreateItem("item_containers_lua_pack", hero, hero) pack.container = c hero:AddItem(pack) end function PlayGround:OnNPCSpawned(keys) local npc = EntIndexToHScript(keys.entindex) if npc:IsRealHero() and npc.bFirstSpawnedPG == nil then npc.bFirstSpawnedPG = true PlayGround:OnHeroInGame(npc) end end function PlayGround:OnConnectFull(keys) if OFPL then PlayGround:OnFirstPlayerLoaded() OFPL = false end end if LOADED then return end LOADED = true OFPL = true MAX_NUMBER_OF_TEAMS = 2 USE_AUTOMATIC_PLAYERS_PER_TEAM = true ListenToGameEvent('npc_spawned', Dynamic_Wrap(PlayGround, 'OnNPCSpawned'), PlayGround) ListenToGameEvent('player_connect_full', Dynamic_Wrap(PlayGround, 'OnConnectFull'), PlayGround) pidInventory = {} pidEquipment = {} lootSpawns = nil itemDrops = nil privateBankEnt = nil sharedBankEnt = nil contShopRadEnt = nil contShopDireEnt = nil itemShopEnt = nil craftingEnt = nil craftingMatsEnt = nil crafting = nil craftingMats = nil contShopRad = nil contShopDire = nil itemShop = nil sharedBank = nil privateBank = {} defaultInventory = {} end
mit
nasomi/darkstar
scripts/zones/Garlaige_Citadel/Zone.lua
17
3962
----------------------------------- -- -- Zone: Garlaige_Citadel (200) -- ----------------------------------- package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/zone"); require("scripts/zones/Garlaige_Citadel/TextIDs"); banishing_gates_base = 17596761; -- _5k0 (First banishing gate) ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local tomes = {17596852,17596853,17596854}; SetGroundsTome(tomes); -- Banishing Gate #1... zone:registerRegion(1,-208,-1,224,-206,1,227); zone:registerRegion(2,-208,-1,212,-206,1,215); zone:registerRegion(3,-213,-1,224,-211,1,227); zone:registerRegion(4,-213,-1,212,-211,1,215); -- Banishing Gate #2 zone:registerRegion(10,-51,-1,82,-49,1,84); zone:registerRegion(11,-151,-1,82,-149,1,84); zone:registerRegion(12,-51,-1,115,-49,1,117); zone:registerRegion(13,-151,-1,115,-149,1,117); -- Banishing Gate #3 zone:registerRegion(19,-190,-1,355,-188,1,357); zone:registerRegion(20,-130,-1,355,-128,1,357); zone:registerRegion(21,-190,-1,322,-188,1,324); zone:registerRegion(22,-130,-1,322,-128,1,324); -- Old Two-Wings SetRespawnTime(17596506, 900, 10800); -- Skewer Sam SetRespawnTime(17596507, 900, 10800); -- Serket SetRespawnTime(17596720, 900, 10800); UpdateTreasureSpawnPoint(17596808); UpdateTreasureSpawnPoint(17596809); end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-380.035,-13.548,398.032,64); end return cs; end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) local regionID = region:GetRegionID(); local mylever = banishing_gates_base + regionID; GetNPCByID(mylever):setAnimation(8); if (regionID >= 1 and regionID <= 4) then gateid = banishing_gates_base; msg_offset = 0; elseif (regionID >= 10 and regionID <= 13) then gateid = banishing_gates_base + 9; msg_offset = 1; elseif (regionID >= 19 and regionID <= 22) then gateid = banishing_gates_base + 18; msg_offset = 2; end; -- Open Gate gate1 = GetNPCByID(gateid + 1); gate2 = GetNPCByID(gateid + 2); gate3 = GetNPCByID(gateid + 3); gate4 = GetNPCByID(gateid + 4); if (gate1:getAnimation() == 8 and gate2:getAnimation() == 8 and gate3:getAnimation() == 8 and gate4:getAnimation() == 8) then player:messageSpecial(BANISHING_GATES + msg_offset); -- Banishing gate opening GetNPCByID(gateid):openDoor(30); end end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) local regionID = region:GetRegionID(); local mylever = banishing_gates_base + regionID; GetNPCByID(mylever):setAnimation(9); 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
fegimanam/zus
plugins/inrealm.lua
11
24925
-- data saved to moderation.json -- check moderation plugin do local function create_group(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Group [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function create_realm(msg) -- superuser and admins only (because sudo are always has privilege) if is_sudo(msg) or is_realm(msg) and is_admin(msg) then local group_creator = msg.from.print_name create_group_chat (group_creator, group_name, ok_cb, false) return 'Realm [ '..string.gsub(group_name, '_', ' ')..' ] has been created.' end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function get_group_type(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not data[tostring(msg.to.id)]['group_type'] then return 'No group type available.' end local group_type = data[tostring(msg.to.id)]['group_type'] return group_type else return 'Chat type not found.' end end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function set_description(msg, data, target, about) if not is_admin(msg) then return "For admins only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function set_rules(msg, data, target) if not is_admin(msg) then return "For admins only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_name(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end --lock/unlock group member. bot automatically kick new added user when locked local function lock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_member(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end --lock/unlock group photo. bot automatically keep group photo when locked local function lock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(target)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) end return 'Please send me the group photo now' end local function unlock_group_photo(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function lock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_flood(msg, data, target) if not is_admin(msg) then return "For admins only!" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end -- show group settings local function show_group_settings(msg, data, target) local data = load_data(_config.moderation.data, data) if not is_admin(msg) then return "For admins only!" end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member return text end local function returnids(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end send_large_msg(receiver, text) local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() end local function returnidsfile(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name local text = 'Users in '..string.gsub(chatname,"_"," ")..' ('..result.id..'):'..'\n'..'' for k,v in pairs(result.members) do local username = "" text = text .. "- " .. string.gsub(v.print_name,"_"," ") .. " (" .. v.id .. ") \n" end local file = io.open("./groups/lists/"..result.id.."memberlist.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..result.id,"./groups/lists/"..result.id.."memberlist.txt", ok_cb, false) end local function admin_promote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if data[tostring(admins)][tostring(admin_id)] then return admin_name..' is already an admin.' end data[tostring(admins)][tostring(admin_id)] = admin_id save_data(_config.moderation.data, data) return admin_id..' has been promoted as admin.' end local function admin_demote(msg, admin_id) if not is_sudo(msg) then return "Access denied!" end local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end if not data[tostring(admins)][tostring(admin_id)] then return admin_id..' is not an admin.' end data[tostring(admins)][tostring(admin_id)] = nil save_data(_config.moderation.data, data) return admin_id..' has been demoted from admin.' end local function admin_list(msg) local data = load_data(_config.moderation.data) local admins = 'admins' if not data[tostring(admins)] then data[tostring(admins)] = {} save_data(_config.moderation.data, data) end local message = 'List for Realm admins:\n' for k,v in pairs(data[tostring(admins)]) do message = message .. '- (at)' .. v .. ' [' .. k .. '] ' ..'\n' end return message end local function groups_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of groups:\n' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['set_owner'] then group_owner = tostring(data[tostring(v)]['set_owner']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/groups.txt", "w") file:write(message) file:flush() file:close() return message end local function realms_list(msg) local data = load_data(_config.moderation.data) local realms = 'realms' if not data[tostring(realms)] then return 'No Realms at the moment' end local message = 'List of Realms:\n' for k,v in pairs(data[tostring(realms)]) do local settings = data[tostring(v)]['settings'] for m,n in pairs(settings) do if m == 'set_name' then name = n end end local group_owner = "No owner" if data[tostring(v)]['admins_in'] then group_owner = tostring(data[tostring(v)]['admins_in']) end local group_link = "No link" if data[tostring(v)]['settings']['set_link'] then group_link = data[tostring(v)]['settings']['set_link'] end message = message .. '- '.. name .. ' (' .. v .. ') ['..group_owner..'] \n {'..group_link.."}\n" end local file = io.open("./groups/lists/realms.txt", "w") file:write(message) file:flush() file:close() return message end local function admin_user_promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already as admin.') end data['admins'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, '@'..member_username..' has been promoted as admin.') end local function admin_user_demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) if not data['admins'] then data['admins'] = {} save_data(_config.moderation.data, data) end if not data['admins'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not an admin.') end data['admins'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Admin '..member_username..' has been demoted.') end local function username_id(cb_extra, success, result) local mod_cmd = cb_extra.mod_cmd local receiver = cb_extra.receiver local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if mod_cmd == 'addadmin' then return admin_user_promote(receiver, member_username, member_id) elseif mod_cmd == 'removeadmin' then return admin_user_demote(receiver, member_username, member_id) end end end send_large_msg(receiver, text) end local function set_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'yes' then return 'Log group is already set' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'yes' save_data(_config.moderation.data, data) return 'Log group has been set' end end local function unset_log_group(msg) if not is_admin(msg) then return end local log_group = data[tostring(groups)][tostring(msg.to.id)]['log_group'] if log_group == 'no' then return 'Log group is already disabled' else data[tostring(groups)][tostring(msg.to.id)]['log_group'] = 'no' save_data(_config.moderation.data, data) return 'log group has been disabled' end end local function help() local help_text = tostring(_config.help_text_realm) return help_text end function run(msg, matches) --vardump(msg) local name_log = user_print_name(msg.from) if matches[1] == 'log' and is_owner(msg) then savelog(msg.to.id, "log file created by owner") send_document("chat#id"..msg.to.id,"./groups/"..msg.to.id.."log.txt", ok_cb, false) end if matches[1] == 'who' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list ") local receiver = get_receiver(msg) chat_info(receiver, returnidsfile, {receiver=receiver}) end if matches[1] == 'wholist' and is_momod(msg) then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested member list in a file") local receiver = get_receiver(msg) chat_info(receiver, returnids, {receiver=receiver}) end if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] group_type = 'group' return create_group(msg) end if not is_sudo(msg) or not is_admin(msg) and not is_realm(msg) then return --Do nothing end if matches[1] == 'createrealm' and matches[2] then group_name = matches[2] group_type = 'realm' return create_realm(msg) end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if matches[2] then if data[tostring(matches[2])] then local settings = data[tostring(matches[2])]['settings'] if matches[1] == 'setabout' and matches[2] then local target = matches[2] local about = matches[3] return set_description(msg, data, target, about) end if matches[1] == 'setrules' then rules = matches[3] local target = matches[2] return set_rules(msg, data, target) end if matches[1] == 'lock' then --group lock * local target = matches[2] if matches[3] == 'name' then return lock_group_name(msg, data, target) end if matches[3] == 'member' then return lock_group_member(msg, data, target) end if matches[3] == 'photo' then return lock_group_photo(msg, data, target) end if matches[3] == 'flood' then return lock_group_flood(msg, data, target) end end if matches[1] == 'unlock' then --group unlock * local target = matches[2] if matches[3] == 'name' then return unlock_group_name(msg, data, target) end if matches[3] == 'member' then return unlock_group_member(msg, data, target) end if matches[3] == 'photo' then return unlock_group_photo(msg, data, target) end if matches[3] == 'flood' then return unlock_group_flood(msg, data, target) end end if matches[1] == 'settings' and data[tostring(matches[2])]['settings'] then local target = matches[2] return show_group_settings(msg, data, target) end if matches[1] == 'setname' and is_realm(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Realm { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setgpname' and is_admin(msg) then local new_name = string.gsub(matches[3], '_', ' ') data[tostring(matches[2])]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(matches[2])]['settings']['set_name'] local to_rename = 'chat#id'..matches[2] rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end end end if matches[1] == 'help' and is_realm(msg) then savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'set' then if matches[2] == 'loggroup' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set as log group") return set_log_group(msg) end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return modrem(msg), print("Closing Group: "..receiver), chat_info(receiver, killchat, {receiver=receiver}) else return 'Error: Group '..matches[3]..' not found' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if is_realm(msg) then local receiver = 'chat#id'..matches[3] return realmrem(msg), print("Closing realm: "..receiver), chat_info(receiver, killrealm, {receiver=receiver}) else return 'Error: Realm '..matches[3]..' not found' end end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if not is_admin(msg) then chat_del_user(chat, user, ok_cb, true) end end if matches[1] == 'addadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been promoted as admin") return admin_promote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "addadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'removeadmin' then if string.match(matches[2], '^%d+$') then local admin_id = matches[2] print("user "..admin_id.." has been demoted") return admin_demote(msg, admin_id) else local member = string.gsub(matches[2], "@", "") local mod_cmd = "removeadmin" chat_info(receiver, username_id, {mod_cmd= mod_cmd, receiver=receiver, member=member}) end end if matches[1] == 'type'then local group_type = get_group_type(msg) return group_type end if matches[1] == 'list' and matches[2] == 'admins' then return admin_list(msg) end if matches[1] == 'list' and matches[2] == 'groups' then if msg.to.type == 'chat' then groups_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) elseif msg.to.type == 'user' then groups_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/groups.txt", ok_cb, false) return "Group list created" --group_list(msg) end end if matches[1] == 'list' and matches[2] == 'realms' then if msg.to.type == 'chat' then realms_list(msg) send_document("chat#id"..msg.to.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) elseif msg.to.type == 'user' then realms_list(msg) send_document("user#id"..msg.from.id, "./groups/lists/realms.txt", ok_cb, false) return "Realms list created" --realms_list(msg) end end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end end return { patterns = { "^(creategroup) (.*)$", "^(createrealm) (.*)$", "^(setabout) (%d+) (.*)$", "^(setrules) (%d+) (.*)$", "^(setname) (.*)$", "^(setgpname) (%d+) (.*)$", "^(setname) (%d+) (.*)$", "^(lock) (%d+) (.*)$", "^(unlock) (%d+) (.*)$", "^(setting) (%d+)$", "^(wholist)$", "^(who)$", "^(type)$", "^(kill) (chat) (%d+)$", "^(kill) (realm) (%d+)$", "^(addadmin) (.*)$", -- sudoers only "^(removeadmin) (.*)$", -- sudoers only "^(list) (.*)$", "^(log)$", "^(help)$", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
nicholas-leonard/nn
SpatialConvolutionLocal.lua
9
6746
local SpatialConvolutionLocal, parent = torch.class('nn.SpatialConvolutionLocal', 'nn.Module') function SpatialConvolutionLocal:__init(nInputPlane, nOutputPlane, iW, iH ,kW, kH, dW, dH, padW, padH) parent.__init(self) dW = dW or 1 dH = dH or 1 self.nInputPlane = nInputPlane self.nOutputPlane = nOutputPlane self.kW = kW self.kH = kH self.iW = iW self.iH = iH self.dW = dW self.dH = dH self.padW = padW or 0 self.padH = padH or self.padW self.oW = math.floor((self.padW * 2 + iW - self.kW) / self.dW) + 1 self.oH = math.floor((self.padH * 2 + iH - self.kH) / self.dH) + 1 assert(1 <= self.oW and 1 <= self.oH, 'illegal configuration: output width or height less than 1') self.weight = torch.Tensor(self.oH, self.oW, nOutputPlane, nInputPlane, kH, kW) self.bias = torch.Tensor(nOutputPlane, self.oH, self.oW) self.gradWeight = torch.Tensor():resizeAs(self.weight) self.gradBias = torch.Tensor():resizeAs(self.bias) self:reset() end function SpatialConvolutionLocal:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1/math.sqrt(self.kW*self.kH*self.nInputPlane) end if nn.oldSeed then self.weight:apply(function() return torch.uniform(-stdv, stdv) end) self.bias:apply(function() return torch.uniform(-stdv, stdv) end) else self.weight:uniform(-stdv, stdv) self.bias:uniform(-stdv, stdv) end end local function viewWeight(self) self.weight = self.weight:view(self.oH * self.oW, self.nOutputPlane, self.nInputPlane * self.kH * self.kW) if self.gradWeight and self.gradWeight:dim() > 0 then self.gradWeight = self.gradWeight:view(self.oH * self.oW, self.nOutputPlane, self.nInputPlane * self.kH * self.kW) end end local function unviewWeight(self) self.weight = self.weight:view(self.oH, self.oW, self.nOutputPlane, self.nInputPlane, self.kH, self.kW) if self.gradWeight and self.gradWeight:dim() > 0 then self.gradWeight = self.gradWeight:view(self.oH, self.oW, self.nOutputPlane, self.nInputPlane, self.kH, self.kW) end end local function checkInputSize(self, input) if input:nDimension() == 3 then if input:size(1) ~= self.nInputPlane or input:size(2) ~= self.iH or input:size(3) ~= self.iW then error(string.format('Given input size: (%dx%dx%d) inconsistent with expected input size: (%dx%dx%d).', input:size(1), input:size(2), input:size(3), self.nInputPlane, self.iH, self.iW)) end elseif input:nDimension() == 4 then if input:size(2) ~= self.nInputPlane or input:size(3) ~= self.iH or input:size(4) ~= self.iW then error(string.format('Given input size: (%dx%dx%dx%d) inconsistent with expected input size: (batchsize x%dx%dx%d).', input:size(1), input:size(2), input:size(3), input:size(4), self.nInputPlane, self.iH, self.iW)) end else error('3D or 4D(batch mode) tensor expected') end end local function checkOutputSize(self, input, output) if output:nDimension() ~= input:nDimension() then error('inconsistent dimension between output and input.') end if output:nDimension() == 3 then if output:size(1) ~= self.nOutputPlane or output:size(2) ~= self.oH or output:size(3) ~= self.oW then error(string.format('Given output size: (%dx%dx%d) inconsistent with expected output size: (%dx%dx%d).', output:size(1), output:size(2), output:size(3), self.nOutputPlane, self.oH, self.oW)) end elseif output:nDimension() == 4 then if output:size(2) ~= self.nOutputPlane or output:size(3) ~= self.oH or output:size(4) ~= self.oW then error(string.format('Given output size: (%dx%dx%dx%d) inconsistent with expected output size: (batchsize x%dx%dx%d).', output:size(1), output:size(2), output:size(3), output:size(4), self.nOutputPlane, self.oH, self.oW)) end else error('3D or 4D(batch mode) tensor expected') end end function SpatialConvolutionLocal:updateOutput(input) self.finput = self.finput or input.new() self.fgradInput = self.fgradInput or input.new() checkInputSize(self, input) viewWeight(self) input.THNN.SpatialConvolutionLocal_updateOutput( input:cdata(), self.output:cdata(), self.weight:cdata(), self.bias:cdata(), self.finput:cdata(), self.fgradInput:cdata(), self.kW, self.kH, self.dW, self.dH, self.padW, self.padH, self.iW, self.iH, self.oW, self.oH ) unviewWeight(self) return self.output end function SpatialConvolutionLocal:updateGradInput(input, gradOutput) checkInputSize(self, input) checkOutputSize(self, input, gradOutput) if self.gradInput then viewWeight(self) input.THNN.SpatialConvolutionLocal_updateGradInput( input:cdata(), gradOutput:cdata(), self.gradInput:cdata(), self.weight:cdata(), self.finput:cdata(), self.fgradInput:cdata(), self.kW, self.kH, self.dW, self.dH, self.padW, self.padH, self.iW, self.iH, self.oW, self.oH ) unviewWeight(self) return self.gradInput end end function SpatialConvolutionLocal:accGradParameters(input, gradOutput, scale) scale = scale or 1 checkInputSize(self, input) checkOutputSize(self, input, gradOutput) viewWeight(self) input.THNN.SpatialConvolutionLocal_accGradParameters( input:cdata(), gradOutput:cdata(), self.gradWeight:cdata(), self.gradBias:cdata(), self.finput:cdata(), self.fgradInput:cdata(), self.kW, self.kH, self.dW, self.dH, self.padW, self.padH, self.iW, self.iH, self.oW, self.oH, scale ) unviewWeight(self) end function SpatialConvolutionLocal:type(type,tensorCache) self.finput = self.finput and torch.Tensor() self.fgradInput = self.fgradInput and torch.Tensor() return parent.type(self,type,tensorCache) end function SpatialConvolutionLocal:__tostring__() local s = string.format('%s(%d -> %d, %dx%d, %dx%d', torch.type(self), self.nInputPlane, self.nOutputPlane, self.iW, self.iH, self.kW, self.kH) if self.dW ~= 1 or self.dH ~= 1 or self.padW ~= 0 or self.padH ~= 0 then s = s .. string.format(', %d,%d', self.dW, self.dH) end if (self.padW or self.padH) and (self.padW ~= 0 or self.padH ~= 0) then s = s .. ', ' .. self.padW .. ',' .. self.padH end return s .. ')' end function SpatialConvolutionLocal:clearState() nn.utils.clear(self, 'finput', 'fgradInput', '_input', '_gradOutput') return parent.clearState(self) end
bsd-3-clause
nasomi/darkstar
scripts/zones/Monastic_Cavern/npcs/Altar.lua
27
1815
----------------------------------- -- Area: Monastic Cavern -- NPC: Altar -- Involved in Quests: The Circle of Time -- @pos 109 -3 -145 150 ----------------------------------- package.loaded["scripts/zones/Monastic_Cavern/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Monastic_Cavern/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local circleOfTime = player:getQuestStatus(JEUNO,THE_CIRCLE_OF_TIME); if (circleOfTime == QUEST_ACCEPTED and player:getVar("circleTime") >= 7) then if (player:hasKeyItem(STAR_RING1) and player:hasKeyItem(MOON_RING)) then if (player:getVar("circleTime") == 7) then SpawnMob(17391804,180):updateClaim(player); -- Spawn bugaboo elseif (player:getVar("circleTime") == 8) then player:startEvent(0x03); -- Show final CS end end else player:messageSpecial(ALTAR) 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 == 0x03) then player:setVar("circleTime",9); -- After bugaboo is killed, and final CS shows up player:delKeyItem(MOON_RING); player:delKeyItem(STAR_RING1); end end;
gpl-3.0
Falcon-peregrinus/moreanimals
init.lua
1
2635
--Add Chicken moreanimals = {} function moreanimals:register_egg(modname, mobname, mobdesc) minetest.register_craftitem(modname..":egg_"..mobname, { description = mobdesc.." egg", inventory_image = modname.."_egg_"..mobname..".png", on_place = function(itemstack, placer, pointed_thing) if pointed_thing.type ~= "node" then return end -- Call on_rightclick if the pointed node defines it if placer and not placer:get_player_control().sneak then local n = minetest.get_node(pointed_thing.under) local nn = n.name if minetest.registered_nodes[nn] and minetest.registered_nodes[nn].on_rightclick then return minetest.registered_nodes[nn].on_rightclick(pointed_thing.under, n, placer, itemstack) or itemstack end end -- Actually spawn the mob minetest.env:add_entity(pointed_thing.above, modname..":"..mobname) if not minetest.setting_getbool("creative_mode") then itemstack:take_item() end return itemstack end, }) end mobs:register_mob("moreanimals:chicken", { type = "animal", hp_max = 2, collisionbox = {-0.5, -0.5, -0.5, 0.5, 0.5, 0.5}, visual = "upright_sprite", visual_size = {x=1, y=1}, textures = {"chicken.png", "chicken.png"}, makes_footstep_sound = true, view_range = 15, walk_velocity = 1, drops = { {name = "mobs:meat_raw", chance = 1, min = 2, max = 3,}, {name = "moreanimals:egg_chicken", chance = 2, min = 1, max = 1,}, }, sounds = { random = "mobs_chicken", }, run_velocity = 2, armor = 200, drawtype = "front", water_damage = 0, lava_damage = 1, light_damage = 0, on_rightclick = function(self, clicker) if clicker:is_player() and clicker:get_inventory() then clicker:get_inventory():add_item("main", "moreanimals:chicken") self.object:remove() end end, }) minetest.register_craftitem("moreanimals:chicken", { description = "Chicken", inventory_image = "chicken.png", on_place = function(itemstack, placer, pointed_thing) if pointed_thing.above then minetest.env:add_entity(pointed_thing.above, "moreanimals:chicken") itemstack:take_item() end return itemstack end, }) minetest.register_craftitem("moreanimals:egg_chicken_fried", { description = "Fried chicken's egg", inventory_image = "moreanimals_egg_chicken_fried.png", on_use = minetest.item_eat(8), }) minetest.register_craft({ type = "cooking", output = "moreanimals:egg_chicken_fried", recipe = "moreanimals:egg_chicken", cooktime = 5, }) mobs:register_spawn("moreanimals:chicken", {"default:dirt_with_grass"}, 20, 8, 9000, 1, 31000) moreanimals:register_egg("moreanimals","chicken","Chicken")
unlicense
nasomi/darkstar
scripts/zones/Port_San_dOria/npcs/HomePoint#1.lua
17
1263
----------------------------------- -- Area: Port San dOria -- NPC: HomePoint#1 -- @pos -67.963 -4.000 -105.023 232 ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/Port_San_dOria/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fc, 6); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x21fc) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Waughroon_Shrine/bcnms/on_my_way.lua
19
1883
----------------------------------- -- Area: Waughroon Shrine -- Name: Mission Rank 7-2 (Bastok) -- @pos -345 104 -260 144 ----------------------------------- package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Waughroon_Shrine/TextIDs"); ----------------------------------- -- After registering the BCNM via bcnmRegister(bcnmid) function onBcnmRegister(player,instance) end; -- Physically entering the BCNM via bcnmEnter(bcnmid) function onBcnmEnter(player,instance) end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage if (player:hasCompletedMission(BASTOK,ON_MY_WAY)) then player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,1); else player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0); end elseif (leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if (csid == 0x7d01) then if ((player:getCurrentMission(BASTOK) == ON_MY_WAY) and (player:getVar("MissionStatus") == 2)) then player:addKeyItem(LETTER_FROM_WEREI); player:messageSpecial(KEYITEM_OBTAINED,LETTER_FROM_WEREI); player:setVar("MissionStatus",3); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/QuBia_Arena/mobs/Rallbrog_of_Clan_Death.lua
36
2534
----------------------------------- -- Area: QuBia_Arena -- Mission 9-2 SANDO ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/missions"); require("scripts/zones/QuBia_Arena/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- ----------------------------------- -- onMobFight ----------------------------------- function onMobFight(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) local mobs= {{17621017,17621018,17621019,17621020,17621021,17621022,17621023,17621024,17621025,17621026,17621027},{17621031,17621032,17621033,17621034,17621035,17621036,17621037,17621038,17621039,17621040,17621041},{17621031,17621046,17621047,17621048,17621049,17621050,17621051,17621052,17621053,17621054,17621055}}; local inst=killer:getBattlefield():getBattlefieldNumber(); local victory = true for i,v in ipairs(mobs[inst]) do local action = GetMobAction(v); printf("action %u",action); if not(action == 0 or (action >=21 and action <=23)) then victory = false end end if victory == true then killer:startEvent(0x7d04,0,0,4); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) printf("finishCSID: %u",csid); printf("RESULT: %u",option); if (csid == 0x7d04) then if (player:getBattlefield():getBattlefieldNumber() == 1) then SpawnMob(17621014); SpawnMob(17621015); SpawnMob(17621016); local trion = player:getBattlefield():insertAlly(14183) trion:setSpawn(-403,-201,413,58); trion:spawn(); player:setPos(-400,-201,419,61); elseif (player:getBattlefield():getBattlefieldNumber() == 2) then SpawnMob(17621028); SpawnMob(17621029); SpawnMob(17621030); local trion = player:getBattlefield():insertAlly(14183) trion:setSpawn(-3,-1,4,61); trion:spawn(); player:setPos(0,-1,10,61); elseif (player:getBattlefield():getBattlefieldNumber() == 3) then SpawnMob(17621042); SpawnMob(17621043); SpawnMob(17621044); local trion = player:getBattlefield():insertAlly(14183) trion:setSpawn(397,198,-395,64); trion:spawn(); player:setPos(399,198,-381,57); end end end;
gpl-3.0
shangjiyu/luci-with-extra
applications/luci-app-upnp/luasrc/controller/upnp.lua
20
1886
-- Copyright 2008 Steven Barth <steven@midlink.org> -- Copyright 2008 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. module("luci.controller.upnp", package.seeall) function index() if not nixio.fs.access("/etc/config/upnpd") then return end local page page = entry({"admin", "services", "upnp"}, cbi("upnp/upnp"), _("UPnP")) page.dependent = true entry({"admin", "services", "upnp", "status"}, call("act_status")).leaf = true entry({"admin", "services", "upnp", "delete"}, post("act_delete")).leaf = true end function act_status() local ipt = io.popen("iptables --line-numbers -t nat -xnvL MINIUPNPD 2>/dev/null") if ipt then local fwd = { } while true do local ln = ipt:read("*l") if not ln then break elseif ln:match("^%d+") then local num, proto, extport, intaddr, intport = ln:match("^(%d+).-([a-z]+).-dpt:(%d+) to:(%S-):(%d+)") if num and proto and extport and intaddr and intport then num = tonumber(num) extport = tonumber(extport) intport = tonumber(intport) fwd[#fwd+1] = { num = num, proto = proto:upper(), extport = extport, intaddr = intaddr, intport = intport } end end end ipt:close() luci.http.prepare_content("application/json") luci.http.write_json(fwd) end end function act_delete(num) local idx = tonumber(num) local uci = luci.model.uci.cursor() if idx and idx > 0 then luci.sys.call("iptables -t filter -D MINIUPNPD %d 2>/dev/null" % idx) luci.sys.call("iptables -t nat -D MINIUPNPD %d 2>/dev/null" % idx) local lease_file = uci:get("upnpd", "config", "upnp_lease_file") if lease_file and nixio.fs.access(lease_file) then luci.sys.call("sed -i -e '%dd' %q" %{ idx, lease_file }) end luci.http.status(200, "OK") return end luci.http.status(400, "Bad request") end
apache-2.0
nasomi/darkstar
scripts/zones/Manaclipper/Zone.lua
28
1617
----------------------------------- -- -- Zone: Manaclipper -- ----------------------------------- package.loaded["scripts/zones/Manaclipper/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Manaclipper/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(0,-3,-8,60); end return cs; end; function onTransportEvent(player,transport) player:startEvent(0x0064); 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; ----------------------------------- -- 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 == 0x0064) then player:setPos(0,0,0,0,4); end end;
gpl-3.0
nicholas-leonard/nn
JoinTable.lua
11
2075
local JoinTable, parent = torch.class('nn.JoinTable', 'nn.Module') function JoinTable:__init(dimension, nInputDims) parent.__init(self) self.size = torch.LongStorage() self.dimension = dimension self.gradInput = {} self.nInputDims = nInputDims end function JoinTable:_getPositiveDimension(input) local dimension = self.dimension if dimension < 0 then dimension = input[1]:dim() + dimension + 1 elseif self.nInputDims and input[1]:dim()==(self.nInputDims+1) then dimension = dimension + 1 end return dimension end function JoinTable:updateOutput(input) local dimension = self:_getPositiveDimension(input) for i=1,#input do local currentOutput = input[i] if i == 1 then self.size:resize(currentOutput:dim()):copy(currentOutput:size()) else self.size[dimension] = self.size[dimension] + currentOutput:size(dimension) end end self.output:resize(self.size) local offset = 1 for i=1,#input do local currentOutput = input[i] self.output:narrow(dimension, offset, currentOutput:size(dimension)):copy(currentOutput) offset = offset + currentOutput:size(dimension) end return self.output end function JoinTable:updateGradInput(input, gradOutput) local dimension = self:_getPositiveDimension(input) for i=1,#input do if self.gradInput[i] == nil then self.gradInput[i] = input[i].new() end self.gradInput[i]:resizeAs(input[i]) end -- clear out invalid gradInputs for i=#input+1, #self.gradInput do self.gradInput[i] = nil end local offset = 1 for i=1,#input do local currentOutput = input[i] local currentGradInput = gradOutput:narrow(dimension, offset, currentOutput:size(dimension)) self.gradInput[i]:copy(currentGradInput) offset = offset + currentOutput:size(dimension) end return self.gradInput end function JoinTable:type(type, tensorCache) self.gradInput = {} return parent.type(self, type, tensorCache) end
bsd-3-clause
nasomi/darkstar
scripts/zones/RuLude_Gardens/npcs/HomePoint#3.lua
17
1250
----------------------------------- -- Area: RuLude_Gardens -- NPC: HomePoint#3 -- @pos -67 6 -25 243 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; require("scripts/globals/settings"); require("scripts/zones/RuLude_Gardens/TextIDs"); require("scripts/globals/homepoint"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) homepointMenu( player, 0x21fe, 31); 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 == 0x21fe) then if (option == 1) then player:setHomePoint(); player:messageSpecial(HOMEPOINT_SET); else hpTeleport( player, option); end end end;
gpl-3.0
nasomi/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Morangeart.lua
38
1057
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Morangeart -- Type: ENM Quest Activator -- @zone: 26 -- @pos -74.308 -24.782 -28.475 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0208); 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/Metalworks/npcs/Mythily.lua
17
2013
----------------------------------- -- Area: Metalworks -- NPC: Mythily -- Type: Immigration NPC -- @pos 94 -20 -8 237 ----------------------------------- require("scripts/globals/conquest"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local new_nation = BASTOK; local old_nation = player:getNation(); local rank = getNationRank(new_nation); if (old_nation == new_nation) then player:startEvent(0x016a,0,0,0,old_nation); elseif (player:getCurrentMission(old_nation) ~= 255 or player:getVar("MissionStatus") ~= 0) then player:startEvent(0x0169,0,0,0,new_nation); elseif (old_nation ~= new_nation) then local has_gil = 0; local cost = 0; if (rank == 1) then cost = 40000; elseif (rank == 2) then cost = 12000; elseif (rank == 3) then cost = 4000; end if (player:getGil() >= cost) then has_gil = 1 end player:startEvent(0x0168,0,1,player:getRank(),new_nation,has_gil,cost); 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 == 0x0168 and option == 1) then local new_nation = BASTOK; local rank = getNationRank(new_nation); local cost = 0; if (rank == 1) then cost = 40000; elseif (rank == 2) then cost = 12000; elseif (rank == 3) then cost = 4000; end player:setNation(new_nation) player:setGil(player:getGil() - cost); player:setRankPoints(0); end end;
gpl-3.0
dani-sj/danibot01
plugins/google.lua
336
1323
do local function googlethat(query) local url = 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&safe=active&&rsz=5&' local parameters = 'q='..(URL.escape(query) or '') -- Do the request local res, code = https.request(url..parameters) if code ~=200 then return nil end local data = json:decode(res) local results = {} for key,result in ipairs(data.responseData.results) do table.insert(results, { result.titleNoFormatting, result.unescapedUrl or result.url }) end return results end local function stringlinks(results) local stringresults='' i = 0 for key,val in ipairs(results) do i = i+1 stringresults=stringresults..i..'. '..val[1]..'\n'..val[2]..'\n' end return stringresults end local function run(msg, matches) -- comment this line if you want this plugin works in private message. if not is_chat_msg(msg) then return nil end local results = googlethat(matches[1]) return stringlinks(results) end return { description = 'Returns five results from Google. Safe search is enabled by default.', usage = ' !google [terms]: Searches Google and send results', patterns = { '^!google (.*)$', '^%.[g|G]oogle (.*)$' }, run = run } end
gpl-2.0
dromozoa/dromozoa-image
dromozoa/image/pnm_reader.lua
3
4876
-- 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 linked_hash_table = require "dromozoa.commons.linked_hash_table" local sequence = require "dromozoa.commons.sequence" local string_reader = require "dromozoa.commons.string_reader" local uint16 = require "dromozoa.commons.uint16" local class = {} function class.new(this) if type(this) == "string" then this = string_reader(this) end return { this = this; } end function class:read_plain(header) local this = self.this local pixels = sequence() local n = header.width * header.height * header.channels local min = header.min local max = header.max for i = 1, n do local value = this:read("*n") if value ~= nil and min <= value and value <= max and value % 1 == 0 then pixels[i] = value else error("invalid pixel") end end return class.super(header, pixels) end function class:read_raw(header) local this = self.this local pixels = sequence() local n = header.width * header.height * header.channels local max = header.max if max < 256 then for i = 4, n, 4 do pixels:push(this:read(4):byte(1, 4)) end local m = n % 4 if m > 0 then pixels:push(this:read(m):byte(1, m)) end else for i = 2, n, 2 do pixels:push(uint16.read(this, 2, ">")) end local m = n % 2 if m > 0 then pixels:push(uint16.read(this, 1, ">")) end end return class.super(header, pixels) end function class:read_pnm_header_value() local this = self.this while true do local value = this:read("*n") if value == nil then local char = this:read(1) if char == "#" then this:read() elseif char:find("%S") then error("invalid header") end else if value > 0 and value % 1 == 0 then return value else error("invalid header value") end end end end function class:read_pnm_header(magic) local this = self.this local header = linked_hash_table() header.width = self:read_pnm_header_value() header.height = self:read_pnm_header_value() header.min = 0 header.max = self:read_pnm_header_value() if this:read(1):find("%S") then error("invalid header") end if magic:find("P[25]") then header.channels = 1 else header.channels = 3 end return header end function class:read_pam_header() local this = self.this local header = linked_hash_table() for line in this:lines() do local line = line:gsub("^%s+", ""):gsub("%s+$", "") if line == "ENDHDR" then break elseif line:find("^TUPLTYPE") then -- ignore else local token, value = line:match("^([A-Z]+)%s+([1-9]%d*)$") local value = tonumber(value) if token == "WIDTH" then header.width = value elseif token == "HEIGHT" then header.height = value elseif token == "DEPTH" then if value <= 4 then header.channels = value else error("invalid DEPTH") end elseif token == "MAXVAL" then header.min = 0 header.max = value else error("invalid header") end end end if header.width == nil then error("WIDTH not found") end if header.height == nil then error("HEIGHT not found") end if header.channels == nil then error("DEPTH not found") end if header.max == nil then error("MAXVAL not found") end return header end function class:read_pnm(magic) local header = self:read_pnm_header(magic) if magic:find("P[56]") then return self:read_raw(header) else return self:read_plain(header) end end function class:read_pam() return self:read_raw(self:read_pam_header()) end function class:apply() local this = self.this local magic = this:read(2) if magic:find("P[2356]") then if this:read(1):find("%s") then return self:read_pnm(magic) end elseif magic == "P7" then if this:read(1) == "\n" then return self:read_pam() end end end local metatable = { __index = class; } return setmetatable(class, { __call = function (_, this) return setmetatable(class.new(this), metatable) end; })
gpl-3.0