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
nesstea/darkstar
scripts/zones/Temenos/mobs/Abyssdweller_Jhabdebb.lua
7
1581
----------------------------------- -- Area: Temenos -- NPC: ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Temenos/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if (IsMobDead(16929010)==true and IsMobDead(16929011)==true and IsMobDead(16929012)==true and IsMobDead(16929013)==true and IsMobDead(16929014)==true and IsMobDead(16929015)==true ) then mob:setMod(MOD_SLASHRES,1400); mob:setMod(MOD_PIERCERES,1400); mob:setMod(MOD_IMPACTRES,1400); mob:setMod(MOD_HTHRES,1400); else mob:setMod(MOD_SLASHRES,300); mob:setMod(MOD_PIERCERES,300); mob:setMod(MOD_IMPACTRES,300); mob:setMod(MOD_HTHRES,300); end GetMobByID(16929006):updateEnmity(target); GetMobByID(16929007):updateEnmity(target); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) if (IsMobDead(16929005)==true and IsMobDead(16929006)==true and IsMobDead(16929007)==true) then GetNPCByID(16928768+78):setPos(-280,-161,-440); GetNPCByID(16928768+78):setStatus(STATUS_NORMAL); GetNPCByID(16928768+473):setStatus(STATUS_NORMAL); end end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/The_Garden_of_RuHmet/npcs/qm2.lua
24
2318
----------------------------------- -- Area: The_Garden_of_RuHmet -- NPC: ??? (Ix'aern (Dark Knight) Spawn) -- Allows players to spawn the Ix'aern (Dark Knight) by checking ??? only after killing the required mobs in the same room as the ???. -- @pos ,-560 5 239 ----------------------------------- package.loaded["scripts/zones/The_Garden_of_RuHmet/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Garden_of_RuHmet/TextIDs"); require("scripts/zones/The_Garden_of_RuHmet/MobIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) --[[ Kills = GetServerVariable("[PH]Ix_aern_drk"); --print(Kills) moba = GetMobByID(16921018); mobb = GetMobByID(16921019); mobc = GetMobByID(16921020); if (Kills == 0) then player:messageSpecial(UNKNOWN_PRESENCE); elseif (Kills == 1) then player:messageSpecial(NONE_HOSTILE); elseif (Kills == 2) then player:messageSpecial(NONE_HOSTILE);--(SHEER_ANIMOSITY); elseif (Kills == 3) then moba:setSpawn(player:getXPos(),player:getYPos(),player:getZPos()); -- Change MobSpawn to Players @pos. SpawnMob(16921018,180):updateClaim(player); mobb:setSpawn(player:getXPos(),player:getYPos(),player:getZPos()); -- Change MobSpawn to Players @pos. SpawnMob(16921019,180):updateClaim(player); mobc:setSpawn(player:getXPos(),player:getYPos(),player:getZPos()); -- Change MobSpawn to Players @pos. SpawnMob(16921020,180):updateClaim(player); GetNPCByID(16921028):hideNPC(900); if (math.random(0,1) == 1) then -- random do select which item do drop. Will select one item 100% of the time. SetDropRate(4397,1854,000); else SetDropRate(4397,1902,000); end end ]]-- end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); end;
gpl-3.0
xTVaser/ramwatches
docs/samples/games/sample_layouts.lua
1
3121
-- Layouts to use with sample.lua. package.loaded.utils = nil local utils = require 'utils' local subclass = utils.subclass package.loaded.layouts = nil local layoutsModule = require 'layouts' local Layout = layoutsModule.Layout local layouts = {} layouts.positionAndVelocity = subclass(Layout) function layouts.positionAndVelocity:init() self:setUpdatesPerSecond(30) self.window:setSize(400, 200) self:addLabel{x=6, y=6, fontSize=12, fontName="Consolas"} self:addItem(self.game.posX) self:addItem(self.game.posY) self:addItem(self.game.posZ) self:addItem(self.game.velX) self:addItem(self.game.velY) self:addItem(self.game.velZ) end layouts.displayExamples = subclass(Layout) function layouts.displayExamples:init() self:setUpdatesPerSecond(30) -- Let's have multiple labels which are spaced vertically across the window -- automatically. self:activateAutoPositioningY() self.window:setSize(400, 250) self.labelDefaults = {fontSize=12, fontName="Consolas"} self:addLabel() -- You can specify display options. self:addItem(self.game.posX, {afterDecimal=5, beforeDecimal=5, signed=true}) -- Display a Vector3Value. self:addItem(self.game.pos, {narrow=true}) self:addLabel() -- addItem() can take a string constant. self:addItem("----------") self:addLabel() -- addItem() can take a function that returns a string. self:addItem( function() local vx = self.game.velX:get() local vy = self.game.velY:get() local speedXY = math.sqrt(vx*vx + vy*vy) return "Speed XY: "..utils.floatToStr(speedXY) end ) end layouts.positionRecording = subclass(Layout) function layouts.positionRecording:init() -- This update method ensures that we record every frame, but this may incur -- a performance hit. If you want performance and it's OK to miss frames, -- use setUpdatesPerSecond() instead. self:setBreakpointUpdateMethod() self:activateAutoPositioningY() self.window:setSize(400, 160) self.labelDefaults = {fontSize=12, fontName="Consolas"} -- Display position. self:addLabel() self:addItem(self.game.posX) self:addItem(self.game.posY) self:addItem(self.game.posZ) local tabSeparatedPosition = function() local positionComponents = { self.game.posX:display{afterDecimal=8, nolabel=true}, self.game.posY:display{afterDecimal=8, nolabel=true}, self.game.posZ:display{afterDecimal=8, nolabel=true}, } return table.concat(positionComponents, '\t') end -- This adds a GUI element with a button. Click the button to start recording -- stats to a file. For every frame of recording, one line is added to -- the file. -- -- Look for the output .txt file in: -- A. The folder you saved your .CT file -- B. The folder with your Cheat Engine installation, if not running from a -- saved .CT file -- -- Because we separated the data elements with linebreaks and tabs (\t), we -- can easily paste the .txt contents into a spreadsheet for analysis. self:addFileWriter( tabSeparatedPosition, 'ram_watch_output.txt') end return { layouts = layouts, }
mit
Xileck/forgottenserver
config.lua
18
2408
-- Combat settings -- NOTE: valid values for worldType are: "pvp", "no-pvp" and "pvp-enforced" worldType = "pvp" hotkeyAimbotEnabled = true protectionLevel = 1 killsToRedSkull = 3 killsToBlackSkull = 6 pzLocked = 60000 removeChargesFromRunes = true timeToDecreaseFrags = 24 * 60 * 60 * 1000 whiteSkullTime = 15 * 60 * 1000 stairJumpExhaustion = 2000 experienceByKillingPlayers = false expFromPlayersLevelRange = 75 -- Connection Config -- NOTE: maxPlayers set to 0 means no limit ip = "127.0.0.1" bindOnlyGlobalAddress = false loginProtocolPort = 7171 gameProtocolPort = 7172 statusProtocolPort = 7171 maxPlayers = 0 motd = "Welcome to The Forgotten Server!" onePlayerOnlinePerAccount = true allowClones = false serverName = "Forgotten" statusTimeout = 5000 replaceKickOnLogin = true maxPacketsPerSecond = 25 -- Deaths -- NOTE: Leave deathLosePercent as -1 if you want to use the default -- death penalty formula. For the old formula, set it to 10. For -- no skill/experience loss, set it to 0. deathLosePercent = -1 -- Houses -- NOTE: set housePriceEachSQM to -1 to disable the ingame buy house functionality housePriceEachSQM = 1000 houseRentPeriod = "never" -- Item Usage timeBetweenActions = 200 timeBetweenExActions = 1000 -- Map -- NOTE: set mapName WITHOUT .otbm at the end mapName = "forgotten" mapAuthor = "Komic" -- Market marketOfferDuration = 30 * 24 * 60 * 60 premiumToCreateMarketOffer = true checkExpiredMarketOffersEachMinutes = 60 maxMarketOffersAtATimePerPlayer = 100 -- MySQL mysqlHost = "127.0.0.1" mysqlUser = "forgottenserver" mysqlPass = "" mysqlDatabase = "forgottenserver" mysqlPort = 3306 mysqlSock = "" -- Misc. allowChangeOutfit = true freePremium = false kickIdlePlayerAfterMinutes = 15 maxMessageBuffer = 4 emoteSpells = false classicEquipmentSlots = false -- Rates -- NOTE: rateExp is not used if you have enabled stages in data/XML/stages.xml rateExp = 5 rateSkill = 3 rateLoot = 2 rateMagic = 3 rateSpawn = 1 -- Monsters deSpawnRange = 2 deSpawnRadius = 50 -- Stamina staminaSystem = true -- Scripts warnUnsafeScripts = true convertUnsafeScripts = true -- Startup -- NOTE: defaultPriority only works on Windows and sets process -- priority, valid values are: "normal", "above-normal", "high" defaultPriority = "high" startupDatabaseOptimization = false -- Status server information ownerName = "" ownerEmail = "" url = "https://otland.net/" location = "Sweden"
gpl-2.0
nesstea/darkstar
scripts/zones/Sauromugue_Champaign/npcs/Tiger_Bones.lua
12
1894
----------------------------------- -- Area: Sauromugue Champaign -- NPC: Tiger Bones -- Involed in Quest: The Fanged One. -- @pos 666 -8 -379 120 ------------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ------------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getQuestStatus(WINDURST,THE_FANGED_ONE) == QUEST_ACCEPTED) then local oldTiger = 17268808; local tigerAction = GetMobAction(oldTiger); local fangedOneCS = player:getVar("TheFangedOneCS"); if (player:hasKeyItem(OLD_TIGERS_FANG) == false and fangedOneCS == 2) then player:addKeyItem(OLD_TIGERS_FANG); player:messageSpecial(KEYITEM_OBTAINED, OLD_TIGERS_FANG); player:setVar("TheFangedOneCS", 0); elseif (tigerAction == ACTION_NONE and fangedOneCS == 1) then SpawnMob(oldTiger):addStatusEffect(EFFECT_POISON,40,10,210); player:messageSpecial(OLD_SABERTOOTH_DIALOG_I); else player:messageSpecial(NOTHING_HAPPENS); end; end; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Waughroon_Shrine/bcnms/shattering_stars.lua
13
1930
----------------------------------- -- Area: Waughroon Shrine -- Name: Shattering stars - Maat Fight -- @pos -345 104 -260 144 ----------------------------------- package.loaded["scripts/zones/Waughroon_Shrine/TextIDs"] = nil; ----------------------------------- 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) -- player:messageSpecial(107); end; -- Leaving the BCNM by every mean possible, given by the LeaveCode -- 1=Select Exit on circle -- 2=Winning the BC -- 3=Disconnected or warped out -- 4=Losing the BC -- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called -- from the core when a player disconnects or the time limit is up, etc function onBcnmLeave(player,instance,leavecode) -- print("leave code "..leavecode); if(leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,1,0); elseif(leavecode == 4) then player:startEvent(0x7d02); end end; function onEventUpdate(player,csid,option) -- print("bc update csid "..csid.." and option "..option); end; function onEventFinish(player,csid,option) -- print("bc finish csid "..csid.." and option "..option); if(csid == 0x7d01) then if(player:getQuestStatus(JEUNO,SHATTERING_STARS) == QUEST_ACCEPTED and player:getFreeSlotsCount() > 0) then player:addItem(4181); player:messageSpecial(ITEM_OBTAINED,4181); end local pjob = player:getMainJob(); player:setVar("maatDefeated",pjob); local maatsCap = player:getVar("maatsCap") if (bit.band(maatsCap, bit.lshift(1, (pjob -1))) ~= 1)then player:setVar("maatsCap",bit.bor(maatsCap, bit.lshift(1, (pjob -1)))) end player:addTitle(MAAT_MASHER); end end;
gpl-3.0
ld-test/fun-alloyed
tests/operators.lua
5
4619
-- -- All these functions are fully covered by Lua tests. -- This test just checks that all functions were defined correctly. -- print(op == operator) -- an alias --[[test true --test]] -------------------------------------------------------------------------------- -- Comparison operators -------------------------------------------------------------------------------- local comparators = { 'le', 'lt', 'eq', 'ne', 'ge', 'gt' } for _k, op in iter(comparators) do print('op', op) print('==') print('num:') print(operator[op](0, 1)) print(operator[op](1, 0)) print(operator[op](0, 0)) print('str:') print(operator[op]("abc", "cde")) print(operator[op]("cde", "abc")) print(operator[op]("abc", "abc")) print('') end --[[test op le == num: true false true str: true false true op lt == num: true false false str: true false false op eq == num: false false true str: false false true op ne == num: true true false str: true true false op ge == num: false true true str: false true true op gt == num: false true false str: false true false --test]] -------------------------------------------------------------------------------- -- Arithmetic operators -------------------------------------------------------------------------------- print(operator.add(-1.0, 1.0)) print(operator.add(0, 0)) print(operator.add(12, 2)) --[[test 0 0 14 --test]] print(operator.div(10, 2)) print(operator.div(10, 3)) print(operator.div(-10, 3)) --[[test 5 3.3333333333333 -3.3333333333333 --test]] print(operator.floordiv(10, 3)) print(operator.floordiv(11, 3)) print(operator.floordiv(12, 3)) print(operator.floordiv(-10, 3)) print(operator.floordiv(-11, 3)) print(operator.floordiv(-12, 3)) --[[test 3 3 4 -4 -4 -4 --test]] print(operator.intdiv(10, 3)) print(operator.intdiv(11, 3)) print(operator.intdiv(12, 3)) print(operator.intdiv(-10, 3)) print(operator.intdiv(-11, 3)) print(operator.intdiv(-12, 3)) --[[test 3 3 4 -3 -3 -4 --test]] print(operator.truediv(10, 3)) print(operator.truediv(11, 3)) print(operator.truediv(12, 3)) print(operator.truediv(-10, 3)) print(operator.truediv(-11, 3)) print(operator.truediv(-12, 3)) --[[test 3.3333333333333 3.6666666666667 4 -3.3333333333333 -3.6666666666667 -4 --test]] print(operator.mod(10, 2)) print(operator.mod(10, 3)) print(operator.mod(-10, 3)) --[[test 0 1 2 --test]] print(operator.mul(10, 0.1)) print(operator.mul(0, 0)) print(operator.mul(-1, -1)) --[[test 1 0 1 --test]] print(operator.neq(1)) print(operator.neq(0) == 0) print(operator.neq(-0) == 0) print(operator.neq(-1)) --[[test -1 true true 1 --test]] print(operator.unm(1)) print(operator.unm(0) == 0) print(operator.unm(-0) == 0) print(operator.unm(-1)) --[[test -1 true true 1 --test]] print(operator.pow(2, 3)) print(operator.pow(0, 10)) print(operator.pow(2, 0)) --[[test 8 0 1 --test]] print(operator.sub(2, 3)) print(operator.sub(0, 10)) print(operator.sub(2, 2)) --[[test -1 -10 0 --test]] -------------------------------------------------------------------------------- -- String operators -------------------------------------------------------------------------------- print(operator.concat("aa", "bb")) print(operator.concat("aa", "")) print(operator.concat("", "bb")) --[[test aabb aa bb --test]] print(operator.len("")) print(operator.len("ab")) print(operator.len("abcd")) --[[test 0 2 4 --test]] print(operator.length("")) print(operator.length("ab")) print(operator.length("abcd")) --[[test 0 2 4 --test]] ---------------------------------------------------------------------------- -- Logical operators ---------------------------------------------------------------------------- print(operator.land(true, true)) print(operator.land(true, false)) print(operator.land(false, true)) print(operator.land(false, false)) print(operator.land(1, 0)) print(operator.land(0, 1)) print(operator.land(1, 1)) print(operator.land(0, 0)) --[[test true false false false 0 1 1 0 --test]] print(operator.lor(true, true)) print(operator.lor(true, false)) print(operator.lor(false, true)) print(operator.lor(false, false)) print(operator.lor(1, 0)) print(operator.lor(0, 1)) print(operator.lor(1, 1)) print(operator.lor(0, 0)) --[[test true true true false 1 0 1 0 --test]] print(operator.lnot(true)) print(operator.lnot(false)) print(operator.lor(1)) print(operator.lor(0)) --[[test false true 1 0 --test]] print(operator.truth(true)) print(operator.truth(false)) print(operator.truth(1)) print(operator.truth(0)) print(operator.truth(nil)) print(operator.truth("")) print(operator.truth({})) --[[test true false true true false true true --test]]
mit
UnfortunateFruit/darkstar
scripts/zones/Den_of_Rancor/npcs/_4g3.lua
10
2115
----------------------------------- -- Area: Den of Rancor -- NPC: Lantern (SW) -- @pos -59 45 24 160 ----------------------------------- package.loaded["scripts/zones/Den_of_Rancor/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Den_of_Rancor/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local Lantern_ID = 17433047 local LSW = GetNPCByID(Lantern_ID):getAnimation(); local LNW = GetNPCByID(Lantern_ID+1):getAnimation(); local LNE = GetNPCByID(Lantern_ID+2):getAnimation(); local LSE = GetNPCByID(Lantern_ID+3):getAnimation(); -- Trade Crimson Rancor Flame if(trade:hasItemQty(1139,1) and trade:getItemCount() == 1) then if (LSW == 8) then player:messageSpecial(LANTERN_OFFSET + 7); -- already lit elseif(LSW == 9)then npc:openDoor(LANTERNS_STAY_LIT); local ALL = LNW+LNE+LSE; player:tradeComplete(); player:addItem(1138); -- Unlit Lantern if ALL == 27 then player:messageSpecial(LANTERN_OFFSET + 9); elseif ALL == 26 then player:messageSpecial(LANTERN_OFFSET + 10); elseif ALL == 25 then player:messageSpecial(LANTERN_OFFSET + 11); elseif ALL == 24 then player:messageSpecial(LANTERN_OFFSET + 12); GetNPCByID(Lantern_ID+3):closeDoor(1); GetNPCByID(Lantern_ID+2):closeDoor(1); GetNPCByID(Lantern_ID+1):closeDoor(1); GetNPCByID(Lantern_ID):closeDoor(1); GetNPCByID(Lantern_ID+4):openDoor(30); GetNPCByID(Lantern_ID+3):openDoor(30); GetNPCByID(Lantern_ID+2):openDoor(30); GetNPCByID(Lantern_ID+1):openDoor(30); GetNPCByID(Lantern_ID):openDoor(30); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local npca = npc:getAnimation() if (npca == 8) then player:messageSpecial(LANTERN_OFFSET + 7); -- already lit else player:messageSpecial(LANTERN_OFFSET + 20); -- unlit end return 0; end;
gpl-3.0
Mashape/kong
spec/01-unit/01-db/05-cassandra_spec.lua
2
3510
local connector = require "kong.db.strategies.cassandra.connector" local cassandra = require "cassandra" local helpers = require "spec.helpers" describe("kong.db [#cassandra] connector", function() describe(".new()", function() local test_conf = helpers.test_conf local test_conf_lb_policy = test_conf.cassandra_lb_policy local test_conf_local_datacenter = test_conf.cassandra_local_datacenter lazy_teardown(function() test_conf.cassandra_lb_policy = test_conf_lb_policy test_conf.cassandra_local_datacenter = test_conf_local_datacenter end) it("sets serial_consistency to serial if LB policy is not DCAware", function() for _, policy in ipairs({ "RoundRobin", "RequestRoundRobin" }) do test_conf.cassandra_lb_policy = policy local c = assert(connector.new(test_conf)) assert.equal(cassandra.consistencies.serial, c.opts.serial_consistency) end end) it("sets serial_consistency to local_serial if LB policy is DCAware", function() test_conf.cassandra_local_datacenter = "dc1" for _, policy in ipairs({ "DCAwareRoundRobin", "RequestDCAwareRoundRobin" }) do test_conf.cassandra_lb_policy = policy local c = assert(connector.new(test_conf)) assert.equal(cassandra.consistencies.local_serial, c.opts.serial_consistency) end end) end) describe(":infos()", function() it("returns infos db_ver always with two digit groups divided with dot (.)", function() local infos = connector.infos{ major_version = 2, major_minor_version = "2.10" } assert.same({ db_desc = "keyspace", db_ver = "2.10", strategy = "Cassandra", }, infos) infos = connector.infos{ major_version = 2, major_minor_version = "2.10.1" } assert.same({ db_desc = "keyspace", db_ver = "2.10", strategy = "Cassandra", }, infos) infos = connector.infos{ major_version = 3, major_minor_version = "3.7" } assert.same({ db_desc = "keyspace", db_ver = "3.7", strategy = "Cassandra", }, infos) end) it("returns infos with db_ver as \"unknown\" when missing major_minor_version", function() local infos = connector.infos{ major_version = 2 } assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) infos = connector.infos{ major_version = 3 } assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) infos = connector.infos{} assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) end) it("returns infos with db_ver as \"unknown\" when invalid major_minor_version", function() local infos = connector.infos{ major_version = 2, major_minor_version = "invalid" } assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) infos = connector.infos{ major_version = 3, major_minor_version = "invalid" } assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) infos = connector.infos{ major_minor_version = "invalid" } assert.same({ db_desc = "keyspace", db_ver = "unknown", strategy = "Cassandra", }, infos) end) end) end)
apache-2.0
nesstea/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/qm7.lua
57
2181
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: qm7 (??? - Ancient Papyrus Shreds) -- Involved in Quest: In Defiant Challenge -- @pos 105.275 -32 92.551 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(ANCIENT_PAPYRUS_SHRED1); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED1); end if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1088, 1); player:messageSpecial(ITEM_OBTAINED, 1088); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088); end end if (player:hasItem(1088)) then player:delKeyItem(ANCIENT_PAPYRUS_SHRED1); player:delKeyItem(ANCIENT_PAPYRUS_SHRED2); player:delKeyItem(ANCIENT_PAPYRUS_SHRED3); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/The_Eldieme_Necropolis/npcs/qm7.lua
57
2181
----------------------------------- -- Area: The Eldieme Necropolis -- NPC: qm7 (??? - Ancient Papyrus Shreds) -- Involved in Quest: In Defiant Challenge -- @pos 105.275 -32 92.551 195 ----------------------------------- package.loaded["scripts/zones/The_Eldieme_Necropolis/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/settings"); require("scripts/zones/The_Eldieme_Necropolis/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (OldSchoolG1 == false) then if (player:hasItem(1088) == false and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) == false and player:getQuestStatus(JEUNO,IN_DEFIANT_CHALLENGE) == QUEST_ACCEPTED) then player:addKeyItem(ANCIENT_PAPYRUS_SHRED1); player:messageSpecial(KEYITEM_OBTAINED,ANCIENT_PAPYRUS_SHRED1); end if (player:hasKeyItem(ANCIENT_PAPYRUS_SHRED1) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED2) and player:hasKeyItem(ANCIENT_PAPYRUS_SHRED3)) then if (player:getFreeSlotsCount() >= 1) then player:addItem(1088, 1); player:messageSpecial(ITEM_OBTAINED, 1088); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 1088); end end if (player:hasItem(1088)) then player:delKeyItem(ANCIENT_PAPYRUS_SHRED1); player:delKeyItem(ANCIENT_PAPYRUS_SHRED2); player:delKeyItem(ANCIENT_PAPYRUS_SHRED3); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/black_bubble-eye.lua
18
1336
----------------------------------------- -- ID: 4311 -- Item: Black Bubble-Eye -- Food Effect: 5 Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,4311); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, 2); target:addMod(MOD_MND, -4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, 2); target:delMod(MOD_MND, -4); end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/zones/Upper_Jeuno/npcs/Migliorozz.lua
38
1033
----------------------------------- -- Area: Upper Jeuno -- NPC: Migliorozz -- Type: Standard NPC -- @zone: 244 -- @pos -37.760 -2.499 12.924 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x272a); 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
nesstea/darkstar
scripts/globals/spells/bluemagic/tail_slap.lua
21
2101
----------------------------------------- -- Spell: Tail Slap -- Delivers an area attack. Additional effect: "Stun." Damage varies with TP -- Spell cost: 77 MP -- Monster Type: Beastmen -- Spell Type: Physical (Blunt) -- Blue Magic Points: 4 -- Stat Bonus: MND+2 -- Level: 69 -- Casting Time: 1 seconds -- Recast Time: 28.5 seconds -- Skillchain Element: Water (can open Impaction and Induration; can close Reverberation and Fragmentation) -- Combos: Store TP ----------------------------------------- require("scripts/globals/bluemagic"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnMagicCastingCheck ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; ----------------------------------------- -- OnSpellCast ----------------------------------------- function onSpellCast(caster,target,spell) local dINT = caster:getStat(MOD_INT) - target:getStat(MOD_INT); local resist = applyResistanceEffect(caster,spell,target,dINT,SKILL_BLU,0,EFFECT_STUN) local params = {}; -- This data should match information on http://wiki.ffxiclopedia.org/wiki/Calculating_Blue_Magic_Damage params.tpmod = TPMOD_ATTACK; params.dmgtype = DMGTYPE_H2H; params.scattr = SC_REVERBERATION; params.numhits = 1; params.multiplier = 1.625; params.tp150 = 1.625; params.tp300 = 1.625; params.azuretp = 1.625; params.duppercap = 75; params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.5; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; local damage = BluePhysicalSpell(caster, target, spell, params); damage = BlueFinalAdjustments(caster, target, spell, damage, params); if (resist > 0.5) then -- This line may need adjusting for retail accuracy. target:addStatusEffect(EFFECT_STUN, 1, 0, 5 * resist); -- pre-resist duration needs confirmed/adjusted end return damage; end;
gpl-3.0
UnfortunateFruit/darkstar
scripts/globals/items/warm_egg.lua
35
1186
----------------------------------------- -- ID: 4602 -- Item: warm_egg -- Food Effect: 5Min, All Races ----------------------------------------- -- Health 18 -- Magic 18 ----------------------------------------- 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,4602); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 18); target:addMod(MOD_MP, 18); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 18); target:delMod(MOD_MP, 18); end;
gpl-3.0
bowlofstew/Macaroni
Main/App/Source/test/lua/Macaroni/Model/DocumentTests/FunctionTests.lua
2
2126
-------------------------------------------------------------------------------- -- Copyright 2011 Tim Simpson -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. -------------------------------------------------------------------------------- require "Macaroni.Model.Document"; -- These are for the stand alone tests. local Document = Macaroni.Model.Document; Test.register( { name = "Document Tests - Functions", --[[init = { ["Constructing and reading a file"] = function(this) this.doc = Macaroni.Model.Document.New(this.testFile); end }, shutdown = { },]]-- tests={ ["Simple function."] = function(this) --pddsfs(); doc = Document.New("SimpleMain"); doc:Read([[ // Comment. namespace A::B::C { void DoSomething() { std::cout << "Hello, EARTH!"; } // comment } ]]); Test.assert(1, #(doc.Namespaces)); Test.assert("A::B::C", tostring(doc.Namespaces[0])); abc = Namespaces[0]; func = abc.GetFunctions(0); func. end, --[[["Namespaces are generated correctly."] = function(this) Test.assert("3", #(this.file.Namespaces)); end]]-- } } -- End of Test table. ); --[[ Test.register( { name = "Document Tests - Classes", init = { ["Constructing and reading a file"] = function(this) this.doc = Macaroni.Model.Document.New(this.testFile); end }, shutdown = { },]]--
apache-2.0
anoidgit/Residue-RNN
test/testrnn.lua
1
4511
require 'paths' require 'rnn' local dl = require 'dataload' torch.setdefaulttensortype('torch.FloatTensor') function savemodel(fname,modelsave) file=torch.DiskFile(fname,'w') file:writeObject(modelsave) file:close() end startlr=0.005 minlr=0.000001 saturate=120--'epoch at which linear decayed LR will reach minlr' batchsize=256 maxepoch=200 earlystop=15 cutoff=5 seqlen=64 hiddensize=200 progress=true savepath=paths.concat(dl.SAVE_PATH, 'rnnlm') id="20160504rnn" local trainset, validset, testset = dl.loadPTB({batchsize,1,1}) print("Vocabulary size : "..#trainset.ivocab) print("Train set split into "..batchsize.." sequences of length "..trainset:size()) local lm = nn.Sequential() -- input layer (i.e. word embedding space) local lookup = nn.LookupTable(#trainset.ivocab, hiddensize) lookup.maxnormout = -1 -- prevent weird maxnormout behaviour lm:add(lookup) -- input is seqlen x batchsize lm:add(nn.SplitTable(1)) -- tensor to table of tensors -- rnn layers local stepmodule = nn.Sequential() -- applied at each time-step local inputsize = hiddensize local rm = nn.Sequential() -- input is {x[t], h[t-1]} :add(nn.ParallelTable() :add(i==1 and nn.Identity() or nn.Linear(inputsize, hiddensize)) -- input layer :add(nn.Linear(hiddensize, hiddensize))) -- recurrent layer :add(nn.CAddTable()) -- merge :add(nn.Sigmoid()) -- transfer rnn = nn.Recurrence(rm, hiddensize, 1) stepmodule:add(rnn) inputsize = hiddensize -- output layer stepmodule:add(nn.Linear(inputsize, #trainset.ivocab)) stepmodule:add(nn.LogSoftMax()) -- encapsulate stepmodule into a Sequencer lm:add(nn.Sequencer(stepmodule)) print"Language Model:" print(lm) -- target is also seqlen x batchsize. local targetmodule = nn.SplitTable(1) --[[ loss function ]]-- local crit = nn.ClassNLLCriterion() local criterion = nn.SequencerCriterion(crit) --[[ experiment log ]]-- -- is saved to file every time a new validation minima is found local xplog = {} xplog.dataset = 'PennTreeBank' xplog.vocab = trainset.vocab -- will only serialize params xplog.model = nn.Serial(lm) xplog.model:mediumSerial() --xplog.model = lm xplog.criterion = criterion xplog.targetmodule = targetmodule -- keep a log of NLL for each epoch xplog.trainppl = {} xplog.valppl = {} -- will be used for early-stopping xplog.minvalppl = 99999999 xplog.epoch = 0 local ntrial = 0 paths.mkdir(savepath) local epoch = 1 lr = startlr trainsize=trainset:size() validsize=validset:size() while epoch <= maxepoch do print("") print("Epoch #"..epoch.." :") -- 1. training local a = torch.Timer() lm:training() local sumErr = 0 for i, inputs, targets in trainset:subiter(seqlen, trainsize) do targets = targetmodule:forward(targets) -- forward local outputs = lm:forward(inputs) local err = criterion:forward(outputs, targets) sumErr = sumErr + err -- backward local gradOutputs = criterion:backward(outputs, targets) lm:zeroGradParameters() lm:backward(inputs, gradOutputs) -- update lm:updateParameters(lr) -- affects params if progress then xlua.progress(math.min(i + seqlen, trainsize), trainsize) end if i % 1000 == 0 then collectgarbage() end end -- learning rate decay lr = lr + (minlr - startlr)/saturate lr = math.max(minlr, lr) print("learning rate", lr) local speed = a:time().real/trainsize print(string.format("Speed : %f sec/batch ", speed)) local ppl = torch.exp(sumErr/trainsize) print("Training PPL : "..ppl) xplog.trainppl[epoch] = ppl -- 2. cross-validation lm:evaluate() local sumErr = 0 for i, inputs, targets in validset:subiter(seqlen, validsize) do targets = targetmodule:forward(targets) local outputs = lm:forward(inputs) local err = criterion:forward(outputs, targets) sumErr = sumErr + err end local ppl = torch.exp(sumErr/validsize) print("Validation PPL : "..ppl) xplog.valppl[epoch] = ppl ntrial = ntrial + 1 -- early-stopping if ppl < xplog.minvalppl then -- save best version of model xplog.minvalppl = ppl xplog.epoch = epoch local filename = paths.concat(savepath, id..'.t7') print("Found new minima. Saving to "..filename) torch.save(filename, xplog) savemodel(filename..'.lm',lm) ntrial = 0 elseif ntrial >= earlystop then print("No new minima found after "..ntrial.." epochs.") print("Stopping experiment.") break else lr=lr/2 end collectgarbage() epoch = epoch + 1 end print("Evaluate model using : ") print("th scripts/evaluate-rnnlm.lua --xplogpath "..paths.concat(savepath, id..'.t7'))
bsd-3-clause
UnfortunateFruit/darkstar
scripts/zones/AlTaieu/npcs/_0x3.lua
8
2001
----------------------------------- -- Area: Al'Taieu -- NPC: Rubious Crystal (East Tower) -- @pos 683.718 -6.250 -222.167 33 ----------------------------------- package.loaded["scripts/zones/AlTaieu/TextIDs"] = nil; ----------------------------------- require("scripts/zones/AlTaieu/TextIDs"); require("scripts/zones/AlTaieu/mobIDs"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ---------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus") == 2 and player:getVar("[SEA][AlTieu]EastTower") == 0 and player:getVar("[SEA][AlTieu]EastTowerCS") == 0) then player:messageSpecial(OMINOUS_SHADOW); SpawnMob(EastTowerAern,180):updateClaim(player); SpawnMob(EastTowerAern+1,180):updateClaim(player); SpawnMob(EastTowerAern+2,180):updateClaim(player); elseif(player:getCurrentMission(COP) == GARDEN_OF_ANTIQUITY and player:getVar("PromathiaStatus") == 2 and player:getVar("[SEA][AlTieu]EastTower") == 1 and player:getVar("[SEA][AlTieu]EastTowerCS") == 0) then player:startEvent(0x00A3); else player:messageSpecial(NOTHING_OF_INTEREST); 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 == 0x00A3) then player:setVar("[SEA][AlTieu]EastTowerCS", 1); player:setVar("[SEA][AlTieu]EastTower", 0); end end;
gpl-3.0
nesstea/darkstar
scripts/globals/items/moon_ball.lua
18
1162
----------------------------------------- -- ID: 4568 -- Item: moon_ball -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 3 -- Magic 3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4568); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 3); target:addMod(MOD_MP, 3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 3); target:delMod(MOD_MP, 3); end;
gpl-3.0
FailcoderAddons/supervillain-ui
SVUI_Skins/components/blizzard/timemanager.lua
2
2481
--[[ ############################################################################## S V U I By: Failcoder ############################################################################## --]] --[[ GLOBALS ]]-- local _G = _G; local unpack = _G.unpack; local select = _G.select; --[[ ADDON ]]-- local SV = _G['SVUI']; local L = SV.L; local MOD = SV.Skins; local Schema = MOD.Schema; --[[ ########################################################## TIMEMANAGER MODR ########################################################## ]]-- local function TimeManagerStyle() if SV.db.Skins.blizzard.enable ~= true or SV.db.Skins.blizzard.timemanager ~= true then return end SV.API:Set("Window", TimeManagerFrame, true) SV.API:Set("CloseButton", TimeManagerFrameCloseButton) TimeManagerFrameInset:Die() SV.API:Set("DropDown", TimeManagerAlarmHourDropDown, 80) SV.API:Set("DropDown", TimeManagerAlarmMinuteDropDown, 80) SV.API:Set("DropDown", TimeManagerAlarmAMPMDropDown, 80) TimeManagerAlarmMessageEditBox:SetStyle("Editbox") TimeManagerAlarmEnabledButton:SetStyle("CheckButton") TimeManagerMilitaryTimeCheck:SetStyle("CheckButton") TimeManagerLocalTimeCheck:SetStyle("CheckButton") TimeManagerStopwatchFrame:RemoveTextures() TimeManagerStopwatchCheck:SetStyle("!_Frame", "Default") TimeManagerStopwatchCheck:GetNormalTexture():SetTexCoord(unpack(_G.SVUI_ICON_COORDS)) TimeManagerStopwatchCheck:GetNormalTexture():InsetPoints() local sWatch = TimeManagerStopwatchCheck:CreateTexture(nil, "OVERLAY") sWatch:SetColorTexture(1, 1, 1, 0.3) sWatch:SetPoint("TOPLEFT", TimeManagerStopwatchCheck, 2, -2) sWatch:SetPoint("BOTTOMRIGHT", TimeManagerStopwatchCheck, -2, 2) TimeManagerStopwatchCheck:SetHighlightTexture(sWatch) StopwatchFrame:RemoveTextures() StopwatchFrame:SetStyle("Frame", 'Transparent') StopwatchFrame.Panel:SetPoint("TOPLEFT", 0, -17) StopwatchFrame.Panel:SetPoint("BOTTOMRIGHT", 0, 2) StopwatchTabFrame:RemoveTextures() SV.API:Set("CloseButton", StopwatchCloseButton) SV.API:Set("PageButton", StopwatchPlayPauseButton) SV.API:Set("PageButton", StopwatchResetButton) StopwatchPlayPauseButton:SetPoint("RIGHT", StopwatchResetButton, "LEFT", -4, 0) StopwatchResetButton:SetPoint("BOTTOMRIGHT", StopwatchFrame, "BOTTOMRIGHT", -4, 6) end --[[ ########################################################## MOD LOADING ########################################################## ]]-- MOD:SaveBlizzardStyle("Blizzard_TimeManager",TimeManagerStyle)
mit
dios-game/dios-cocos-samples
src/lua-coin-tree/Resources/src/dxm/data_structures/list.lua
4
2231
--region *.lua --Date --此文件由[BabeLua]插件自动生成 dxm = dxm or {} -- 链表节点 dxm.CNode = class("CNode") local CNode = dxm.CNode function CNode:ctor() self.prev = nil self.next = nil self.value = nil end -- 链表 dxm.CList = class("CList") local CList = dxm.CList function CList:ctor() self.first = nil -- 头 self.last = nil -- 尾 self.size = 0 -- 容量 end -- 成员函数 function CList:Clear() local node = self.first while node ~= nil do local next_node = node.next node.prev = nil node.value = nil node.next = nil node = next_node end self.first = nil self.last = nil end function CList:Erase(node) if node == nil then return end local node_prev = node.prev local node_next = node.next if node_prev ~= nil then node_prev.next = node_next end if node_next ~= nil then node_next.prev = node_prev end if node == self.first then self.first = node.next end if node == self.last then self.last = node.prev end self.size = self.size - 1 node.prev = nil node.next = nil node.value = nil end function CList:PushBack(value) local node = { prev = self.last, value = value } if self.last ~= nil then self.last.next = node end self.last = node if self.first == nil then self.first = node end self.size = self.size + 1 end function CList:PopFront() local node = self.first if node == nil then return nil end self.first = node.next if self.last == node then self.last = nil end self.size = self.size - 1 node.next = nil node.prev = nil return node.value end function CList:Begin() local node = self.first return function () if not node then return nil end local ret = node node = node.next return ret end end function CList:End() local node = self.last return function () if not node then return nil end local ret = node node = node.prev return ret end end return CList --endregion
mit
dstodev/MC-Fluid-Tank-Controller
lib/schmitt_trigger.lua
1
1105
local Trigger = {} Trigger.__index = Trigger setmetatable(Trigger, { __call = function (cls, ...) return cls.new(...) end, }) function Trigger.new(left, right, left_callback, right_callback) local self = {} setmetatable(self, Trigger) self._left = left self._right = right self._position = 0 self._state = -1 self._left_callback = left_callback self._right_callback = right_callback return self end function Trigger:increment(value) self._position = self._position + value self:_manage_state() end function Trigger:decrement(value) self._position = self._position - value self:_manage_state() end function Trigger:update(value) self._position = value self:_manage_state() end function Trigger:_manage_state() if (self._state == 0 or self._state == -1) and self._position > self._right then self._right_callback() self._state = 1 elseif (self._state == 1 or self._state == -1) and self._position < self._left then self._left_callback() self._state = 0 end end return Trigger
mit
drakmaniso/Flapoline
src/dot.lua
1
1037
Dot = {} Dot.__index = Dot --------------------------------------------------------------------------------------------------- Dot.radius = 4 Dot.segments = 6 --------------------------------------------------------------------------------------------------- function Dot:new(x, y) object = { x = x, y = y, age = 0} setmetatable(object, self) return object end --------------------------------------------------------------------------------------------------- function Dot:move(dx) self.x = self.x - dx self.age = self.age + dx / 16 end --------------------------------------------------------------------------------------------------- function Dot:draw() local alpha = math.max(0, 29 - self.age) love.graphics.setColor(10, 10, 10, alpha) love.graphics.circle("fill", self.x, self.y, Dot.radius, Dot.segments) end --------------------------------------------------------------------------------------------------- -- Copyright (c) 2014 - Laurent Moussault <moussault.laurent@gmail.com>
gpl-3.0
dpino/snabb
src/program/packetblaster/synth/synth.lua
14
1360
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local config = require("core.config") local main = require("core.main") local Synth = require("apps.test.synth").Synth local lib = require("core.lib") local packetblaster = require("program.packetblaster.packetblaster") local long_opts = { duration = "D", help = "h", src = "s", dst = "d", sizes = "S", } local function show_usage (code) print(require("program.packetblaster.synth.README_inc")) main.exit(code) end function run (args) local c = config.new() local handlers = {} local opts = {} function handlers.D (arg) opts.duration = assert(tonumber(arg), "duration is not a number!") end function handlers.h () show_usage(0) end local source local destination local sizes function handlers.s (arg) source = arg end function handlers.d (arg) destination = arg end function handlers.S (arg) sizes = {} for size in string.gmatch(arg, "%d+") do sizes[#sizes+1] = tonumber(size) end end args = lib.dogetopt(args, handlers, "hD:s:d:S:", long_opts) config.app(c, "source", Synth, { sizes = sizes, src = source, dst = destination }) packetblaster.run_loadgen(c, args, opts) end
apache-2.0
Kthulupwns/darkstar
scripts/zones/Southern_San_dOria/npcs/Femitte.lua
17
3106
----------------------------------- -- Area: Southern San d'Oria -- NPC: Femitte -- Involved in Quest: Lure of the Wildcat (San d'Oria), Distant Loyalties -- @pos -17 2 10 230 ------------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if(trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local DistantLoyaltiesProgress = player:getVar("DistantLoyaltiesProgress"); local DistantLoyalties = player:getQuestStatus(SANDORIA,DISTANT_LOYALTIES); local WildcatSandy = player:getVar("WildcatSandy"); if(player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,3) == false) then player:startEvent(0x0327); elseif (player:getFameLevel(SANDORIA) >= 4 and DistantLoyalties == 0) then player:startEvent(0x0297); elseif (DistantLoyalties == 1 and DistantLoyaltiesProgress == 1) then player:startEvent(0x0298); elseif (DistantLoyalties == 1 and DistantLoyaltiesProgress == 4 and player:hasKeyItem(MYTHRIL_HEARTS)) then player:startEvent(0x0299); else player:startEvent(0x295); 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 == 0x0327) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",3,true); elseif (csid == 0x0297 and option == 0) then player:addKeyItem(GOLDSMITHING_ORDER); player:messageSpecial(KEYITEM_OBTAINED,GOLDSMITHING_ORDER); player:addQuest(SANDORIA,DISTANT_LOYALTIES); player:setVar("DistantLoyaltiesProgress",1); elseif (csid == 0x0299) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13585); else player:delKeyItem(MYTHRIL_HEARTS); player:addItem(13585,1); player:messageSpecial(ITEM_OBTAINED,13585); player:setVar("DistantLoyaltiesProgress",0); player:completeQuest(SANDORIA,DISTANT_LOYALTIES); end; end; end; --------Other CS --0x7fb4 --0x0000 --0x0295 Standard dialog --0x0297 --0x0298 --0x0299 --0x02d5 --0x02eb --0x02ec --0x0327 Lure of the Wildcat --0x03b1 CS with small mythra dancer
gpl-3.0
FPtje/DarkRP
gamemode/modules/f4menu/cl_interface.lua
13
2912
DarkRP.openF4Menu = DarkRP.stub{ name = "openF4Menu", description = "Open the F4 menu.", parameters = { }, returns = { }, metatable = DarkRP } DarkRP.closeF4Menu = DarkRP.stub{ name = "closeF4Menu", description = "Close the F4 menu if it's open.", parameters = { }, returns = { }, metatable = DarkRP } DarkRP.toggleF4Menu = DarkRP.stub{ name = "toggleF4Menu", description = "Toggle the state of the F4 menu (open or closed).", parameters = { }, returns = { }, metatable = DarkRP } DarkRP.getF4MenuPanel = DarkRP.stub{ name = "getF4MenuPanel", description = "Get the F4 menu panel.", parameters = { }, returns = { { name = "panel", description = "The F4 menu panel. It will be invalid until the F4 menu has been opened.", type = "Panel", optional = false } }, metatable = DarkRP } DarkRP.addF4MenuTab = DarkRP.stub{ name = "addF4MenuTab", description = "Add a tab to the F4 menu.", parameters = { { name = "name", description = "The title of the tab.", type = "string", optional = false }, { name = "panel", description = "The panel of the tab.", type = "Panel", optional = false } }, returns = { { name = "index", description = "The index of the tab in the menu. This is the number you use for the tab in DarkRP.switchTabOrder.", type = "number" }, { name = "sheet", description = "The tab sheet.", type = "Panel" } }, metatable = DarkRP } DarkRP.removeF4MenuTab = DarkRP.stub{ name = "removeF4MenuTab", description = "Remove a tab from the F4 menu by name.", parameters = { { name = "name", description = "The name of the tab it should remove.", type = "string", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.switchTabOrder = DarkRP.stub{ name = "switchTabOrder", description = "Switch the order of two tabs.", parameters = { { name = "firstTab", description = "The number of the first tab (if it's the second tab, then this number is 2).", type = "number", optional = false }, { name = "secondTab", description = "The number of the second tab.", type = "number", optional = false } }, returns = { }, metatable = DarkRP } DarkRP.hookStub{ name = "F4MenuTabs", description = "Called when tabs are generated. Add and remove tabs in this hook.", parameters = { }, returns = { } }
mit
Kthulupwns/darkstar
scripts/zones/King_Ranperres_Tomb/npcs/Grounds_Tome.lua
34
1155
----------------------------------- -- Area: King Ranperre's Tomb -- NPC: Grounds Tome ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/groundsofvalor"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) startGov(GOV_EVENT_KING_RANPERRES_TOMB,player); end; ----------------------------------- -- onEventSelection ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); updateGov(player,csid,option,631,632,633,634,635,636,637,638,0,0); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); finishGov(player,csid,option,631,632,633,634,635,636,637,638,0,0,GOV_MSG_KING_RANPERRES_TOMB); end;
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Southern_San_dOria/npcs/Taumila.lua
17
2257
----------------------------------- -- Area: Northern San d'Oria -- NPC: Taumila -- Starts and Finishes Quest: Tiger's Teeth (R) -- @pos -140 -5 -8 230 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(SANDORIA,TIGER_S_TEETH) ~= QUEST_AVAILABLE) then if(trade:hasItemQty(884,3) and trade:getItemCount() == 3) then player:startEvent(0x023c); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local tigersTeeth = player:getQuestStatus(SANDORIA,TIGER_S_TEETH); if(player:getFameLevel(SANDORIA) >= 3 and tigersTeeth == QUEST_AVAILABLE) then player:startEvent(0x023e); elseif(tigersTeeth == QUEST_ACCEPTED) then player:startEvent(0x023f); elseif(tigersTeeth == QUEST_COMPLETED) then player:startEvent(0x023d); else player:startEvent(0x023b); 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 == 0x023e and option == 0) then player:addQuest(SANDORIA,TIGER_S_TEETH); elseif(csid == 0x023c) then player:tradeComplete(); player:addTitle(FANG_FINDER); player:addGil(GIL_RATE*2100); player:messageSpecial(GIL_OBTAINED,GIL_RATE*2100) if(player:getQuestStatus(SANDORIA,TIGER_S_TEETH) == QUEST_ACCEPTED) then player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,TIGER_S_TEETH); else player:addFame(SANDORIA,SAN_FAME*5); end end end;
gpl-3.0
mlody1039/ModernOts
data/npc/scripts/TP1/boat_liberty3.lua
1
2225
local keywordHandler = KeywordHandler:new() local npcHandler = NpcHandler:new(keywordHandler) NpcSystem.parseParameters(npcHandler) -- OTServ event handling functions start function onCreatureAppear(cid) npcHandler:onCreatureAppear(cid) end function onCreatureDisappear(cid) npcHandler:onCreatureDisappear(cid) end function onCreatureSay(cid, type, msg) npcHandler:onCreatureSay(cid, type, msg) end function onThink() npcHandler:onThink() end -- OTServ event handling functions end -- Don't forget npcHandler = npcHandler in the parameters. It is required for all StdModule functions! local travelNode = keywordHandler:addKeyword({'calassa'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to sail to Calassa for free?'}) travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, level = 0, cost = 0, destination = {x=31747, y=32718, z=6} }) travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Then stay here!'}) local travelNode = keywordHandler:addKeyword({'yalahar'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'Do you want to sail to Yalahar for free?'}) travelNode:addChildKeyword({'yes'}, StdModule.travel, {npcHandler = npcHandler, level = 0, cost = 0, destination = {x=601, y=669, z=6} }) travelNode:addChildKeyword({'no'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, reset = true, text = 'Then stay here!'}) keywordHandler:addKeyword({'sail'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I can take you to Calassa and Yalahar.'}) keywordHandler:addKeyword({'job'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I am the captain of this ship.'}) keywordHandler:addKeyword({'travel'}, StdModule.say, {npcHandler = npcHandler, onlyFocus = true, text = 'I can only offer you a trip to Calassa and Yalahar.'}) -- Makes sure the npc reacts when you say hi, bye etc. npcHandler:addModule(FocusModule:new())
gpl-3.0
Kthulupwns/darkstar
scripts/zones/PsoXja/npcs/_092.lua
9
1609
----------------------------------- -- Area: Pso'Xja -- NPC: _092 (Stone Gate) -- Notes: Spawns Gargoyle when triggered -- @pos -330.000 14.074 -261.600 9 ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/keyitems"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local X=player:getXPos(); if (npc:getAnimation() == 9) then if(X >= 339)then if(GetMobAction(16814083) == 0) then local Rand = math.random(1,10); if (Rand <=9) then -- Spawn Gargoyle player:messageSpecial(TRAP_ACTIVATED); SpawnMob(16814083,120):updateEnmity(player); -- Gargoyle else player:messageSpecial(TRAP_FAILS); npc:openDoor(30); end else player:messageSpecial(DOOR_LOCKED); end elseif(X <= 338)then player:startEvent(0x001A); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) if(csid == 0x001A and option == 1) then player:setPos(260,-0.25,-20,254,111); end end;
gpl-3.0
aa65535/luci
modules/luci-base/luasrc/http/protocol.lua
16
16196
-- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. -- This class contains several functions useful for http message- and content -- decoding and to retrive form data from raw http messages. module("luci.http.protocol", package.seeall) local ltn12 = require("luci.ltn12") HTTP_MAX_CONTENT = 1024*8 -- 8 kB maximum content size -- the "+" sign to " " - and return the decoded string. function urldecode( str, no_plus ) local function __chrdec( hex ) return string.char( tonumber( hex, 16 ) ) end if type(str) == "string" then if not no_plus then str = str:gsub( "+", " " ) end str = str:gsub( "%%([a-fA-F0-9][a-fA-F0-9])", __chrdec ) end return str end -- from given url or string. Returns a table with urldecoded values. -- Simple parameters are stored as string values associated with the parameter -- name within the table. Parameters with multiple values are stored as array -- containing the corresponding values. function urldecode_params( url, tbl ) local params = tbl or { } if url:find("?") then url = url:gsub( "^.+%?([^?]+)", "%1" ) end for pair in url:gmatch( "[^&;]+" ) do -- find key and value local key = urldecode( pair:match("^([^=]+)") ) local val = urldecode( pair:match("^[^=]+=(.+)$") ) -- store if type(key) == "string" and key:len() > 0 then if type(val) ~= "string" then val = "" end if not params[key] then params[key] = val elseif type(params[key]) ~= "table" then params[key] = { params[key], val } else table.insert( params[key], val ) end end end return params end function urlencode( str ) local function __chrenc( chr ) return string.format( "%%%02x", string.byte( chr ) ) end if type(str) == "string" then str = str:gsub( "([^a-zA-Z0-9$_%-%.%~])", __chrenc ) end return str end -- separated by "&". Tables are encoded as parameters with multiple values by -- repeating the parameter name with each value. function urlencode_params( tbl ) local enc = "" for k, v in pairs(tbl) do if type(v) == "table" then for i, v2 in ipairs(v) do enc = enc .. ( #enc > 0 and "&" or "" ) .. urlencode(k) .. "=" .. urlencode(v2) end else enc = enc .. ( #enc > 0 and "&" or "" ) .. urlencode(k) .. "=" .. urlencode(v) end end return enc end -- (Internal function) -- Initialize given parameter and coerce string into table when the parameter -- already exists. local function __initval( tbl, key ) if tbl[key] == nil then tbl[key] = "" elseif type(tbl[key]) == "string" then tbl[key] = { tbl[key], "" } else table.insert( tbl[key], "" ) end end -- (Internal function) -- Initialize given file parameter. local function __initfileval( tbl, key, filename, fd ) if tbl[key] == nil then tbl[key] = { file=filename, fd=fd, name=key, "" } else table.insert( tbl[key], "" ) end end -- (Internal function) -- Append given data to given parameter, either by extending the string value -- or by appending it to the last string in the parameter's value table. local function __appendval( tbl, key, chunk ) if type(tbl[key]) == "table" then tbl[key][#tbl[key]] = tbl[key][#tbl[key]] .. chunk else tbl[key] = tbl[key] .. chunk end end -- (Internal function) -- Finish the value of given parameter, either by transforming the string value -- or - in the case of multi value parameters - the last element in the -- associated values table. local function __finishval( tbl, key, handler ) if handler then if type(tbl[key]) == "table" then tbl[key][#tbl[key]] = handler( tbl[key][#tbl[key]] ) else tbl[key] = handler( tbl[key] ) end end end -- Table of our process states local process_states = { } -- Extract "magic", the first line of a http message. -- Extracts the message type ("get", "post" or "response"), the requested uri -- or the status code if the line descripes a http response. process_states['magic'] = function( msg, chunk, err ) if chunk ~= nil then -- ignore empty lines before request if #chunk == 0 then return true, nil end -- Is it a request? local method, uri, http_ver = chunk:match("^([A-Z]+) ([^ ]+) HTTP/([01]%.[019])$") -- Yup, it is if method then msg.type = "request" msg.request_method = method:lower() msg.request_uri = uri msg.http_version = tonumber( http_ver ) msg.headers = { } -- We're done, next state is header parsing return true, function( chunk ) return process_states['headers']( msg, chunk ) end -- Is it a response? else local http_ver, code, message = chunk:match("^HTTP/([01]%.[019]) ([0-9]+) ([^\r\n]+)$") -- Is a response if code then msg.type = "response" msg.status_code = code msg.status_message = message msg.http_version = tonumber( http_ver ) msg.headers = { } -- We're done, next state is header parsing return true, function( chunk ) return process_states['headers']( msg, chunk ) end end end end -- Can't handle it return nil, "Invalid HTTP message magic" end -- Extract headers from given string. process_states['headers'] = function( msg, chunk ) if chunk ~= nil then -- Look for a valid header format local hdr, val = chunk:match( "^([A-Za-z][A-Za-z0-9%-_]+): +(.+)$" ) if type(hdr) == "string" and hdr:len() > 0 and type(val) == "string" and val:len() > 0 then msg.headers[hdr] = val -- Valid header line, proceed return true, nil elseif #chunk == 0 then -- Empty line, we won't accept data anymore return false, nil else -- Junk data return nil, "Invalid HTTP header received" end else return nil, "Unexpected EOF" end end -- data line by line with the trailing \r\n stripped of. function header_source( sock ) return ltn12.source.simplify( function() local chunk, err, part = sock:receive("*l") -- Line too long if chunk == nil then if err ~= "timeout" then return nil, part and "Line exceeds maximum allowed length" or "Unexpected EOF" else return nil, err end -- Line ok elseif chunk ~= nil then -- Strip trailing CR chunk = chunk:gsub("\r$","") return chunk, nil end end ) end -- Content-Type. Stores all extracted data associated with its parameter name -- in the params table withing the given message object. Multiple parameter -- values are stored as tables, ordinary ones as strings. -- If an optional file callback function is given then it is feeded with the -- file contents chunk by chunk and only the extracted file name is stored -- within the params table. The callback function will be called subsequently -- with three arguments: -- o Table containing decoded (name, file) and raw (headers) mime header data -- o String value containing a chunk of the file data -- o Boolean which indicates wheather the current chunk is the last one (eof) function mimedecode_message_body( src, msg, filecb ) if msg and msg.env.CONTENT_TYPE then msg.mime_boundary = msg.env.CONTENT_TYPE:match("^multipart/form%-data; boundary=(.+)$") end if not msg.mime_boundary then return nil, "Invalid Content-Type found" end local tlen = 0 local inhdr = false local field = nil local store = nil local lchunk = nil local function parse_headers( chunk, field ) local stat repeat chunk, stat = chunk:gsub( "^([A-Z][A-Za-z0-9%-_]+): +([^\r\n]+)\r\n", function(k,v) field.headers[k] = v return "" end ) until stat == 0 chunk, stat = chunk:gsub("^\r\n","") -- End of headers if stat > 0 then if field.headers["Content-Disposition"] then if field.headers["Content-Disposition"]:match("^form%-data; ") then field.name = field.headers["Content-Disposition"]:match('name="(.-)"') field.file = field.headers["Content-Disposition"]:match('filename="(.+)"$') end end if not field.headers["Content-Type"] then field.headers["Content-Type"] = "text/plain" end if field.name and field.file and filecb then __initval( msg.params, field.name ) __appendval( msg.params, field.name, field.file ) store = filecb elseif field.name and field.file then local nxf = require "nixio" local fd = nxf.mkstemp(field.name) __initfileval ( msg.params, field.name, field.file, fd ) if fd then store = function(hdr, buf, eof) fd:write(buf) if (eof) then fd:seek(0, "set") end end else store = function( hdr, buf, eof ) __appendval( msg.params, field.name, buf ) end end elseif field.name then __initval( msg.params, field.name ) store = function( hdr, buf, eof ) __appendval( msg.params, field.name, buf ) end else store = nil end return chunk, true end return chunk, false end local function snk( chunk ) tlen = tlen + ( chunk and #chunk or 0 ) if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then return nil, "Message body size exceeds Content-Length" end if chunk and not lchunk then lchunk = "\r\n" .. chunk elseif lchunk then local data = lchunk .. ( chunk or "" ) local spos, epos, found repeat spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "\r\n", 1, true ) if not spos then spos, epos = data:find( "\r\n--" .. msg.mime_boundary .. "--\r\n", 1, true ) end if spos then local predata = data:sub( 1, spos - 1 ) if inhdr then predata, eof = parse_headers( predata, field ) if not eof then return nil, "Invalid MIME section header" elseif not field.name then return nil, "Invalid Content-Disposition header" end end if store then store( field, predata, true ) end field = { headers = { } } found = found or true data, eof = parse_headers( data:sub( epos + 1, #data ), field ) inhdr = not eof end until not spos if found then -- We found at least some boundary. Save -- the unparsed remaining data for the -- next chunk. lchunk, data = data, nil else -- There was a complete chunk without a boundary. Parse it as headers or -- append it as data, depending on our current state. if inhdr then lchunk, eof = parse_headers( data, field ) inhdr = not eof else -- We're inside data, so append the data. Note that we only append -- lchunk, not all of data, since there is a chance that chunk -- contains half a boundary. Assuming that each chunk is at least the -- boundary in size, this should prevent problems store( field, lchunk, false ) lchunk, chunk = chunk, nil end end end return true end return ltn12.pump.all( src, snk ) end -- Content-Type. Stores all extracted data associated with its parameter name -- in the params table withing the given message object. Multiple parameter -- values are stored as tables, ordinary ones as strings. function urldecode_message_body( src, msg ) local tlen = 0 local lchunk = nil local function snk( chunk ) tlen = tlen + ( chunk and #chunk or 0 ) if msg.env.CONTENT_LENGTH and tlen > tonumber(msg.env.CONTENT_LENGTH) + 2 then return nil, "Message body size exceeds Content-Length" elseif tlen > HTTP_MAX_CONTENT then return nil, "Message body size exceeds maximum allowed length" end if not lchunk and chunk then lchunk = chunk elseif lchunk then local data = lchunk .. ( chunk or "&" ) local spos, epos repeat spos, epos = data:find("^.-[;&]") if spos then local pair = data:sub( spos, epos - 1 ) local key = pair:match("^(.-)=") local val = pair:match("=([^%s]*)%s*$") if key and #key > 0 then __initval( msg.params, key ) __appendval( msg.params, key, val ) __finishval( msg.params, key, urldecode ) end data = data:sub( epos + 1, #data ) end until not spos lchunk = data end return true end return ltn12.pump.all( src, snk ) end -- version, message headers and resulting CGI environment variables from the -- given ltn12 source. function parse_message_header( src ) local ok = true local msg = { } local sink = ltn12.sink.simplify( function( chunk ) return process_states['magic']( msg, chunk ) end ) -- Pump input data... while ok do -- get data ok, err = ltn12.pump.step( src, sink ) -- error if not ok and err then return nil, err -- eof elseif not ok then -- Process get parameters if ( msg.request_method == "get" or msg.request_method == "post" ) and msg.request_uri:match("?") then msg.params = urldecode_params( msg.request_uri ) else msg.params = { } end -- Populate common environment variables msg.env = { CONTENT_LENGTH = msg.headers['Content-Length']; CONTENT_TYPE = msg.headers['Content-Type'] or msg.headers['Content-type']; REQUEST_METHOD = msg.request_method:upper(); REQUEST_URI = msg.request_uri; SCRIPT_NAME = msg.request_uri:gsub("?.+$",""); SCRIPT_FILENAME = ""; -- XXX implement me SERVER_PROTOCOL = "HTTP/" .. string.format("%.1f", msg.http_version); QUERY_STRING = msg.request_uri:match("?") and msg.request_uri:gsub("^.+?","") or "" } -- Populate HTTP_* environment variables for i, hdr in ipairs( { 'Accept', 'Accept-Charset', 'Accept-Encoding', 'Accept-Language', 'Connection', 'Cookie', 'Host', 'Referer', 'User-Agent', } ) do local var = 'HTTP_' .. hdr:upper():gsub("%-","_") local val = msg.headers[hdr] msg.env[var] = val end end end return msg end -- This function will examine the Content-Type within the given message object -- to select the appropriate content decoder. -- Currently the application/x-www-urlencoded and application/form-data -- mime types are supported. If the encountered content encoding can't be -- handled then the whole message body will be stored unaltered as "content" -- property within the given message object. function parse_message_body( src, msg, filecb ) -- Is it multipart/mime ? if msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and msg.env.CONTENT_TYPE:match("^multipart/form%-data") then return mimedecode_message_body( src, msg, filecb ) -- Is it application/x-www-form-urlencoded ? elseif msg.env.REQUEST_METHOD == "POST" and msg.env.CONTENT_TYPE and msg.env.CONTENT_TYPE:match("^application/x%-www%-form%-urlencoded") then return urldecode_message_body( src, msg, filecb ) -- Unhandled encoding -- If a file callback is given then feed it chunk by chunk, else -- store whole buffer in message.content else local sink -- If we have a file callback then feed it if type(filecb) == "function" then local meta = { name = "raw", encoding = msg.env.CONTENT_TYPE } sink = function( chunk ) if chunk then return filecb(meta, chunk, false) else return filecb(meta, nil, true) end end -- ... else append to .content else msg.content = "" msg.content_length = 0 sink = function( chunk ) if chunk then if ( msg.content_length + #chunk ) <= HTTP_MAX_CONTENT then msg.content = msg.content .. chunk msg.content_length = msg.content_length + #chunk return true else return nil, "POST data exceeds maximum allowed length" end end return true end end -- Pump data... while true do local ok, err = ltn12.pump.step( src, sink ) if not ok and err then return nil, err elseif not ok then -- eof return true end end return true end end statusmsg = { [200] = "OK", [206] = "Partial Content", [301] = "Moved Permanently", [302] = "Found", [304] = "Not Modified", [400] = "Bad Request", [403] = "Forbidden", [404] = "Not Found", [405] = "Method Not Allowed", [408] = "Request Time-out", [411] = "Length Required", [412] = "Precondition Failed", [416] = "Requested range not satisfiable", [500] = "Internal Server Error", [503] = "Server Unavailable", }
apache-2.0
Kthulupwns/darkstar
scripts/globals/items/acorn_cookie.lua
35
1338
----------------------------------------- -- ID: 4510 -- Item: Acorn Cookie -- Food Effect: 3Min, All Races ----------------------------------------- -- Magic Regen While Healing 3 -- Aquan Killer 5 -- 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,180,4510); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 3); target:addMod(MOD_AQUAN_KILLER, 5); target:addMod(MOD_SLEEPRES, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 3); target:delMod(MOD_AQUAN_KILLER, 5); target:delMod(MOD_SLEEPRES, 5); end;
gpl-3.0
dpino/snabb
src/lib/ipsec/esp.lua
3
18586
-- Implementation of IPsec ESP using AES-128-GCM with a 12 byte ICV and -- “Extended Sequence Number” (see RFC 4303 and RFC 4106). Provides -- address-family independent encapsulation/decapsulation routines for -- “tunnel mode” and “transport mode” routines for IPv6. -- -- Notes: -- -- * Wrapping around of the Extended Sequence Number is *not* detected because -- it is assumed to be an unrealistic scenario as it would take 584 years to -- overflow the counter when transmitting 10^9 packets per second. -- -- * decapsulate_transport6: Rejection of IP fragments is *not* implemented -- because `lib.protocol.ipv6' does not support fragmentation. E.g. -- fragments will be rejected because they can not be parsed as IPv6 -- packets. If however `lib.protocol.ipv6' were to be updated to be able to -- parse IP fragments this implementation would have to be updated as well -- to remain correct. See the “Reassembly” section of RFC 4303 for details: -- https://tools.ietf.org/html/rfc4303#section-3.4.1 -- module(..., package.seeall) local header = require("lib.protocol.header") local datagram = require("lib.protocol.datagram") local ethernet = require("lib.protocol.ethernet") local ipv6 = require("lib.protocol.ipv6") local esp = require("lib.protocol.esp") local esp_tail = require("lib.protocol.esp_tail") local aes_128_gcm = require("lib.ipsec.aes_128_gcm") local seq_no_t = require("lib.ipsec.seq_no_t") local lib = require("core.lib") local ffi = require("ffi") local C = ffi.C local logger = lib.logger_new({ rate = 32, module = 'esp' }) require("lib.ipsec.track_seq_no_h") local window_t = ffi.typeof("uint8_t[?]") PROTOCOL = 50 -- https://tools.ietf.org/html/rfc4303#section-2 local ETHERNET_SIZE = ethernet:sizeof() local IPV6_SIZE = ipv6:sizeof() local ESP_SIZE = esp:sizeof() local ESP_TAIL_SIZE = esp_tail:sizeof() local TRANSPORT6_PAYLOAD_OFFSET = ETHERNET_SIZE + IPV6_SIZE local function padding (a, l) return (a - l%a) % a end function esp_new (conf) assert(conf.mode == "aes-gcm-128-12", "Only supports 'aes-gcm-128-12'.") assert(conf.spi, "Need SPI.") local o = { cipher = aes_128_gcm:new(conf.spi, conf.key, conf.salt), spi = conf.spi, seq = ffi.new(seq_no_t), pad_to = 4, -- minimal padding esp = esp:new({}), esp_tail = esp_tail:new({}), ip = ipv6:new({}) -- for transport mode } o.ESP_CTEXT_OVERHEAD = o.cipher.IV_SIZE + ESP_TAIL_SIZE o.ESP_OVERHEAD = ESP_SIZE + o.ESP_CTEXT_OVERHEAD + o.cipher.AUTH_SIZE return o end encrypt = {} function encrypt:new (conf) return setmetatable(esp_new(conf), {__index=encrypt}) end -- Increment sequence number. function encrypt:next_seq_no () self.seq.no = self.seq.no + 1 end function encrypt:padding (length) -- See https://tools.ietf.org/html/rfc4303#section-2.4 return padding(self.pad_to, length + self.ESP_CTEXT_OVERHEAD) end function encrypt:encode_esp_trailer (ptr, next_header, pad_length) self.esp_tail:new_from_mem(ptr, ESP_TAIL_SIZE) self.esp_tail:next_header(next_header) self.esp_tail:pad_length(pad_length) end function encrypt:encrypt_payload (ptr, length) self:next_seq_no() local seq, low, high = self.seq, self.seq:low(), self.seq:high() self.cipher:encrypt(ptr, seq, low, high, ptr, length, ptr + length) end function encrypt:encode_esp_header (ptr) self.esp:new_from_mem(ptr, ESP_SIZE) self.esp:spi(self.spi) self.esp:seq_no(self.seq:low()) ffi.copy(ptr + ESP_SIZE, self.seq, self.cipher.IV_SIZE) end -- Encapsulation in transport mode is performed as follows: -- 1. Grow p to fit ESP overhead -- 2. Append ESP trailer to p -- 3. Encrypt payload+trailer in place -- 4. Move resulting ciphertext to make room for ESP header -- 5. Write ESP header function encrypt:encapsulate_transport6 (p) if p.length < TRANSPORT6_PAYLOAD_OFFSET then return nil end local payload = p.data + TRANSPORT6_PAYLOAD_OFFSET local payload_length = p.length - TRANSPORT6_PAYLOAD_OFFSET local pad_length = self:padding(payload_length) local overhead = self.ESP_OVERHEAD + pad_length p = packet.resize(p, p.length + overhead) self.ip:new_from_mem(p.data + ETHERNET_SIZE, IPV6_SIZE) local tail = payload + payload_length + pad_length self:encode_esp_trailer(tail, self.ip:next_header(), pad_length) local ctext_length = payload_length + pad_length + ESP_TAIL_SIZE self:encrypt_payload(payload, ctext_length) local ctext = payload + ESP_SIZE + self.cipher.IV_SIZE C.memmove(ctext, payload, ctext_length + self.cipher.AUTH_SIZE) self:encode_esp_header(payload) self.ip:next_header(PROTOCOL) self.ip:payload_length(payload_length + overhead) return p end -- Encapsulation in tunnel mode is performed as follows: -- (In tunnel mode, the input packet must be an IP frame already stripped of -- its Ethernet header.) -- 1. Grow and shift p to fit ESP overhead -- 2. Append ESP trailer to p -- 3. Encrypt payload+trailer in place -- 4. Write ESP header -- (The resulting packet contains the raw ESP frame, without IP or Ethernet -- headers.) function encrypt:encapsulate_tunnel (p, next_header) local pad_length = self:padding(p.length) local trailer_overhead = pad_length + ESP_TAIL_SIZE + self.cipher.AUTH_SIZE local orig_length = p.length p = packet.resize(p, orig_length + trailer_overhead) local tail = p.data + orig_length + pad_length self:encode_esp_trailer(tail, next_header, pad_length) local ctext_length = orig_length + pad_length + ESP_TAIL_SIZE self:encrypt_payload(p.data, ctext_length) local len = p.length p = packet.shiftright(p, ESP_SIZE + self.cipher.IV_SIZE) self:encode_esp_header(p.data) return p end decrypt = {} function decrypt:new (conf) local o = esp_new(conf) o.MIN_SIZE = o.ESP_OVERHEAD + padding(o.pad_to, o.ESP_OVERHEAD) o.CTEXT_OFFSET = ESP_SIZE + o.cipher.IV_SIZE o.PLAIN_OVERHEAD = ESP_SIZE + o.cipher.IV_SIZE + o.cipher.AUTH_SIZE local window_size = conf.window_size or 128 o.window_size = window_size + padding(8, window_size) o.window = ffi.new(window_t, o.window_size / 8) o.resync_threshold = conf.resync_threshold or 1024 o.resync_attempts = conf.resync_attempts or 8 o.decap_fail = 0 o.auditing = conf.auditing return setmetatable(o, {__index=decrypt}) end function decrypt:decrypt_payload (ptr, length) -- NB: bounds check is performed by caller local esp = self.esp:new_from_mem(ptr, esp:sizeof()) local iv_start = ptr + ESP_SIZE local ctext_start = ptr + self.CTEXT_OFFSET local ctext_length = length - self.PLAIN_OVERHEAD local seq_low = esp:seq_no() local seq_high = tonumber( C.check_seq_no(seq_low, self.seq.no, self.window, self.window_size) ) local error = nil if seq_high < 0 or not self.cipher:decrypt( ctext_start, seq_low, seq_high, iv_start, ctext_start, ctext_length ) then if seq_high < 0 then error = "replayed" else error = "integrity error" end self.decap_fail = self.decap_fail + 1 if self.decap_fail > self.resync_threshold then seq_high = self:resync(ptr, length, seq_low, seq_high) if seq_high then error = nil end end end if error then self:audit(error) return nil end self.decap_fail = 0 self.seq.no = C.track_seq_no( seq_high, seq_low, self.seq.no, self.window, self.window_size ) local esp_tail_start = ctext_start + ctext_length - ESP_TAIL_SIZE self.esp_tail:new_from_mem(esp_tail_start, ESP_TAIL_SIZE) local ptext_length = ctext_length - self.esp_tail:pad_length() - ESP_TAIL_SIZE return ctext_start, ptext_length end -- Decapsulation in transport mode is performed as follows: -- 1. Parse IP and ESP headers and check Sequence Number -- 2. Decrypt ciphertext in place -- 3. Parse ESP trailer and update IP header -- 4. Move cleartext up to IP payload -- 5. Shrink p by ESP overhead function decrypt:decapsulate_transport6 (p) if p.length - TRANSPORT6_PAYLOAD_OFFSET < self.MIN_SIZE then return nil end self.ip:new_from_mem(p.data + ETHERNET_SIZE, IPV6_SIZE) local payload = p.data + TRANSPORT6_PAYLOAD_OFFSET local payload_length = p.length - TRANSPORT6_PAYLOAD_OFFSET local ptext_start, ptext_length = self:decrypt_payload(payload, payload_length) if not ptext_start then return nil end self.ip:next_header(self.esp_tail:next_header()) self.ip:payload_length(ptext_length) C.memmove(payload, ptext_start, ptext_length) p = packet.resize(p, TRANSPORT6_PAYLOAD_OFFSET + ptext_length) return p end -- Decapsulation in tunnel mode is performed as follows: -- (In tunnel mode, the input packet must be already stripped of its outer -- Ethernet and IP headers.) -- 1. Parse ESP header and check Sequence Number -- 2. Decrypt ciphertext in place -- 3. Parse ESP trailer and shrink p by overhead -- (The resulting packet contains the raw ESP payload (i.e. an IP frame), -- without an Ethernet header.) function decrypt:decapsulate_tunnel (p) if p.length < self.MIN_SIZE then return nil end local ptext_start, ptext_length = self:decrypt_payload(p.data, p.length) if not ptext_start then return nil end p = packet.shiftleft(p, self.CTEXT_OFFSET) p = packet.resize(p, ptext_length) return p, self.esp_tail:next_header() end function decrypt:audit (reason) if not self.auditing then return end -- This is the information RFC4303 says we SHOULD log logger:log("Rejecting packet (" .. "SPI=" .. self.spi .. ", " .. "src_addr='" .. self.ip:ntop(self.ip:src()) .. "', " .. "dst_addr='" .. self.ip:ntop(self.ip:dst()) .. "', " .. "seq_low=" .. self.esp:seq_no() .. ", " .. "flow_id=" .. self.ip:flow_label() .. ", " .. "reason='" .. reason .. "'" .. ")") end function decrypt:resync (ptr, length, seq_low, seq_high) local iv_start = ptr + ESP_SIZE local ctext_start = ptr + self.CTEXT_OFFSET local ctext_length = length - self.PLAIN_OVERHEAD if seq_high < 0 then -- The sequence number looked replayed, we use the last seq_high we have -- seen seq_high = self.seq:high() else -- We failed to decrypt in-place, undo the damage to recover the original -- ctext (ignore bogus auth data) self.cipher:encrypt( ctext_start, iv_start, seq_low, seq_high, ctext_start, ctext_length ) end local p_orig = packet.from_pointer(ptr, length) for i = 1, self.resync_attempts do seq_high = seq_high + 1 if self.cipher:decrypt( ctext_start, seq_low, seq_high, iv_start, ctext_start, ctext_length ) then packet.free(p_orig) return seq_high else ffi.copy(ptr, p_orig.data, length) end end end function selftest () local conf = { spi = 0x0, mode = "aes-gcm-128-12", key = "00112233445566778899AABBCCDDEEFF", salt = "00112233", resync_threshold = 16, resync_attempts = 8} local enc, dec = encrypt:new(conf), decrypt:new(conf) local payload = packet.from_string( [[abcdefghijklmnopqrstuvwxyz ABCDEFGHIJKLMNOPQRSTUVWXYZ 0123456789]] ) local d = datagram:new(payload) local ip = ipv6:new({}) ip:payload_length(payload.length) d:push(ip) d:push(ethernet:new({type=0x86dd})) local p = d:packet() -- Check integrity print("original", lib.hexdump(ffi.string(p.data, p.length))) local p_enc = assert(enc:encapsulate_transport6(packet.clone(p)), "encapsulation failed") print("encrypted", lib.hexdump(ffi.string(p_enc.data, p_enc.length))) local p2 = assert(dec:decapsulate_transport6(packet.clone(p_enc)), "decapsulation failed") print("decrypted", lib.hexdump(ffi.string(p2.data, p2.length))) assert(p2.length == p.length and C.memcmp(p.data, p2.data, p.length) == 0, "integrity check failed") -- ... for tunnel mode local p_enc = assert(enc:encapsulate_tunnel(packet.clone(p), 42), "encapsulation failed") print("enc. (tun)", lib.hexdump(ffi.string(p_enc.data, p_enc.length))) local p2, nh = dec:decapsulate_tunnel(packet.clone(p_enc)) assert(p2 and nh == 42, "decapsulation failed") print("dec. (tun)", lib.hexdump(ffi.string(p2.data, p2.length))) assert(p2.length == p.length and C.memcmp(p.data, p2.data, p.length) == 0, "integrity check failed") -- Check invalid packets. assert(not enc:encapsulate_transport6(packet.from_string("invalid")), "encapsulated invalid packet") assert(not dec:decapsulate_transport6(packet.from_string("invalid")), "decapsulated invalid packet") -- ... for tunnel mode assert(not dec:decapsulate_tunnel(packet.from_string("invalid")), "decapsulated invalid packet") -- Check minimum packet. local p_min = packet.from_string("012345678901234567890123456789012345678901234567890123") p_min.data[18] = 0 -- Set IPv6 payload length to zero p_min.data[19] = 0 -- ... assert(p_min.length == TRANSPORT6_PAYLOAD_OFFSET) print("original", lib.hexdump(ffi.string(p_min.data, p_min.length))) local e_min = assert(enc:encapsulate_transport6(packet.clone(p_min))) print("encrypted", lib.hexdump(ffi.string(e_min.data, e_min.length))) assert(e_min.length == dec.MIN_SIZE+TRANSPORT6_PAYLOAD_OFFSET) e_min = assert(dec:decapsulate_transport6(e_min), "decapsulation of minimum packet failed") print("decrypted", lib.hexdump(ffi.string(e_min.data, e_min.length))) assert(e_min.length == TRANSPORT6_PAYLOAD_OFFSET) assert(p_min.length == e_min.length and C.memcmp(p_min.data, e_min.data, p_min.length) == 0, "integrity check failed") -- ... for tunnel mode print("original", "(empty)") local e_min = assert(enc:encapsulate_tunnel(packet.allocate(), 0)) print("enc. (tun)", lib.hexdump(ffi.string(e_min.data, e_min.length))) e_min = assert(dec:decapsulate_tunnel(e_min)) assert(e_min.length == 0) -- Tunnel/transport mode independent tests for _, op in ipairs( {{encap=function (p) return enc:encapsulate_transport6(p) end, decap=function (p) return dec:decapsulate_transport6(p) end}, {encap=function (p) return enc:encapsulate_tunnel(p, 0) end, decap=function (p) return dec:decapsulate_tunnel(p) end}} ) do -- Check transmitted Sequence Number wrap around C.memset(dec.window, 0, dec.window_size / 8) -- clear window enc.seq.no = 2^32 - 1 -- so next encapsulated will be seq 2^32 dec.seq.no = 2^32 - 1 -- pretend to have seen 2^32-1 local px = op.encap(packet.clone(p)) assert(op.decap(px), "Transmitted Sequence Number wrap around failed.") assert(dec.seq:high() == 1 and dec.seq:low() == 0, "Lost Sequence Number synchronization.") -- Check Sequence Number exceeding window C.memset(dec.window, 0, dec.window_size / 8) -- clear window enc.seq.no = 2^32 dec.seq.no = 2^32 + dec.window_size + 1 local px = op.encap(packet.clone(p)) assert(not op.decap(px), "Accepted out of window Sequence Number.") assert(dec.seq:high() == 1 and dec.seq:low() == dec.window_size+1, "Corrupted Sequence Number.") -- Test anti-replay: From a set of 15 packets, first send all those -- that have an even sequence number. Then, send all 15. Verify that -- in the 2nd run, packets with even sequence numbers are rejected while -- the others are not. -- Then do the same thing again, but with offset sequence numbers so that -- we have a 32bit wraparound in the middle. local offset = 0 -- close to 2^32 in the 2nd iteration for offset = 0, 2^32-7, 2^32-7 do -- duh C.memset(dec.window, 0, dec.window_size / 8) -- clear window dec.seq.no = offset for i = 1+offset, 15+offset do if (i % 2 == 0) then enc.seq.no = i-1 -- so next seq will be i local px = op.encap(packet.clone(p)) assert(op.decap(px), "rejected legitimate packet seq=" .. i) assert(dec.seq.no == i, "Lost sequence number synchronization") end end for i = 1+offset, 15+offset do enc.seq.no = i-1 local px = op.encap(packet.clone(p)) if (i % 2 == 0) then assert(not op.decap(px), "accepted replayed packet seq=" .. i) else assert(op.decap(px), "rejected legitimate packet seq=" .. i) end end end -- Check that packets from way in the past/way in the future (further -- than the biggest allowable window size) are rejected This is where we -- ultimately want resynchronization (wrt. future packets) C.memset(dec.window, 0, dec.window_size / 8) -- clear window dec.seq.no = 2^34 + 42 enc.seq.no = 2^36 + 24 local px = op.encap(packet.clone(p)) assert(not op.decap(px), "accepted packet from way into the future") enc.seq.no = 2^32 + 42 local px = op.encap(packet.clone(p)) assert(not op.decap(px), "accepted packet from way into the past") -- Test resynchronization after having lost >2^32 packets enc.seq.no = 0 dec.seq.no = 0 C.memset(dec.window, 0, dec.window_size / 8) -- clear window local px = op.encap(packet.clone(p)) -- do an initial packet assert(op.decap(px), "decapsulation failed") enc.seq:high(3) -- pretend there has been massive packet loss enc.seq:low(24) for i = 1, dec.resync_threshold do local px = op.encap(packet.clone(p)) assert(not op.decap(px), "decapsulated pre-resync packet") end local px = op.encap(packet.clone(p)) assert(op.decap(px), "failed to resynchronize") -- Make sure we don't accidentally resynchronize with very old replayed -- traffic enc.seq.no = 42 for i = 1, dec.resync_threshold do local px = op.encap(packet.clone(p)) assert(not op.decap(px), "decapsulated very old packet") end local px = op.encap(packet.clone(p)) assert(not op.decap(px), "resynchronized with the past!") end end
apache-2.0
beni55/lua-resty-http
lib/resty/http_headers.lua
69
1716
local rawget, rawset, setmetatable = rawget, rawset, setmetatable local str_gsub = string.gsub local str_lower = string.lower local _M = { _VERSION = '0.01', } -- Returns an empty headers table with internalised case normalisation. -- Supports the same cases as in ngx_lua: -- -- headers.content_length -- headers["content-length"] -- headers["Content-Length"] function _M.new(self) local mt = { normalised = {}, } mt.__index = function(t, k) local k_hyphened = str_gsub(k, "_", "-") local matched = rawget(t, k) if matched then return matched else local k_normalised = str_lower(k_hyphened) return rawget(t, mt.normalised[k_normalised]) end end -- First check the normalised table. If there's no match (first time) add an entry for -- our current case in the normalised table. This is to preserve the human (prettier) case -- instead of outputting lowercased header names. -- -- If there's a match, we're being updated, just with a different case for the key. We use -- the normalised table to give us the original key, and perorm a rawset(). mt.__newindex = function(t, k, v) -- we support underscore syntax, so always hyphenate. local k_hyphened = str_gsub(k, "_", "-") -- lowercase hyphenated is "normalised" local k_normalised = str_lower(k_hyphened) if not mt.normalised[k_normalised] then mt.normalised[k_normalised] = k_hyphened rawset(t, k_hyphened, v) else rawset(t, mt.normalised[k_normalised], v) end end return setmetatable({}, mt) end return _M
bsd-2-clause
kayru/tundra
scripts/tundra/syntax/native.lua
9
10662
-- native.lua -- support for programs, static libraries and such module(..., package.seeall) local util = require "tundra.util" local nodegen = require "tundra.nodegen" local path = require "tundra.path" local depgraph = require "tundra.depgraph" local _native_mt = nodegen.create_eval_subclass { DeclToEnvMappings = { Libs = "LIBS", Defines = "CPPDEFS", Includes = "CPPPATH", Frameworks = "FRAMEWORKS", LibPaths = "LIBPATH", }, } local _object_mt = nodegen.create_eval_subclass({ Suffix = "$(OBJECTSUFFIX)", Prefix = "", Action = "$(OBJCOM)", Label = "Object $(<)", OverwriteOutputs = true, }, _native_mt) local _program_mt = nodegen.create_eval_subclass({ Suffix = "$(PROGSUFFIX)", Prefix = "$(PROGPREFIX)", Action = "$(PROGCOM)", Label = "Program $(@)", PreciousOutputs = true, OverwriteOutputs = true, Expensive = true, }, _native_mt) local _staticlib_mt = nodegen.create_eval_subclass({ Suffix = "$(LIBSUFFIX)", Prefix = "$(LIBPREFIX)", Action = "$(LIBCOM)", Label = "StaticLibrary $(@)", -- Play it safe and delete the output files of this node before re-running it. -- Solves iterative issues with e.g. AR OverwriteOutputs = false, IsStaticLib = true, }, _native_mt) local _objgroup_mt = nodegen.create_eval_subclass({ Label = "ObjGroup $(<)", }, _native_mt) local _shlib_mt = nodegen.create_eval_subclass({ Suffix = "$(SHLIBSUFFIX)", Prefix = "$(SHLIBPREFIX)", Action = "$(SHLIBCOM)", Label = "SharedLibrary $(@)", PreciousOutputs = true, OverwriteOutputs = true, Expensive = true, }, _native_mt) local _extlib_mt = nodegen.create_eval_subclass({ Suffix = "", Prefix = "", Label = "", }, _native_mt) local cpp_exts = util.make_lookup_table { ".cpp", ".cc", ".cxx", ".C" } local _is_native_mt = util.make_lookup_table { _object_mt, _program_mt, _staticlib_mt, _shlib_mt, _extlib_mt, _objgroup_mt } -- sources can be a mix of raw strings like {"file1.cpp", "file2.cpp"} -- or files with filters like {{"file1.cpp", "file2.cpp"; Config = "..."}} local function is_file_in_sources(sources, fn) for k,v in pairs(sources) do if type(v) == 'table' then return util.array_contains(v, fn) elseif v == fn then return true end end return false end function _native_mt:customize_env(env, raw_data) if env:get('GENERATE_PDB', '0') ~= '0' then -- Figure out the final linked PDB (the one next to the dll or exe) if raw_data.Target then local target = env:interpolate(raw_data.Target) local link_pdb = path.drop_suffix(target) .. '.pdb' env:set('_PDB_LINK_FILE', link_pdb) else env:set('_PDB_LINK_FILE', "$(OBJECTDIR)/" .. raw_data.Name .. ".pdb") end -- Keep the compiler's idea of the PDB file separate env:set('_PDB_CC_FILE', "$(OBJECTDIR)/" .. raw_data.Name .. "_ccpdb.pdb") env:set('_USE_PDB_CC', '$(_USE_PDB_CC_OPT)') env:set('_USE_PDB_LINK', '$(_USE_PDB_LINK_OPT)') end local pch = raw_data.PrecompiledHeader if pch and env:get('_PCH_SUPPORTED', '0') ~= '0' then assert(pch.Header) if not nodegen.resolve_pass(pch.Pass) then croak("%s: PrecompiledHeader requires a valid Pass", raw_data.Name) end local pch_dir = "$(OBJECTDIR)/__" .. raw_data.Name env:set('_PCH_HEADER', pch.Header) env:set('_PCH_FILE', pch_dir .. '/' .. pch.Header .. '$(_PCH_SUFFIX)') env:set('_PCH_INCLUDE_PATH', path.join(pch_dir, pch.Header)) env:set('_USE_PCH', '$(_USE_PCH_OPT)') env:set('_PCH_SOURCE', path.normalize(pch.Source)) env:set('_PCH_PASS', pch.Pass) if cpp_exts[path.get_extension(pch.Source)] then env:set('PCHCOMPILE', '$(PCHCOMPILE_CXX)') else env:set('PCHCOMPILE', '$(PCHCOMPILE_CC)') end local pch_source = path.remove_prefix(raw_data.SourceDir or '', pch.Source) if not is_file_in_sources(raw_data.Sources, pch_source) then raw_data.Sources[#raw_data.Sources + 1] = pch_source end end if env:has_key('MODDEF') then env:set('_USE_MODDEF', '$(_USE_MODDEF_OPT)') end end function _native_mt:create_dag(env, data, input_deps) local build_id = env:get("BUILD_ID") local my_pass = data.Pass local sources = data.Sources local libsuffix = { env:get("LIBSUFFIX") } local shlibsuffix = { env:get("SHLIBLINKSUFFIX") } local my_extra_deps = {} -- Link with libraries in dependencies. for _, dep in util.nil_ipairs(data.Depends) do if dep.Keyword == "SharedLibrary" then -- On Win32 toolsets, we need foo.lib -- On UNIX toolsets, we need -lfoo -- -- We only want to add this if the node actually produced any output (i.e -- it's not completely filtered out.) local node = dep:get_dag(env:get_parent()) if #node.outputs > 0 then my_extra_deps[#my_extra_deps + 1] = node local target = dep.Decl.Target or dep.Decl.Name target = env:interpolate(target) local dir, fn = path.split(target) local libpfx = env:interpolate("$(LIBPREFIX)") if fn:sub(1, libpfx:len()) == libpfx then fn = fn:sub(libpfx:len()+1) end local link_lib = path.drop_suffix(fn) .. '$(SHLIBLINKSUFFIX)' env:append('LIBS', link_lib) if dir:len() > 0 then env:append('LIBPATH', dir) end end elseif dep.Keyword == "StaticLibrary" then local node = dep:get_dag(env:get_parent()) my_extra_deps[#my_extra_deps + 1] = node if not self.IsStaticLib then node:insert_output_files(sources, libsuffix) end elseif dep.Keyword == "ObjGroup" then -- We want all .obj files local objsuffix = { env:get("OBJECTSUFFIX") } -- And also .res files, if we know what that is if env:has_key("W32RESSUFFIX") then objsuffix[#objsuffix + 1] = env:get("W32RESSUFFIX") end local node = dep:get_dag(env:get_parent()) my_extra_deps[#my_extra_deps + 1] = node if not sources then sources = {} end for _, dep in util.nil_ipairs(node.deps) do my_extra_deps[#my_extra_deps + 1] = dep dep:insert_output_files(sources, objsuffix) end else --[[ A note about win32 import libraries: It is tempting to add an implicit input dependency on the import library of the linked-to shared library here; but this would be suboptimal: 1. Because there is a dependency between the nodes themselves, the import library generation will always run before this link step is run. Therefore, the import lib will always exist and be updated before this link step runs. 2. Because the import library is regenerated whenever the DLL is relinked we would have to custom-sign it (using a hash of the DLLs export list) to avoid relinking the executable all the time when only the DLL's internals change. 3. The DLL's export list should be available in headers anyway, which is already covered in the compilation of the object files that actually uses those APIs. Therefore the best way right now is to not tell Tundra about the import lib at all and rely on header scanning to pick up API changes. An implicit input dependency would be needed however if someone is doing funky things with their import library (adding non-linker-generated code for example). These cases are so rare that we can safely put them off. ]]-- end end -- Make sure sources are not specified more than once. This can happen when -- there are recursive dependencies on object groups. if data.Sources and #data.Sources > 0 then data.Sources = util.uniq(data.Sources) end local aux_outputs = env:get_list("AUX_FILES_" .. self.Keyword:upper(), {}) if env:get('GENERATE_PDB', '0') ~= '0' then aux_outputs[#aux_outputs + 1] = "$(_PDB_LINK_FILE)" aux_outputs[#aux_outputs + 1] = "$(_PDB_CC_FILE)" end local extra_inputs = {} if env:has_key('MODDEF') then extra_inputs[#extra_inputs + 1] = "$(MODDEF)" end local targets = nil if self.Action then targets = { nodegen.get_target(data, self.Suffix, self.Prefix) } end local deps = util.merge_arrays(input_deps, my_extra_deps) local dag = depgraph.make_node { Env = env, Label = self.Label, Pass = data.Pass, Action = self.Action, PreAction = data.PreAction, InputFiles = data.Sources, InputFilesUntracked = data.UntrackedSources, OutputFiles = targets, AuxOutputFiles = aux_outputs, ImplicitInputs = extra_inputs, Dependencies = deps, OverwriteOutputs = self.OverwriteOutputs, PreciousOutputs = self.PreciousOutputs, Expensive = self.Expensive, } -- Remember this dag node for IDE file generation purposes data.__DagNode = dag return dag end local native_blueprint = { Name = { Required = true, Help = "Set output (base) filename", Type = "string", }, Sources = { Required = true, Help = "List of source files", Type = "source_list", ExtensionKey = "NATIVE_SUFFIXES", }, UntrackedSources = { Help = "List of input files that are not tracked", Type = "source_list", ExtensionKey = "NATIVE_SUFFIXES", }, Target = { Help = "Override target location", Type = "string", }, PreAction = { Help = "Optional action to run before main action.", Type = "string", }, PrecompiledHeader = { Help = "Enable precompiled header (if supported)", Type = "table", }, IdeGenerationHints = { Help = "Data to support control IDE file generation", Type = "table", }, } local external_blueprint = { Name = { Required = true, Help = "Set name of the external library", Type = "string", }, } local external_counter = 1 function _extlib_mt:create_dag(env, data, input_deps) local name = string.format("dummy node for %s (%d)", data.Name, external_counter) external_counter = external_counter + 1 return depgraph.make_node { Env = env, Label = name, Pass = data.Pass, Dependencies = input_deps, } end nodegen.add_evaluator("Object", _object_mt, native_blueprint) nodegen.add_evaluator("Program", _program_mt, native_blueprint) nodegen.add_evaluator("StaticLibrary", _staticlib_mt, native_blueprint) nodegen.add_evaluator("SharedLibrary", _shlib_mt, native_blueprint) nodegen.add_evaluator("ExternalLibrary", _extlib_mt, external_blueprint) nodegen.add_evaluator("ObjGroup", _objgroup_mt, native_blueprint)
gpl-3.0
moteus/lua-odbc-pool
examples/fusionpbx/odbc_pool.lua
1
1666
require "resources.functions.config" require "resources.functions.file_exists" local log = require "resources.functions.log".dbpool local odbc = require "odbc" local odbcpool = require "odbc.pool" -- Configuration local POLL_TIMEOUT = 5 local run_file = scripts_dir .. "/run/dbpool.tmp"; -- Pool ctor local function run_odbc_pool(name, n) local connection_string = assert(database[name]) local typ, dsn, user, password = connection_string:match("^(.-)://(.-):(.-):(.-)$") assert(typ == 'odbc', "unsupported connection string:" .. connection_string) local cli = odbcpool.client(name) log.noticef("Starting reconnect thread[%s] ...", name) local rthread = odbcpool.reconnect_thread(cli, dsn, user, password) rthread:start() log.noticef("Reconnect thread[%s] started", name) local env = odbc.environment() local connections = {} for i = 1, (n or 10) do local cnn = odbc.assert(env:connection()) connections[#connections+1] = cnn cli:reconnect(cnn) end return { name = name; cli = cli; cnn = connections; thr = rthread; } end local function stop_odbc_pool(ctx) log.noticef("Stopping reconnect thread[%s] ...", ctx.name) ctx.thr:stop() log.noticef("Reconnect thread[%s] stopped", ctx.name) end local function main() local system_pool = run_odbc_pool("system", 10) local switch_pool = run_odbc_pool("switch", 10) local file = assert(io.open(run_file, "w")); file:write("remove this file to stop the script"); file:close() while file_exists(run_file) do freeswitch.msleep(POLL_TIMEOUT*1000) end stop_odbc_pool(system_pool) stop_odbc_pool(switch_pool) end main()
mit
ASHRAF97/ASHRAFKASPERV3
plugins/iq_abs.lua
2
15268
-- made by { @Mouamle } do ws = {} rs = {} -- some examples of how to use this :3 ws[1] = "هلاو" rs[1] = "هـﮩـڵآوآت 🦀❤" ws[2] = "هلو" -- msg rs[2] = "هـﮩـڵآوآت 🦀❤️" -- reply ws[3] = "شلونكم" -- msg rs[3] = "تـمـآم وأنتـہ 🌝💙" -- reply ws[4] = "دووم" -- msg rs[4] = "يدوم نبضك 🌝💙" -- reply ws[5] = "شونك" rs[5] = "تـمـآم وأنتـہ 🌝💙" ws[6] = "شلونك" rs[6] = "تـمـآم وأنتـہ 🌝💙" ws[7] = "غنيلي" rs[7] = " 🙈 احبك اني 🙊 اني احبك 🙉 واتحدى واحد بلبشر مثلي يحبك 🙊" ws[8] = "شغل المبردة" rs[8] = " تم تشغيل المبردة بنجاح ❄️" ws[9] = "طفي المبردة" rs[9] = "طفيتهه 😒🍃" ws[10] = "شغل السبلت" rs[10] = "شغلته 🌚🍃 بس حثلجون معليه ترا " ws[11] = "مايا خليفه" rs[11] = " 😂 عيب صايمين" ws[12] = "فطور" rs[12] = "واخيراً 😍😍 خل اروح افطر " ws[13] = "جاسم" rs[13] = "خير 🌚🍃" ws[14] = "اه" rs[14] = "ادخله 🍆" ws[15] = "تخليني" rs[15] = "لـمن يصـير عـندڪ عود اخليګ 😹🌝" ws[16] = "زاحف" rs[16] = "🌝😹 هاي عود انته جبير" ws[17] = "تركيا" rs[17] = "😐🍃 فديتهه" ws[18] = "داعش" rs[18] = "دي خل يولون 😒💙" ws[19] = "الدولة الاسلامية" rs[19] = "انته داعشي ؟؟ 😒💔" ws[20] = "سني" rs[20] = "لتصير طائفي 😐💙" ws[21] = "شيعي" rs[21] = "لتصير طائفي 😐💙" ws[22] = "تبادل" rs[22] = "كافي ملينه 😒 ما اريد اتبادل" ws[23] = "العراقيين" rs[23] = "احلى ناس ولله 😻🙈" ws[24] = "من وين" rs[24] = "شعليك زاحف 😹🌶" ws[25] = "هاي" rs[25] = "هـٱيـآت🙈🍷" ws[26] = "البوت" rs[26] = "معاجبك؟😕😒🍃" ws[27] = "البوت واكف" rs[27] = "لتجذب🙄💙" ws[28] = "منو ديحذف رسائلي" rs[28] = "مـحـد 🏌" ws[29] = "كلاش اوف كلانس" rs[29] = "تلعبهه ؟ شكد لفلك ؟" ws[30] = "جوني" rs[30] = "😹مأذيك ؟" ws[31] = "ازحف " rs[31] = "عـلـﻰ ٱخـتـڪ ٱزحـف 🐉" ws[32] = "اكطع" rs[32] = " سِـلُـطِـُه مٌـنَ بّْعـدِ 😅الُبّـ🤖ـوَتْ🎄 " ws[33] = "بوت" rs[33] = "ها نعم ..{✮ خٍّـٌٍّـٍَْيْـٌٍّرَُ ✮}.. ✭ شتريد مني خلوني انام شوي ✾ ٱڵـڵـه واكبر عليكم اربعه وعشرين ساعه كاعد احمي بكروبكم شوي خلوني ارتاح تكسبون اجر 😭 بَـßÊـسّ كلولي شلون احمي كروبكم اذا زباله ازعل واطلع واذا عاجبكم خلوني انام 😢😂" ws[34] = "اريد بوت" rs[34] = " تريد بوت بكروبك وسيرفر مدفوع 24 ساعه راسل المطور ويضيفني بكروبك @IQ_ABS ❥" ws[35] = "اريد اكبل" rs[35] = "زُاحُـفَ مٌـوَ بّـيَـدِكِ 😒😂" ws[37] = "عبوسي" rs[37] = "ٲلمطور ماڵتي فديتهہ 😻💙 @IQ_ABS" ws[38] = "نجب" rs[38] = "بّـحُـلُـكِكِ😑👊" ws[39] = "المنصور" rs[39] = " احلى ناس ولله " ws[40] = "المدرسه" rs[40] = "😒🍃الله لا يراوينه" ws[41] = "تحبني" rs[41] = "اعـشقـڪ😻" ws[42] = "يعني شكد" rs[42] = "فوك متتوقع" ws[43] = "😂" rs[43] = " دوم حبي ❤️" ws[44] = "هههه" rs[44] = "❀دِْوم حبيْ❀" ws[45] = "ههههه" rs[45] = "️❀دِْوم حبيْ❀" ws[46] = "😹" rs[46] = "❀دِْوم حبيْ❀" ws[47] = "🌚" rs[47] = "مـنـور صخـام الـجـدر 🌚😹" ws[48] = "😍" rs[48] = "آإمـ﴿😚﴾ـحہ" ws[49] = "مح" rs[49] = "عہ🍯🙊سہل" ws[50] = "انمي" rs[50] = "اته اوتاكو ؟ ❤️" ws[51] = "منحرف" rs[51] = "وينه حطردة 🌚☝️🏻" ws[52] = "😭" rs[52] = "ڵـتبجـي 😿" ws[53] = "😢" rs[53] = "ڵـتبجـي 😿" ws[54] = "شكد عمرك" rs[54] = "زاحـﮩـف 😹" ws[55] = "شكد عمرج" rs[55] = "زاحـﮩـف 😹" ws[56] = "اقرالي دعاء" rs[56] = " اللهم عذب المدرسين 😢 منهم الاحياء والاموات 😭🔥 اللهم عذب ام الانكليزي 😭💔 وكهربها بلتيار الرئيسي 😇 اللهم عذب ام الرياضيات وحولها الى غساله بطانيات 🙊 اللهم عذب ام الاسلاميه واجعلها بائعة الشاميه 😭🍃 اللهم عذب ام العربي وحولها الى بائعه البلبي اللهم عذب ام الجغرافيه واجعلها كلدجاجه الحافية اللهم عذب ام التاريخ وزحلقها بقشره من البطيخ وارسلها الى المريخ اللهم عذب ام الاحياء واجعلها كل مومياء اللهم عذب المعاون اقتله بلمدرسه بهاون 😂😂😂" ws[57] = "غبي" rs[57] = " انـت ٱڵٱغبۍ" ws[58] = "دي" rs[58] = "دي تنـڪاڵ لـبوك 🌝🖕" ws[59] = "منو حبيبك" rs[59] = "ٲخـتڪ 🙈" ws[60] = "تكرهني" rs[60] = "ٲمـوت منڪ 😖" ws[61] = "اكرهك" rs[61] = "عـلسـاس ٲنـﮩـي ٲحـبڪ هه😒😂" ws[62] = "😂" rs[62] = "❀دِْوم حبيْ❀" ws[63] = "الاعضميه" rs[63] = " احسن ناس وربي❤️" ws[64] = "الكرادة" rs[64] = " احسن ناس وربي❤️" ws[65] = "شارع فلسطين" rs[65] = " احسن ناس وربي❤️" ws[66] = "ببكن ملف" rs[66] = " دﮩہہ⇣﴿🐎﴾⇣ہہﮩيہ❥ تحلم 🐞" ws[67] = "😇" rs[67] = "شـﮩﮩـدتـﮩـحس 🐛" ws[68] = "😐" rs[68] = "شِـبـيک صـﮩـٲفـﮩـن 😒👋🏻" ws[69] = "انجب" rs[69] = "بـحـلكڪ😒💦" ws[70] = "حارة" rs[70] = "ايَيَ ڪوَلڵشِ⚶ " ws[71] = "خالتك" rs[71] = " راح اطـﮩـردڪ ڵـﮩۦـڪ 😒🐞" ws[72] = "اطرد البوت" rs[72] = " راح ابقة احترمك❤️" ws[73] = "هه" rs[73] = " شـﮩـدتـحـﮩـس 🕊" ws[74] = "شدتحس" rs[74] = " نـﮩـفـﮩـس شـعـﮩـورك 🍁🐎" ws[75] = "اكولك" rs[75] = " ڪـﮩﮩۛﮩـوڵ مـاكـوڵ لٱحـﮩـد 🐿" ws[76] = "اكلك" rs[76] = " ڪـﮩﮩۛﮩـوڵ مـاكـوڵ لٱحـﮩـد 🐿" ws[78] = "بغداد" rs[78] = " 😍 فديتهه" ws[79] = "البصرة" rs[79] = " احسن ناس وربي❤️" ws[80] = "تركماني" rs[80] = " والنعم منك❤️" ws[81] = "@IQ_ABS" rs[81] = "ٲلمطور ماڵتي فديتهہ 😻💙 @IQ_ABS" ws[83] = "باي" rs[83] = " ✾ ٱڵـڵـه ✾ ٱڵـڵـه ✾ ٱڵـڵـه وياك 🕊" ws[84] = "تنح" rs[84] = "عـيـب ٲبـنـي 😒🍃" ws[85] = "جوعان" rs[85] = "تـﮩـعال اڪـﮩـلنـي 😐😂" ws[86] = "عطشان" rs[86] = "روح ٲشـﮩـرب مــيي" ws[87] = "صايم" rs[87] = "شًـﮩـسـويـلـك 😐🍃" ws[88] = "☹️" rs[88] = "لـﮩـضـوج פـٍـٍبيبي 😢❤️🍃" ws[89] = "😔" rs[89] = " لـﮩـيـﺵ ضـٲيـﮩـج 😿🍃" ws[90] = "فرخ" rs[90] = " عيبب 😱😱" ws[92] = "كسمك" rs[92] = " عيب 😱😱😱" ws[93] = "نعال" rs[93] = " بـﮩـوجـهـڪ 😐😂" ws[94] = "حروح اسبح" rs[94] = " واخيراً 😹🌝" ws[95] = "حروح اغسل" rs[95] = " واخيراً 😹🌝" ws[96] = "حروح اطب للحمام" rs[96] = " واخيراً 😹🌝" ws[97] = "حبيبتي" rs[97] = " منو هاي 😱 تخوني 😔☹" ws[98] = "كبلت" rs[98] = " بلخير 😂💔" ws[99] = "البوت عاوي" rs[99] = " اطردك ؟ 😒" ws[100] = "منور" rs[100] = " بـﮩـنورك حـﮩـبـﮩـي 😍🍷" ws[101] = "حفلش" rs[101] = " افلش راسك" ws[102] = "كردي" rs[102] = "والنعم منك ❤️" ws[103] = "طفي السبلت" rs[103] = " تم اطفاء السبلت بنجاح 🌚🍃" ws[104] = "🌝" rs[104] = "مــﮩﮩﮩــننوورر 🌝💙" ws[105] = "اذن المغرب" rs[105] = "ٲسـﮩـتـحـﮩـرم 🌚🍃" ws[106] = "حلو" rs[106] = "ٱنـﮩـت الاحـلآ 🌚❤️️" ws[107] = "احبك" rs[107] = " اني اكثر 😍🍃" ws[108] = "😑" rs[108] = " شبيك 🍃☹" ws[109] = "😒" rs[109] = "شِـبـيک کآڵـب وجـهہهـڪ 😐" ws[110] = "منو تحب" rs[110] = "خـﮩـالـتڪ ٱلـشـڪـرﮪ 😹🏃🏻" ws[111] = "اباجر العيد" rs[111] = "كل عام وانت بالف خير حبي 😇❤️" ws[112] = "فديت" rs[112] = "ها زاحف كمشتك" ws[113] = "مضغوط" rs[113] = "دي انضغظ منك ؟ 😂😂" ws[114] = "فديت" rs[114] = "ها زاحف كمشتك" ws[115] = "فديتك" rs[115] = "ها زاحف كمشتك" ws[116] = "فديتج" rs[116] = "ها زاحف كمشتك" ws[117] = "شوف خاصك" rs[117] = "شدازله 😱😨" ws[118] = "تعال خاص" rs[118] = "شحسوون 😱" ws[119] = "تعالي خاص" rs[119] = "شحسوون 😱" ws[120] = "دخل السبام" rs[120] = "شحسوون 😱" ws[121] = "😎" rs[121] = "يلا عود انته فد نعال 😐🍃" ws[122] = "😱" rs[122] = "خير خوفتني 😨" ws[123] = "كحبه" rs[123] = "عيب 😱" ws[124] = "بيش ساعة" rs[124] = "ما اعرف 🌚🍃" ws[125] = "🚶🏻" rs[125] = "لُـﮩـضڵ تتـمشـﮥ اڪعـد ﺳـﯠڵـف 🤖👋🏻" ws[126] = "منو اكثر واحد تحبه" rs[126] = "خالتك" ws[127] = "ليش" rs[127] = "تاكل خرة الجيش 😂😂" ws[128] = "طاسه" rs[128] = "امك حلوة ورقاصه 💃🏻" ws[129] = "عشرين" rs[129] = "تاكل جدر خنين 😫" ws[130] = "ميه" rs[130] = "😂تشرب مميه" ws[131] = "اربعة" rs[131] = "😂لحيه ابوك مربعه" ws[132] = "فارة" rs[132] = "😂دفترك كله صفارة" ws[133] = "ميتين" rs[133] = "😂فوك راسك قندرتين" ws[134] = "مات" rs[134] = "ابو الحمامات 🐦" ws[135] = "توفه" rs[135] = "ابو اللفه 🌯" ws[136] = "احترك" rs[136] = "🍾البو العرك" ws[137] = "غرك" rs[137] = "ابو العرك 🍾" ws[138] = "طار" rs[138] = "ابن الطيار" ws[139] = "ديسحك" rs[139] = "😂😂 هاي بعده" ws[140] = "لتسحك" rs[140] = "😐😂 وك" ws[141] = "اندرويد" rs[141] = "افشل نظام بلعالم 🌝🍷" ws[142] = "ios" rs[142] = "احسن نظام بلعالم🌚❤️" ws[143] = "ايفون" rs[143] = "فديتك اته والايفون 🌚🔥" ws[144] = "كلكسي" rs[144] = "فاشل اخرة نوع تلفون🔥☹" ws[145] = "سامسونك" rs[145] = "فاشل اخرة نوع تلفون🔥☹" ws[146] = "لتزحف" rs[146] = "وك اسف 🙁😔" ws[147] = "حاته" rs[147] = "زاحف 😂 منو هاي دزلي صورتهه" ws[148] = "حات" rs[148] = "زاحفه 😂 منو هذا دزيلي صورته" ws[149] = "صاكه" rs[149] = "زاحف 😂 منو هاي دزلي صورتهه" ws[150] = "صاك" rs[150] = "زاحفه 😂 منو هذا دزيلي صورهه" ws[151] = "منو اني" rs[151] = "انته احلى شي بحياتي ❤️🍃" ws[152] = "ابن الكلب" rs[152] = "عيب ابني 🔥☹" ws[153] = "انجب انته" rs[153] = "وك وك 😭😔" ws[154] = "حطردك" rs[154] = "اعصابك 😨 لتتهور" ws[155] = "المطور" rs[155] = "شتريد من المطور 😐🍃" ws[156] = "منو اكثر واحد تكرهه" rs[156] = "انته" ws[157] = "شباب" rs[157] = "هًّْـــُ﴿⍨﴾ـٍِٰـــہاا حـﮩـب 🚶🏻🌝" ws[158] = "اته زلمه" rs[158] = "تعال لزمه 😐😂" ws[159] = "الاحد" rs[159] = "هذا اليوم نحس بلنسبه الي" ws[160] = "الاثنين" rs[160] = "يوم اجة بي ناس عزيزين وفقدت بي ناس هم ☹" ws[161] = "هلاوو" rs[161] = "هـﮩـڵآوآت 🦀❤️" ws[162] = "اختك" rs[162] = "شبيهه 😱" ws[163] = "كواد" rs[163] = "عيب 😨😨" ws[164] = "😌" rs[164] = "ٱڵـمـطـڵـوب ¿ ❥" ws[165] = "هلا" rs[165] = "✾ هـﮩـڵا ہبـﮩـک 💙🖐🏻" ws[166] = "مرحبا" rs[166] = "✾ مٌـﮩۚـرحـﮩۘـبـتـيـن 💙🖐🏻" ws[167] = "سلام" rs[167] = "✾ ٲلـﮩـسـلا۾م ؏ـﮩـڵـيڪم 💙🖐🏻" ws[168] = "السلام" rs[168] = "✾ ٲلـﮩـسـلا۾م ؏ـﮩـڵـيڪم 💙🖐🏻" ws[169] = "السلام عليكم" rs[169] = "✾ وَْ؏ـﮩـڵـيڪم ٲلـﮩـسـلا۾م 💙🖐🏻" ws[170] = "تسلم" rs[170] = "✾ ٱڵـڵـه يسـلـمـڪ 💙🖐🏻" ws[171] = "ممكن" rs[171] = "ﺗْـ•ـﮩ؏ْﮩـ•ــ🚶ـاْلْ اويـلـي 😋👙" ws[172] = "ماسكو" rs[172] = "ٲلمطور ماڵتي فديتهہ 😻💙 @IQ_ABS" ws[173] = "القناة" rs[173] = "قناة ديف بروكس خاصة بالتطوير وبرمجة البوتات وغبرها معرف القناة @DEV_PROX" ws[174] = "ديف بروكس" rs[174] = "احسن سورس في التليكرام ☻☂ القناة @DEV_PROX" -- the main function function run( msg, matches ) -- just a local variables that i used in my algorithm local i = 0; local w = false -- the main part that get the message that the user send and check if it equals to one of the words in the ws table :) -- this section loops through all the words table and assign { k } to the word index and { v } to the word itself for k,v in pairs(ws) do -- change the message text to uppercase and the { v } value that toke form the { ws } table and than compare it in a specific pattern if ( string.find(string.upper(msg.text), "^" .. string.upper(v) .. "$") ) then -- assign the { i } to the index of the reply and the { w } to true ( we will use it later ) i = k; w = true; end end -- check if { w } is not false and { i } not equals to 0 if ( (w ~= false) and (i ~= 0) ) then -- get the receiver :3 R = get_receiver(msg) -- send him the proper message from the index that { i } assigned to --send_large_msg ( R , rs[i] ); --send_reply(msg.id, rs[i]) reply_msg(msg.id, rs[i], ok_cb, false ) end -- don't edit this section if ( msg.text == "about" ) then if ( msg.from.username == "Mouamle" ) then R = get_receiver(msg) send_large_msg ( R , "Made by @Mouamle" ); end end end return { patterns = { "(.*)" }, run = run } end
gpl-2.0
Kthulupwns/darkstar
scripts/zones/Northern_San_dOria/npcs/Rondipur.lua
38
1049
----------------------------------- -- Area: Northern San d'Oria -- NPC: Rondipur -- Type: Quest Giver -- @zone: 231 -- @pos -154.415 10.999 153.744 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02d1); 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
Kthulupwns/darkstar
scripts/zones/Apollyon/mobs/Proto-Omega.lua
12
3065
----------------------------------- -- Area: Apollyon Centrale -- NPC: Proto-Omega ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); require("scripts/globals/titles"); require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) --print("Proto-omega_engaged"); mob:setMod(MOD_SLASHRES,300); mob:setMod(MOD_PIERCERES,300); mob:setMod(MOD_IMPACTRES,300); mob:setMod(MOD_HTHRES,300); for n =1,table.getn (resistMod),1 do mob:setMod(resistMod[n],-50); end for n =1,table.getn (defenseMod),1 do mob:setMod(defenseMod[n],-50); end end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) local mobID = mob:getID(); local lifepourcent= ((mob:getHP()/mob:getMaxHP())*100); if(lifepourcent > 70 or lifepourcent <30)then mob:AnimationSub(1); elseif(lifepourcent > 30 and lifepourcent < 70)then mob:AnimationSub(2); end if(lifepourcent > 30 and lifepourcent < 70 and mob:getLocalVar("form") == 8)then -- bipede mob:setMod(MOD_SLASHRES,1400); mob:setMod(MOD_PIERCERES,1400); mob:setMod(MOD_IMPACTRES,1400); mob:setMod(MOD_HTHRES,1400); for n =1,table.getn (resistMod),1 do mob:setMod(resistMod[n],100); end for n =1,table.getn (defenseMod),1 do mob:setMod(defenseMod[n],100); end SpawnMob(16933125):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());-- spawn gunpod mob:setLocalVar("form", 9) -- print("bipede"); elseif(lifepourcent < 30 and mob:getLocalVar("form") == 9 )then -- quadripede mob:setMod(MOD_SLASHRES,1450); mob:setMod(MOD_PIERCERES,1450); mob:setMod(MOD_IMPACTRES,1450); mob:setMod(MOD_HTHRES,1450); for n =1,table.getn (resistMod),1 do mob:setMod(resistMod[n],-50); end for n =1,table.getn (defenseMod),1 do mob:setMod(defenseMod[n],-50); end mob:addStatusEffect(EFFECT_REGAIN,7,3,0); -- The final form has Regain, SpawnMob(16933125):setMobMod(MOBMOD_SUPERLINK, mob:getShortID());-- spawn gunpod mob:setLocalVar("form", 8); end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) killer:addTitle(APOLLYON_RAVAGER); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); GetNPCByID(16932864+39):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+39):setStatus(STATUS_NORMAL); end;
gpl-3.0
amenophis1er/prosody-modules
mod_broadcast/mod_broadcast.lua
32
1043
local is_admin = require "core.usermanager".is_admin; local allowed_senders = module:get_option_set("broadcast_senders", {}); local from_address = module:get_option_string("broadcast_from"); local jid_bare = require "util.jid".bare; function send_to_online(message) local c = 0; for hostname, host_session in pairs(hosts) do if host_session.sessions then for username in pairs(host_session.sessions) do c = c + 1; message.attr.to = username.."@"..hostname; module:send(message); end end end return c; end function send_message(event) local stanza = event.stanza; local from = stanza.attr.from; if is_admin(from) or allowed_senders:contains(jid_bare(from)) then if from_address then stanza = st.clone(stanza); stanza.attr.from = from_address; end local c = send_to_online(stanza); module:log("debug", "Broadcast stanza from %s to %d online users", from, c); return true; else module:log("warn", "Broadcasting is not allowed for %s", from); end end module:hook("message/bare", send_message);
mit
GabrielNicolasAvellaneda/luvit-upstream
tests/test-fs-write-sync.lua
14
1192
--[[ Copyright 2015 The Luvit Authors. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License") you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] require('tap')(function(test) local FS = require('fs') local Path = require('path') local Buffer = require('buffer').Buffer test('fs.writeSync', function() local fn = Path.join(module.dir, 'write.txt') local foo = 'foo' local fd = FS.openSync(fn, 'w') local written = FS.writeSync(fd, -1, '') assert(written == 0) FS.writeSync(fd, -1, foo) local bar = 'bár' -- TODO: Support buffer argument written = FS.writeSync(fd, -1, Buffer:new(bar):toString()) assert(written > 3) FS.closeSync(fd) assert(FS.readFileSync(fn) == 'foobár') end) end)
apache-2.0
Kthulupwns/darkstar
scripts/zones/Mhaura/npcs/Dieh_Yamilsiah.lua
38
2198
----------------------------------- -- Area: Mhaura -- NPC: Dieh Yamilsiah -- Reports the time remaining before boat arrival. -- @pos 7.057 -2.364 2.489 249 ----------------------------------- package.loaded["scripts/zones/Mhaura/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Mhaura/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- Each boat comes every 1152 seconds/8 game hours, 4 hour offset between Selbina and Aht Urghan -- Original timer: local timer = 1152 - ((os.time() - 1009810584)%1152); local timer = 1152 - ((os.time() - 1009810802)%1152); local destination = 0; -- Selbina, set to 1 for Al Zhabi local direction = 0; -- Arrive, 1 for depart local waiting = 216; -- Offset for Selbina -- Next ferry is Al Zhabi for higher values. if (timer >= 576) then destination = 1; timer = timer - 576; waiting = 193; end -- Logic to manipulate cutscene results. if (timer <= waiting) then direction = 1; -- Ship arrived, switch dialog from "arrive" to "depart" else timer = timer - waiting; -- Ship hasn't arrived, subtract waiting time to get time to arrival end player:startEvent(231,timer,direction,0,destination); -- timer arriving/departing ??? destination --[[Other cutscenes: 233 "This ship is headed for Selbina." 234 "The Selbina ferry will deparrrt soon! Passengers are to board the ship immediately!" Can't find a way to toggle the destination on 233 or 234, so they are not used. Users knowing which ferry is which > using all CSs.]] 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
dpino/snabb
src/lib/protocol/header.lua
9
11831
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. -- Protocol header base class -- -- This is an abstract class (should not be instantiated) -- -- Derived classes must implement the following class variables -- -- _name a string that describes the header type in a -- human readable form -- -- _ulp a table that holds information about the "upper -- layer protocols" supported by the header. It -- contains two keys -- method the name of the method of the header -- class whose result identifies the ULP -- and is used as key for the class_map -- table -- class_map a table whose keys must represent -- valid return values of the instance -- method given by the 'method' name -- above. The corresponding value must -- be the name of the header class that -- parses this particular ULP -- -- In the simplest case, a protocol header consists of a single data -- structure of a fixed size, e.g. an untagged Ethernet II header. -- Such headers are supported by this framework in a straight forward -- manner. More complex headers may have representations that differ -- in size and structure, depending on the use-case, e.g. GRE. -- Headers of that kind can be supported as long as all variants can -- be enumerated and represented by a separate fixed-sized data -- structure. This requirement is necessary because all data -- structures must be pre-allocated for performance reasons and to -- support the instance recycling mechanism of the class framework. -- Each header is described by a ctype object that serves as a -- template for the header. -- -- A protocol header can be created in two different manners. In the -- first case (provided by the new() constructor method), the protocol -- instance contains the header structure itself, where as in the -- second case (provided by the new_from_mem() constructor), the -- protocol instance contains a pointer to an arbitrary location in -- memory where the actual header resides (usually a packet buffer). -- The pointer is cast to the appropriate ctype to access the fields -- of the header. -- -- To support the second mode of creation for protocols with variable -- header structures, one of the headers must be designated as the -- "base header". It must be chosen such that it contains enough -- information to determine the actual header that is present in -- memory. -- -- The constructors in the header base class deal exclusively with the -- base header, i.e. the instances created by the new() and -- new_from_mem() methods only provide access to the fields present in -- the base header. Protocols that implement variable headers must -- extend the base methods to select the appropriate header variant. -- -- The header class uses the following data structures to support this -- mechanism. Each header variant is described by a table with the -- following elements -- -- t the ctype that represents the header itself -- ptr_t a ctype constructed by ffi.typeof("$*", ctype) used for -- casting of pointers -- box_t a ctype that represents a "box" to store a ptr_t, i.e. -- ffi.typeof("$[1]", ptr_t) -- -- These tables are stored as an array in the class variable _headers, -- where, by definition, the first element designates the base header. -- -- This array is initialized by the class method init(), which must be -- called by every derived class. -- -- When a new instance of a protocol class is created, it receives its -- own, private array of headers stored in the instance variable of -- the same name. The elements from the header tables stored in the -- class are inherited by the instance by means of setmetatable(). -- For each header, one instance of the header itself and one instance -- of a box are created from the t and box_t ctypes, respectively. -- These objects are stored in the keys "data" and "box" and are -- private to the instance. The following schematic should make the -- relationship clearer -- -- class._headers = { -- [1] = { t = ..., -- ptr_t = ..., -- box_t = ..., -- }, <---------------+ -- [2] = { t = ..., | -- ptr_t = ..., | -- box_t = ..., | -- }, <------------+ | -- ... | | -- } | | -- | | -- instance._headers = { | | -- [1] = { data = t(), | | -- box = box_t()| | -- }, ----------------+ metatable -- [2] = { data = t(), | -- box = box_t()| -- }, -------------+ metatable -- ... -- } -- -- The constructors of the base class store a reference to the base -- header (i.e. _headers[1]) in the instance variable _header. In -- other words, the box and data can be accessed by dereferencing -- _header.data and _header.box, respectively. -- -- This initialization is common to both constructors. The difference -- lies in the contents of the pointer stored in the box. The new() -- constructor stores a pointer to the data object, i.e. -- -- _header.box[0] = ffi.cast(_header.ptr_t, _header.data) -- -- where as the new_from_mem() constructor stores the pointer to the -- region of memory supplied as argument to the method call, i.e. -- -- _header.box[0] = ffi.cast(_header.ptr_t, mem) -- -- In that case, the _header.data object is not used at all. -- -- When a derived class overrides these constructors, it should first -- call the construcor of the super class, which will initialize the -- base header as described above. An extension of the new() method -- will replace the reference to the base header stored in _header by -- a reference to the header variant selected by the configuration -- passed as arguments to the method, i.e. it will eventually do -- -- _header = _headers[foo] -- -- where <foo> is the index of the selected header. -- -- An extension of the new_from_mem() constructor uses the base header -- to determine the actual header variant to use and override the base -- header with it. -- -- Refer to the lib.protocol.ethernet and lib.protocol.gre classes for -- examples. -- -- For convenience, the class variable class._header exists as well -- and contains a reference to the base header class._headers[1]. -- This promotes the instance methods sizeof() and ctype() to class -- methods, which will provide the size and ctype of a protocol's base -- header from the class itself. For example, the size of an ethernet -- header can be obtained by -- -- local ethernet = require("lib.protocol.ethernet") -- local ether_size = ethernet:sizeof() -- -- without creating an instance first. module(..., package.seeall) local ffi = require("ffi") local header = subClass(nil) -- Class methods -- Initialize a subclass with a set of headers, which must contain at -- least one element (the base header). function header:init (headers) assert(self and headers and #headers > 0) self._singleton_p = #headers == 1 local _headers = {} for i = 1, #headers do local header = {} local ctype = headers[i] header.t = ctype header.ptr_t = ffi.typeof("$*", ctype) header.box_t = ffi.typeof("$*[1]", ctype) header.meta = { __index = header } _headers[i] = header end self._headers = _headers self._header = _headers[1] end -- Initialize an instance of the class. If the instance is new (has -- not been recycled), an instance of each header struct and a box -- that holds a pointer to it are allocated. A reference to the base -- header is installed in the _header instance variable. local function _new (self) local o = header:superClass().new(self) if not o._recycled then -- Allocate boxes and headers for all variants of the -- classe's header structures o._headers = {} for i = 1, #self._headers do -- This code is only executed when a new instance is created -- via the class construcor, i.e. self is the class itself -- (as opposed to the case when an instance is recycled by -- calling the constructor as an instance method, in which -- case self would be the instance instead of the class). -- This is why it is safe to use self._headers[i].meta as -- metatable here. The effect is that the ctypes are -- inherited from the class while the data and box table are -- private to the instance. local _header = setmetatable({}, self._headers[i].meta) _header.data = _header.t() _header.box = _header.box_t() o._headers[i] = _header end end -- Make the base header the active header o._header = o._headers[1] return o end -- Initialize the base protocol header with 0 and store a pointer to -- it in the header box. function header:new () local o = _new(self) local header = o._header ffi.fill(header.data, ffi.sizeof(header.t)) header.box[0] = ffi.cast(header.ptr_t, header.data) return o end -- This alternative constructor creates a protocol header from a chunk -- of memory by "overlaying" a header structure. In this mode, the -- protocol ctype _header.data is unused and _header.box stores the -- pointer to the memory location supplied by the caller. function header:new_from_mem (mem, size) local o = _new(self) local header = o._header if ffi.sizeof(header.t) > size then o:free() return nil end header.box[0] = ffi.cast(header.ptr_t, mem) return o end -- Instance methods -- Return a reference to the header function header:header () return self._header.box[0][0] end -- Return a pointer to the header function header:header_ptr () return self._header.box[0] end -- Return the ctype of header function header:ctype () return self._header.t end -- Return the size of the header function header:sizeof () return ffi.sizeof(self._header.t) end -- Return true if <other> is of the same type and contains identical -- data, false otherwise. function header:eq (other) local ctype = self:ctype() local size = self:sizeof() local other_ctype = other:ctype() return (ctype == other_ctype and ffi.string(self:header_ptr(), size) == ffi.string(other:header_ptr(), size)) end -- Copy the header to some location in memory (usually a packet -- buffer). The caller must make sure that there is enough space at -- the destination. If relocate is a true value, the copy is promoted -- to be the active storage of the header. function header:copy (dst, relocate) ffi.copy(dst, self:header_ptr(), self:sizeof()) if relocate then self._header.box[0] = ffi.cast(self._header.ptr_t, dst) end end -- Create a new protocol instance that is a copy of this instance. -- This is horribly inefficient and should not be used in the fast -- path. function header:clone () local header = self:ctype()() local sizeof = ffi.sizeof(header) ffi.copy(header, self:header_ptr(), sizeof) return self:class():new_from_mem(header, sizeof) end -- Return the class that can handle the upper layer protocol or nil if -- the protocol is not supported or the protocol has no upper-layer. function header:upper_layer () local method = self._ulp.method if not method then return nil end local class = self._ulp.class_map[self[method](self)] if class then if package.loaded[class] then return package.loaded[class] else return require(class) end else return nil end end return header
apache-2.0
Kthulupwns/darkstar
scripts/globals/items/love_chocolate.lua
35
1149
----------------------------------------- -- ID: 5230 -- Item: love_chocolate -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic Regen 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,10800,5230); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPHEAL, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPHEAL, 4); end;
gpl-3.0
Kthulupwns/darkstar
scripts/zones/Bastok_Mines/npcs/Maymunah.lua
19
1152
----------------------------------- -- Area: Bastok Mines -- NPC: Maymunah -- Guild Merchant NPC: Alchemy Guild -- @pos 108.738 5.017 -3.129 234 ----------------------------------- package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:sendGuild(5262,8,23,6)) then player:showText(npc, MAYMUNAH_SHOP_DIALOG); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
Kthulupwns/darkstar
scripts/globals/weaponskills/herculean_slash.lua
12
1575
----------------------------------- -- Herculean Slash -- Great Sword weapon skill -- Skill Level: 290 -- Paralyzes target. Duration of effect varies with TP. -- Aligned with the Snow Gorget, Thunder Gorget & Breeze Gorget. -- Aligned with the Snow Belt, Thunder Belt & Breeze Belt. -- Element: Ice -- Modifiers: VIT:60% -- As this is a magic-based weaponskill it is also modified by Magic Attack Bonus. -- 100%TP 200%TP 300%TP -- 3.50 3.50 3.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 = 3.5; params.ftp200 = 3.5; params.ftp300 = 3.5; params.str_wsc = 0.0; params.dex_wsc = 0.0; params.vit_wsc = 0.6; params.agi_wsc = 0.0; params.int_wsc = 0.0; 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.vit_wsc = 0.8; end local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params); if damage > 0 then local tp = player:getTP(); local duration = (tp/100 * 60) if(target:hasStatusEffect(EFFECT_PARALYSIS) == false) then target:addStatusEffect(EFFECT_PARALYSIS, 30, 0, duration); end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Mleaf/mleaf_luci
applications/luci-olsr/luasrc/model/cbi/olsr/olsrdiface.lua
49
6797
--[[ 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 util = require "luci.util" local ip = require "luci.ip" function write_float(self, section, value) local n = tonumber(value) if n ~= nil then return Value.write(self, section, "%.1f" % n) end end m = Map("olsrd", translate("OLSR Daemon - Interface"), translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. ".. "As such it allows mesh routing for any network equipment. ".. "It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. ".. "Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation.")) m.redirect = luci.dispatcher.build_url("admin/services/olsrd") if not arg[1] or m.uci:get("olsrd", arg[1]) ~= "Interface" then luci.http.redirect(m.redirect) return end i = m:section(NamedSection, arg[1], "Interface", translate("Interface")) i.anonymous = true i.addremove = false i:tab("general", translate("General Settings")) i:tab("addrs", translate("IP Addresses")) i:tab("timing", translate("Timing and Validity")) ign = i:taboption("general", Flag, "ignore", translate("Enable"), translate("Enable this interface.")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = i:taboption("general", Value, "interface", translate("Network"), translate("The interface OLSRd should serve.")) network.template = "cbi/network_netlist" network.widget = "radio" network.nocreate = true mode = i:taboption("general", ListValue, "Mode", translate("Mode"), translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. ".. "valid Modes are \"mesh\" and \"ether\". Default is \"mesh\".")) mode:value("mesh") mode:value("ether") mode.optional = true mode.rmempty = true weight = i:taboption("general", Value, "Weight", translate("Weight"), translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. ".. "Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, ".. "but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />".. "<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. ".. "For any other value of LinkQualityLevel, the interface ETX value is used instead.")) weight.optional = true weight.datatype = "uinteger" weight.placeholder = "0" lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"), translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. ".. "It is only used when LQ-Level is greater than 0. Examples:<br />".. "reduce LQ to 192.168.0.1 by half: 192.168.0.1 0.5<br />".. "reduce LQ to all nodes on this interface by 20%: default 0.8")) lqmult.optional = true lqmult.rmempty = true lqmult.cast = "table" lqmult.placeholder = "default 1.0" function lqmult.validate(self, value) for _, v in pairs(value) do if v ~= "" then local val = util.split(v, " ") local host = val[1] local mult = val[2] if not host or not mult then return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.") end if not (host == "default" or ip.IPv4(host) or ip.IPv6(host)) then return nil, translate("Can only be a valid IPv4 or IPv6 address or 'default'") end if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.") end if not mult:match("[0-1]%.[0-9]+") then return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.") end end end return value end ip4b = i:taboption("addrs", Value, "Ip4Broadcast", translate("IPv4 broadcast"), translate("IPv4 broadcast address for outgoing OLSR packets. One useful example would be 255.255.255.255. ".. "Default is \"0.0.0.0\", which triggers the usage of the interface broadcast IP.")) ip4b.optional = true ip4b.datatype = "ip4addr" ip4b.placeholder = "0.0.0.0" ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"), translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast.")) ip6m.optional = true ip6m.datatype = "ip6addr" ip6m.placeholder = "FF02::6D" ip4s = i:taboption("addrs", Value, "IPv4Src", translate("IPv4 source"), translate("IPv4 src address for outgoing OLSR packages. Default is \"0.0.0.0\", which triggers usage of the interface IP.")) ip4s.optional = true ip4s.datatype = "ip4addr" ip4s.placeholder = "0.0.0.0" ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"), translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. ".. "Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP.")) ip6s.optional = true ip6s.datatype = "ip6addr" ip6s.placeholder = "0::/0" hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval")) hi.optional = true hi.datatype = "ufloat" hi.placeholder = "5.0" hi.write = write_float hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time")) hv.optional = true hv.datatype = "ufloat" hv.placeholder = "40.0" hv.write = write_float ti = i:taboption("timing", Value, "TcInterval", translate("TC interval")) ti.optional = true ti.datatype = "ufloat" ti.placeholder = "2.0" ti.write = write_float tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time")) tv.optional = true tv.datatype = "ufloat" tv.placeholder = "256.0" tv.write = write_float mi = i:taboption("timing", Value, "MidInterval", translate("MID interval")) mi.optional = true mi.datatype = "ufloat" mi.placeholder = "18.0" mi.write = write_float mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time")) mv.optional = true mv.datatype = "ufloat" mv.placeholder = "324.0" mv.write = write_float ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval")) ai.optional = true ai.datatype = "ufloat" ai.placeholder = "18.0" ai.write = write_float av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time")) av.optional = true av.datatype = "ufloat" av.placeholder = "108.0" av.write = write_float return m
apache-2.0
dpino/snabb
src/apps/wall/l7fw.lua
9
12868
module(..., package.seeall) -- This module implements a level 7 firewall app that consumes the result -- of DPI scanning done by l7spy. -- -- The firewall rules are a table mapping protocol names to either -- * a simple action ("drop", "reject", "accept") -- * a pfmatch expression local bit = require("bit") local ffi = require("ffi") local link = require("core.link") local packet = require("core.packet") local datagram = require("lib.protocol.datagram") local ether = require("lib.protocol.ethernet") local icmp = require("lib.protocol.icmp.header") local ipv4 = require("lib.protocol.ipv4") local ipv6 = require("lib.protocol.ipv6") local tcp = require("lib.protocol.tcp") local match = require("pf.match") ffi.cdef[[ void syslog(int priority, const char*format, ...); ]] -- constants from <syslog.h> for syslog priority argument local LOG_USER = 8 local LOG_INFO = 6 -- network constants local ETHER_PROTO_IPV4 = 0x0800 local ETHER_PROTO_IPV6 = 0x86dd local IP_PROTO_ICMPV4 = 1 local IP_PROTO_TCP = 6 local IP_PROTO_ICMPV6 = 58 L7Fw = {} L7Fw.__index = L7Fw -- create a new firewall app object given an instance of Scanner -- and firewall rules function L7Fw:new(config) local obj = { local_ipv4 = config.local_ipv4, local_ipv6 = config.local_ipv6, local_macaddr = config.local_macaddr, scanner = config.scanner, rules = config.rules, -- this map tracks flows to compiled pfmatch functions -- so that we only compile them once per flow handler_map = {}, -- log level for logging filtered packets logging = config.logging or "off", -- for stats accepted = 0, rejected = 0, dropped = 0, total = 0 } assert(obj.logging == "on" or obj.logging == "off", ("invalid log level: %s"):format(obj.logging)) return setmetatable(obj, self) end -- called by pfmatch handlers, just drop the packet on the floor function L7Fw:drop(pkt, len) if self.logging == "on" then self:log_packet("DROP") end packet.free(self.current_packet) self.dropped = self.dropped + 1 end -- called by pfmatch handler, handle rejection response function L7Fw:reject(pkt, len) link.transmit(self.output.reject, self:make_reject_response()) self.rejected = self.rejected + 1 if self.logging == "on" then self:log_packet("REJECT") end packet.free(self.current_packet) end -- called by pfmatch handler, forward packet function L7Fw:accept(pkt, len) link.transmit(self.output.output, self.current_packet) self.accepted = self.accepted + 1 end function L7Fw:push() local i = assert(self.input.input, "input port not found") local o = assert(self.output.output, "output port not found") local rules = self.rules local scanner = self.scanner assert(self.output.reject, "output port for reject policy not found") while not link.empty(i) do local pkt = link.receive(i) local flow = scanner:get_flow(pkt) -- so that pfmatch handler methods can access the original packet self.current_packet = pkt self.total = self.total + 1 if flow then local name = scanner:protocol_name(flow.protocol) local policy = rules[name] or rules["default"] self.current_protocol = name if policy == "accept" then self:accept(pkt.data, pkt.length) elseif policy == "drop" then self:drop(pkt.data, pkt.length) elseif policy == "reject" then self:reject(pkt.data, pkt.length) -- handle a pfmatch string case elseif type(policy) == "string" then if self.handler_map[policy] then -- we've already compiled a matcher for this policy self.handler_map[policy](self, pkt.data, pkt.length, flow.packets) else local opts = { extra_args = { "flow_count" } } local handler = match.compile(policy, opts) self.handler_map[policy] = handler handler(self, pkt.data, pkt.length, flow.packets) end -- TODO: what should the default policy be if there is none specified? else self:accept(pkt.data, pkt.length) end else -- TODO: we may wish to have a default policy for packets -- without detected flows instead of just forwarding self:accept(pkt.data, pkt.length) end end end function L7Fw:report() local accepted, rejected, dropped = self.accepted, self.rejected, self.dropped local total = self.total local a_pct = math.ceil((accepted / total) * 100) local r_pct = math.ceil((rejected / total) * 100) local d_pct = math.ceil((dropped / total) * 100) print(("Accepted packets: %d (%d%%)"):format(accepted, a_pct)) print(("Rejected packets: %d (%d%%)"):format(rejected, r_pct)) print(("Dropped packets: %d (%d%%)"):format(dropped, d_pct)) end local logging_priority = bit.bor(LOG_USER, LOG_INFO) function L7Fw:log_packet(type) local pkt = self.current_packet local protocol = self.current_protocol local eth_h = assert(ether:new_from_mem(pkt.data, pkt.length)) local ip_h if eth_h:type() == ETHER_PROTO_IPV4 then ip_h = ipv4:new_from_mem(pkt.data + eth_h:sizeof(), pkt.length - eth_h:sizeof()) elseif eth_h:type() == ETHER_PROTO_IPV6 then ip_h = ipv6:new_from_mem(pkt.data + eth_h:sizeof(), pkt.length - eth_h:sizeof()) end assert(ip_h) local msg = string.format("[Snabbwall %s] PROTOCOL=%s MAC=%s SRC=%s DST=%s", type, protocol, ether:ntop(eth_h:src()), ip_h:ntop(ip_h:src()), ip_h:ntop(ip_h:dst())) ffi.C.syslog(logging_priority, msg) end -- create either an ICMP port unreachable packet or a TCP RST to -- send in case of a reject policy function L7Fw:make_reject_response() local pkt = self.current_packet local ether_orig = assert(ether:new_from_mem(pkt.data, pkt.length)) local ip_orig if ether_orig:type() == ETHER_PROTO_IPV4 then ip_orig = ipv4:new_from_mem(pkt.data + ether_orig:sizeof(), pkt.length - ether_orig:sizeof()) elseif ether_orig:type() == ETHER_PROTO_IPV6 then ip_orig = ipv6:new_from_mem(pkt.data + ether_orig:sizeof(), pkt.length - ether_orig:sizeof()) else -- no responses to non-IP packes return end assert(ip_orig) local is_tcp = false local ip_protocol if ip_orig:version() == 4 then if ip_orig:protocol() == 6 then is_tcp = true ip_protocol = IP_PROTO_TCP else ip_protocol = IP_PROTO_ICMPV4 end else if ip_orig:next_header() == 6 then is_tcp = true ip_protocol = IP_PROTO_TCP else ip_protocol = IP_PROTO_ICMPV6 end end local dgram = datagram:new() local ether_h, ip_h if ip_orig:version() == 4 then ether_h = ether:new({ dst = ether_orig:src(), src = self.local_macaddr, type = ETHER_PROTO_IPV4 }) assert(self.local_ipv4, "config is missing local_ipv4") ip_h = ipv4:new({ dst = ip_orig:src(), src = ipv4:pton(self.local_ipv4), protocol = ip_protocol, ttl = 64 }) else ether_h = ether:new({ dst = ether_orig:src(), src = self.local_macaddr, type = ETHER_PROTO_IPV6 }) assert(self.local_ipv6, "config is missing local_ipv6") ip_h = ipv6:new({ dst = ip_orig:src(), src = ipv6:pton(self.local_ipv6), next_header = ip_protocol, ttl = 64 }) end if is_tcp then local tcp_orig = tcp:new_from_mem(pkt.data + ether_orig:sizeof() + ip_orig:sizeof(), pkt.length - ether_orig:sizeof() - ip_orig:sizeof()) assert(tcp_orig) local tcp_h = tcp:new({src_port = tcp_orig:dst_port(), dst_port = tcp_orig:src_port(), seq_num = tcp_orig:seq_num() + 1, ack_num = tcp_orig:ack_num() + 1, ack = 1, rst = 1, -- minimum TCP header size is 5 words offset = 5 }) -- checksum needs a non-nil first argument, but we have zero payload bytes -- so give a bogus value tcp_h:checksum(ffi.new("uint8_t[0]"), 0) dgram:push(tcp_h) if ip_h:version() == 4 then ip_h:total_length(ip_h:sizeof() + tcp_h:sizeof()) else ip_h:payload_length(ip_h:sizeof() + tcp_h:sizeof()) end else local icmp_h if ip_h:version() == 4 then -- ICMPv4 code & type for "port unreachable" icmp_h = icmp:new(3, 3) else -- ICMPv6 code & type for "administratively prohibited" icmp_h = icmp:new(1, 1) end dgram:payload(ffi.new("uint8_t [4]"), 4) if ip_h:version() == 4 then dgram:payload(ip_orig:header(), ip_orig:sizeof()) -- ICMPv4 port unreachable errors come with the original IPv4 -- header and 8 bytes of the original payload dgram:payload(pkt.data + ether_orig:sizeof() + ip_orig:sizeof(), 8) icmp_h:checksum(dgram:payload()) dgram:push(icmp_h) ip_h:total_length(ip_h:sizeof() + icmp_h:sizeof() + 4 + -- extra zero bytes ip_orig:sizeof() + 8) else -- ICMPv6 destination unreachable packets contain up to 1232 bytes -- of the original packet -- (the minimum MTU 1280 - IPv6 header length - ICMPv6 header) local payload_len = math.min(1232, pkt.length - ether_orig:sizeof() - ip_orig:sizeof()) dgram:payload(ip_orig:header(), ip_orig:sizeof()) dgram:payload(pkt.data + ether_orig:sizeof() + ip_orig:sizeof(), payload_len) local mem, len = dgram:payload() icmp_h:checksum(mem, len, ip_h) dgram:push(icmp_h) ip_h:payload_length(icmp_h:sizeof() + 4 + -- extra zero bytes ip_orig:sizeof() + payload_len) end end dgram:push(ip_h) dgram:push(ether_h) return dgram:packet() end function selftest() local savefile = require("pf.savefile") local pflua = require("pf") local function test(name, packet, pflang) local fake_self = { local_ipv4 = "192.168.42.42", local_ipv6 = "2001:0db8:85a3:0000:0000:8a2e:0370:7334", local_macaddr = "01:23:45:67:89:ab", current_packet = { data = packet.packet, length = packet.len } } local response = L7Fw.make_reject_response(fake_self) local pred = pf.compile_filter(pflang) assert(pred(response.data, response.length), string.format("test %s failed", name)) end local base_dir = "./program/wall/tests/data/" local dhcp = savefile.load_packets(base_dir .. "dhcp.pcap") local dhcpv6 = savefile.load_packets(base_dir .. "dhcpv6.pcap") local v4http = savefile.load_packets(base_dir .. "http.cap") local v6http = savefile.load_packets(base_dir .. "v6-http.cap") test("icmpv4-1", dhcp[2], [[ether proto ip]]) test("icmpv4-2", dhcp[2], [[ip proto icmp]]) test("icmpv4-3", dhcp[2], [[icmp and dst net 192.168.0.1]]) test("icmpv4-3", dhcp[2], [[icmp[icmptype] = 3 and icmp[icmpcode] = 3]]) test("icmpv6-1", dhcpv6[1], [[ether proto ip6]]) -- TODO: ip6 protochain is not implemented in pflang --test("icmpv6-2", dhcpv6[1], [[ip6 protochain 58]]) -- it would be nice to test the icmp type & code here, but pflang -- does not have good support for dereferencing ip6 protocols test("icmpv6-3", dhcpv6[1], [[icmp6 and dst net fe80::a00:27ff:fefe:8f95]]) test("tcpv4-1", v4http[5], [[ether proto ip]]) test("tcpv4-2", v4http[5], [[tcp and tcp[tcpflags] & (tcp-rst|tcp-ack) != 0]]) test("tcpv6-1", v6http[50], [[ether proto ip6]]) test("tcpv6-2", v6http[50], [[tcp]]) print("selftest ok") end
apache-2.0
kuoruan/luci
applications/luci-app-olsr/luasrc/model/cbi/olsr/olsrdiface6.lua
68
5949
-- Copyright 2010 Jo-Philipp Wich <jow@openwrt.org> -- Licensed to the public under the Apache License 2.0. local util = require "luci.util" local ip = require "luci.ip" function write_float(self, section, value) local n = tonumber(value) if n ~= nil then return Value.write(self, section, "%.1f" % n) end end m = Map("olsrd6", translate("OLSR Daemon - Interface"), translate("The OLSR daemon is an implementation of the Optimized Link State Routing protocol. ".. "As such it allows mesh routing for any network equipment. ".. "It runs on any wifi card that supports ad-hoc mode and of course on any ethernet device. ".. "Visit <a href='http://www.olsr.org'>olsrd.org</a> for help and documentation.")) m.redirect = luci.dispatcher.build_url("admin/services/olsrd6") if not arg[1] or m.uci:get("olsrd6", arg[1]) ~= "Interface" then luci.http.redirect(m.redirect) return end i = m:section(NamedSection, arg[1], "Interface", translate("Interface")) i.anonymous = true i.addremove = false i:tab("general", translate("General Settings")) i:tab("addrs", translate("IP Addresses")) i:tab("timing", translate("Timing and Validity")) ign = i:taboption("general", Flag, "ignore", translate("Enable"), translate("Enable this interface.")) ign.enabled = "0" ign.disabled = "1" ign.rmempty = false function ign.cfgvalue(self, section) return Flag.cfgvalue(self, section) or "0" end network = i:taboption("general", Value, "interface", translate("Network"), translate("The interface OLSRd should serve.")) network.template = "cbi/network_netlist" network.widget = "radio" network.nocreate = true mode = i:taboption("general", ListValue, "Mode", translate("Mode"), translate("Interface Mode is used to prevent unnecessary packet forwarding on switched ethernet interfaces. ".. "valid Modes are \"mesh\" and \"ether\". Default is \"mesh\".")) mode:value("mesh") mode:value("ether") mode.optional = true mode.rmempty = true weight = i:taboption("general", Value, "Weight", translate("Weight"), translate("When multiple links exist between hosts the weight of interface is used to determine the link to use. ".. "Normally the weight is automatically calculated by olsrd based on the characteristics of the interface, ".. "but here you can specify a fixed value. Olsrd will choose links with the lowest value.<br />".. "<b>Note:</b> Interface weight is used only when LinkQualityLevel is set to 0. ".. "For any other value of LinkQualityLevel, the interface ETX value is used instead.")) weight.optional = true weight.datatype = "uinteger" weight.placeholder = "0" lqmult = i:taboption("general", DynamicList, "LinkQualityMult", translate("LinkQuality Multiplicator"), translate("Multiply routes with the factor given here. Allowed values are between 0.01 and 1.0. ".. "It is only used when LQ-Level is greater than 0. Examples:<br />".. "reduce LQ to fd91:662e:3c58::1 by half: fd91:662e:3c58::1 0.5<br />".. "reduce LQ to all nodes on this interface by 20%: default 0.8")) lqmult.optional = true lqmult.rmempty = true lqmult.cast = "table" lqmult.placeholder = "default 1.0" function lqmult.validate(self, value) for _, v in pairs(value) do if v ~= "" then local val = util.split(v, " ") local host = val[1] local mult = val[2] if not host or not mult then return nil, translate("LQMult requires two values (IP address or 'default' and multiplicator) seperated by space.") end if not (host == "default" or ip.IPv6(host)) then return nil, translate("Can only be a valid IPv6 address or 'default'") end if not tonumber(mult) or tonumber(mult) > 1 or tonumber(mult) < 0.01 then return nil, translate("Invalid Value for LQMult-Value. Must be between 0.01 and 1.0.") end if not mult:match("[0-1]%.[0-9]+") then return nil, translate("Invalid Value for LQMult-Value. You must use a decimal number between 0.01 and 1.0 here.") end end end return value end ip6m = i:taboption("addrs", Value, "IPv6Multicast", translate("IPv6 multicast"), translate("IPv6 multicast address. Default is \"FF02::6D\", the manet-router linklocal multicast.")) ip6m.optional = true ip6m.datatype = "ip6addr" ip6m.placeholder = "FF02::6D" ip6s = i:taboption("addrs", Value, "IPv6Src", translate("IPv6 source"), translate("IPv6 src prefix. OLSRd will choose one of the interface IPs which matches the prefix of this parameter. ".. "Default is \"0::/0\", which triggers the usage of a not-linklocal interface IP.")) ip6s.optional = true ip6s.datatype = "ip6addr" ip6s.placeholder = "0::/0" hi = i:taboption("timing", Value, "HelloInterval", translate("Hello interval")) hi.optional = true hi.datatype = "ufloat" hi.placeholder = "5.0" hi.write = write_float hv = i:taboption("timing", Value, "HelloValidityTime", translate("Hello validity time")) hv.optional = true hv.datatype = "ufloat" hv.placeholder = "40.0" hv.write = write_float ti = i:taboption("timing", Value, "TcInterval", translate("TC interval")) ti.optional = true ti.datatype = "ufloat" ti.placeholder = "2.0" ti.write = write_float tv = i:taboption("timing", Value, "TcValidityTime", translate("TC validity time")) tv.optional = true tv.datatype = "ufloat" tv.placeholder = "256.0" tv.write = write_float mi = i:taboption("timing", Value, "MidInterval", translate("MID interval")) mi.optional = true mi.datatype = "ufloat" mi.placeholder = "18.0" mi.write = write_float mv = i:taboption("timing", Value, "MidValidityTime", translate("MID validity time")) mv.optional = true mv.datatype = "ufloat" mv.placeholder = "324.0" mv.write = write_float ai = i:taboption("timing", Value, "HnaInterval", translate("HNA interval")) ai.optional = true ai.datatype = "ufloat" ai.placeholder = "18.0" ai.write = write_float av = i:taboption("timing", Value, "HnaValidityTime", translate("HNA validity time")) av.optional = true av.datatype = "ufloat" av.placeholder = "108.0" av.write = write_float return m
apache-2.0
dios-game/dios-cocos-samples
src/lua-earth-warrior-3d/Resources/src/Plane.lua
2
1244
require("GameEntity") local Plane = class("Plane", function() return require("GameEntity").new() end) Plane.pXW = 1.1 Plane.pYW = 5.0 Plane.pZW = 1.0 Plane.pXA = 1.0 Plane.pYA = 10.0 Plane.pZA = 7.0 function Plane:init() self.pRate = 3.1415926/2 self.originX = -15.0 - 90.0 self.originY = 159.0 self.originZ = 9.0 --TODO use EffectSprite3D class instead(zhanghh) -- self._model = require("EffectSprite3D").new() -- self._model:init("playerv002.c3b", "playerv002_256.png"); self._model = cc.Sprite3D:create("playerv002.c3b") self._model:setTexture("playerv002_256.png") if (self._model ~= nil) then self._model:setScale(55) self._model:setRotation3D({x=self.originX, y=self.originY, z=self.originZ}) self:setRotation3D({x=self.originX, y=self.originY, z=self.originZ}) self:addChild(self._model) local function update(dt) self.pRate = self.pRate + 0.01 self._model:setRotation3D({x=0 - Plane.pXA * math.sin(Plane.pXW * self.pRate), y=0, z=0 - Plane.pZA * math.sin(Plane.pZW * self.pRate)}) end self:scheduleUpdateWithPriorityLua(update, 0) end return true end return Plane
mit
Kthulupwns/darkstar
scripts/zones/Dynamis-Xarcabard/mobs/Animated_Shield.lua
17
1481
----------------------------------- -- Area: Dynamis Xarcabard -- NPC: Animated Shield ----------------------------------- require("scripts/globals/status"); require("scripts/zones/Dynamis-Xarcabard/TextIDs"); ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) if(mob:AnimationSub() == 3) then SetDropRate(113,1822,1000); else SetDropRate(113,1822,0); end target:showText(mob,ANIMATED_SHIELD_DIALOG); SpawnMob(17330290,120):updateEnmity(target); SpawnMob(17330291,120):updateEnmity(target); SpawnMob(17330292,120):updateEnmity(target); SpawnMob(17330299,120):updateEnmity(target); SpawnMob(17330300,120):updateEnmity(target); SpawnMob(17330301,120):updateEnmity(target); end; ----------------------------------- -- onMobFight Action ----------------------------------- function onMobFight(mob,target) -- TODO: add battle dialog end; ----------------------------------- -- onMobDisengage ----------------------------------- function onMobDisengage(mob) mob:showText(mob,ANIMATED_SHIELD_DIALOG+2); end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) killer:showText(mob,ANIMATED_SHIELD_DIALOG+1); DespawnMob(17330290); DespawnMob(17330291); DespawnMob(17330292); DespawnMob(17330299); DespawnMob(17330300); DespawnMob(17330301); end;
gpl-3.0
vyrus714/Trap-Wars
game/dota_addons/trap_wars/scripts/vscripts/libraries/attachments.lua
1
21446
ATTACHMENTS_VERSION = "1.00" --[[ Lua-controlled Frankenstein Attachments Library by BMD Installation -"require" this file inside your code in order to gain access to the Attachments global table. -Optionally require "libraries/notifications" before this file so that the Attachment Configuration GUI can display messages via the Notifications library. -Ensure that this file is placed in the vscripts/libraries path -Ensure that you have the barebones_attachments.xml, barebones_attachments.js, and barebones_attachments.css files in your panorama content folder to use the GUI. -Ensure that barebones_attachments.xml is included in your custom_ui_manifest.xml with <CustomUIElement type="Hud" layoutfile="file://{resources}/layout/custom_game/barebones_attachments.xml" /> -Finally, include the "attachments.txt" in your scripts directory if you have a pre-build database of attachment settings. Library Usage -The library when required in loads in the "scripts/attachments.txt" file containing the attachment properties database for use during your game mode. -Attachment properties are specified as a 3-tuple of unit model name, attachment point string, and attachment prop model name. -Ex: ("models/heroes/antimage/antimage.vmdl" // "attach_hitloc" // "models/items/axe/weapon_heavy_cutter.vmdl") -Optional particles can be specified in the "Particles" block of attachmets.txt. -To attach a prop to a unit, use the Attachments:AttachProp(unit, attachPoint, model[, scale[, properties] ]) function -Ex: Attachments:AttachProp(unit, "attach_hitloc", "models/items/axe/weapon_heavy_cutter.vmdl", 1.0) -This will create the prop and retrieve the properties from the database to attach it to the provided unit -If you pass in an already created prop or unit as the 'model' parameter, the attachment system will scale, position, and attach that prop/unit without creating a new one -Scale is the prop scale to be used, and defaults to 1.0. The scale of the prop will also be scaled based on the unit model scale. -It is possible not to use the attachment database, but to instead provide the properties directly in the 'properties' parameter. -This properties table will look like: { pitch = 45.0, yaw = 55.0, roll = 65.0, XPos = 10.0, YPos = -10.0, ZPos = -33.0, Animation = "idle_hurt" } -To retrieve the currently attached prop entity, you can call Attachments:GetCurrentAttachment(unit, attachPoint) -Ex: local prop = Attachments:AttachProp(unit, "attach_hitloc") -Calling prop:RemoveSelf() will automatically detach the prop from the unit -To access the loaded Attachment database directly (for reading properties directly), you can call Attachments:GetAttachmentDatabase() Attachment Configuration Usage -In tools-mode, execute "attachment_configure <ADDON_NAME>" to activate the attachment configuration GUI for setting up the attachment database. -See https://www.youtube.com/watch?v=PS1XmHGP3sw for an example of how to generally use the GUI -The Load button will reload the database from disk and update the current attach point/prop model if values are stored therein. -The Hide button will hide/remove the current atatach point/prop model being displayed -The Save button will save the current properties as well as any other adjusted properties in the attachment database to disk. -Databases will be saved to the scripts/attachments.txt file of the addon you set when calling the attachment_configure <ADDON_NAME> command. -More detail to come... Notes -"attach_origin" can be used as the attachment string for attaching a prop do the origin of the unit, even if that unit has no attachment point named "attach_origin" -Attached props will automatically scale when the parent unit/models are scaled, so rescaling individual props after attachment is not necessary. -This library requires that the "libraries/timers.lua" be present in your vscripts directory. Examples: --Attach an Axe axe model to the "attach_hitloc" to a given unit at a 1.0 Scale. Attachments:AttachProp(unit, "attach_hitloc", "models/items/axe/weapon_heavy_cutter.vmdl", 1.0) --For GUI use, see https://www.youtube.com/watch?v=PS1XmHGP3sw ]] --LinkLuaModifier( "modifier_animation_freeze", "libraries/modifiers/modifier_animation_freeze.lua", LUA_MODIFIER_MOTION_NONE ) LinkLuaModifier( "modifier_animation_freeze_stun", "libraries/attachments.lua", LUA_MODIFIER_MOTION_NONE ) modifier_animation_freeze_stun = class({}) function modifier_animation_freeze_stun:OnCreated(keys) end function modifier_animation_freeze_stun:GetAttributes() return MODIFIER_ATTRIBUTE_PERMANENT + MODIFIER_ATTRIBUTE_IGNORE_INVULNERABLE --+ MODIFIER_ATTRIBUTE_MULTIPLE end function modifier_animation_freeze_stun:IsHidden() return true end function modifier_animation_freeze_stun:IsDebuff() return false end function modifier_animation_freeze_stun:IsPurgable() return false end function modifier_animation_freeze_stun:CheckState() local state = { [MODIFIER_STATE_FROZEN] = true, [MODIFIER_STATE_STUNNED] = true, } return state end -- Drop out of self-include to prevent execution of timers library and other code in modifier lua VM environment if not Entities or not Entities.CreateByClassname then return end require('libraries/timers') local Notify = function(player, msg, duration) duration = duration or 2 if Notifications then local table = {text=msg, duration=duration, style={color="red"}} Notifications:Bottom(player, table) else print('[Attachments.lua] ' .. msg) end end function WriteKV(file, firstLine, t, indent, done) if type(t) ~= "table" then return end done = done or {} done[t] = true indent = indent or 1 file:write(string.rep ("\t", indent-1) .. "\"" .. firstLine .. "\"\n") file:write(string.rep ("\t", indent-1) .. "{\n") for k,value in pairs(t) do if type(value) == "table" and not done[value] then done [value] = true WriteKV (file, k, value, indent + 1, done) elseif type(value) == "userdata" and not done[value] then --skip userdata else file:write(string.rep ("\t", indent) .. "\"" .. tostring(k) .. "\"\t\t\"" .. tostring(value) .. "\"\n") end end file:write(string.rep ("\t", indent-1) .. "}\n") end if not Attachments then Attachments = class({}) end function Attachments:start() local src = debug.getinfo(1).source --print(src) self.gameDir = "" self.addonName = "" if IsInToolsMode() then if src:sub(2):find("(.*dota 2 beta[\\/]game[\\/]dota_addons[\\/])([^\\/]+)[\\/]") then self.gameDir, self.addonName = string.match(src:sub(2), "(.*dota 2 beta[\\/]game[\\/]dota_addons[\\/])([^\\/]+)[\\/]") --print('[attachments] ', self.gameDir) --print('[attachments] ', self.addonName) self.initialized = true self.activated = false self.dbFilePath = nil self.currentAttach = {} self.hiddenCosmetics = {} self.doAttach = true self.doSphere = false self.attachDB = LoadKeyValues("scripts/attachments.txt") if IsInToolsMode() then print('[attachments] Tools Mode') SendToServerConsole("dota_combine_models 0") Convars:RegisterCommand( "attachment_configure", Dynamic_Wrap(Attachments, 'ActivateAttachmentSetup'), "Activate Attachment Setup", FCVAR_CHEAT ) end else print("[attachments] RELOADING") SendToServerConsole("script_reload_code " .. src:sub(2)) end else self.initialized = true self.activated = false self.dbFilePath = nil self.currentAttach = {} self.hiddenCosmetics = {} self.doAttach = true self.doSphere = false self.attachDB = LoadKeyValues("scripts/attachments.txt") end end function Attachments:ActivateAttachmentSetup() addon = Attachments.addonName --[[if addon == nil or addon == "" then print("[Attachments.lua] Addon name must be specified.") return end]] if not io then print("[Attachments.lua] Attachments Setup is only available in tools mode.") return end if not Attachments.activated then local file = io.open("../../dota_addons/" .. addon .. "/scripts/attachments.txt", 'r') if not file and Attachments.dbFilePath == nil then print("[Attachments.lua] Cannot find file 'dota_addons/" .. addon .. "/scripts/attachments.txt'. Re-execute the console command to force create the file.") Attachments.dbFilePath = "" return end Attachments.dbFilePath = "../../dota_addons/" .. addon .. "/scripts/attachments.txt" if not file then file = io.open(Attachments.dbFilePath, 'w') WriteKV(file, "Attachments", {}) print("[Attachments.lua] Created file: 'dota_addons/" .. addon .. "/scripts/attachments.txt'.") end file:close() CustomGameEventManager:RegisterListener("Attachment_DoSphere", Dynamic_Wrap(Attachments, "Attachment_DoSphere")) CustomGameEventManager:RegisterListener("Attachment_DoAttach", Dynamic_Wrap(Attachments, "Attachment_DoAttach")) CustomGameEventManager:RegisterListener("Attachment_Freeze", Dynamic_Wrap(Attachments, "Attachment_Freeze")) CustomGameEventManager:RegisterListener("Attachment_UpdateAttach", Dynamic_Wrap(Attachments, "Attachment_UpdateAttach")) CustomGameEventManager:RegisterListener("Attachment_SaveAttach", Dynamic_Wrap(Attachments, "Attachment_SaveAttach")) CustomGameEventManager:RegisterListener("Attachment_LoadAttach", Dynamic_Wrap(Attachments, "Attachment_LoadAttach")) CustomGameEventManager:RegisterListener("Attachment_HideAttach", Dynamic_Wrap(Attachments, "Attachment_HideAttach")) CustomGameEventManager:RegisterListener("Attachment_UpdateUnit", Dynamic_Wrap(Attachments, "Attachment_UpdateUnit")) CustomGameEventManager:RegisterListener("Attachment_HideCosmetic", Dynamic_Wrap(Attachments, "Attachment_HideCosmetic")) Attachments.activated = true Attachments.doSphere = true end local ply = Convars:GetCommandClient() CustomGameEventManager:Send_ServerToPlayer(ply, "activate_attachment_configuration", {}) end function Attachments:Attachment_DoSphere(args) --DebugPrint('Attachment_DoSphere') --DebugPrintTable(args) Attachments.doSphere = args.doSphere == 1 Attachments:Attachment_UpdateAttach(args) end function Attachments:Attachment_DoAttach(args) --DebugPrint('Attachment_DoAttach') --DebugPrintTable(args) Attachments.doAttach = args.doAttach == 1 Attachments:Attachment_UpdateAttach(args) end function Attachments:Attachment_Freeze(args) --DebugPrint('Attachment_Freeze') --DebugPrintTable(args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end if args.freeze == 1 then unit:AddNewModifier(unit, nil, "modifier_animation_freeze_stun", {}) unit:SetForwardVector(Vector(0,-1,0)) --unit:AddNewModifier(unit, nil, "modifier_stunned", {}) else unit:RemoveModifierByName("modifier_animation_freeze_stun") --unit:RemoveModifierByName("modifier_stunned") end end function Attachments:Attachment_UpdateAttach(args) DebugPrint('Attachment_UpdateAttach') DebugPrintTable(args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local properties = args.properties local unitModel = unit:GetModelName() local attach = properties.attach local model = properties.model properties.attach = nil properties.model = nil if not string.find(model, "%.vmdl$") then Notify(args.PlayerID, "Prop model must end in '.vmdl'.") return end local point = unit:ScriptLookupAttachment(attach) if attach ~= "attach_origin" and point == 0 then Notify(args.PlayerID, "Attach point '" .. attach .. "' not found.") return end local db = Attachments.attachDB if not db[unitModel] then db[unitModel] = {} end if not db[unitModel][attach] then db[unitModel][attach] = {} end local oldProperties = db[unitModel][attach][model] or {} -- update old properties for k,v in pairs(properties) do oldProperties[k] = v end properties = oldProperties db[unitModel][attach][model] = properties if not Attachments.currentAttach[args.index] then Attachments.currentAttach[args.index] = {} end local prop = Attachments.currentAttach[args.index][attach] if prop and IsValidEntity(prop) then prop:RemoveSelf() end --Attachments.currentAttach[args.index][attach] = Attachments:AttachProp(unit, attach, model, properties.scale) Attachments:AttachProp(unit, attach, model, properties.scale) end function Attachments:Attachment_SaveAttach(args) --DebugPrint('Attachment_SaveAttach') --DebugPrintTable(args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local properties = args.properties local unitModel = unit:GetModelName() local attach = properties.attach local model = properties.model Attachments:Attachment_UpdateAttach(args) if not io then print("[Attachments.lua] Attachments Setup is only available in tools mode.") return end if Attachments.dbFilePath == nil or Attachments.dbFilePath == "" then print("[Attachments.lua] Attachments database file must be set.") return end local file = io.open(Attachments.dbFilePath, 'w') WriteKV(file, "Attachments", Attachments.attachDB) file:close(); end function Attachments:Attachment_LoadAttach(args) --DebugPrint('Attachment_LoadAttach') --DebugPrintTable(args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local properties = args.properties local unitModel = unit:GetModelName() local attach = properties.attach local model = properties.model if not io then print("[Attachments.lua] Attachments Setup is only available in tools mode.") return end Attachments.attachDB = LoadKeyValues("scripts/attachments.txt") local db = Attachments.attachDB if not db[unitModel] or not db[unitModel][attach] or not db[unitModel][attach][model] then Notify(args.PlayerID, "No saved attach found for '" .. attach .. "'' / '" .. model .. "' on this unit.") return end local ply = PlayerResource:GetPlayer(args.PlayerID) local properties = {} for k,v in pairs(db[unitModel][attach][model]) do properties[k] = v end properties.attach = attach properties.model = model CustomGameEventManager:Send_ServerToPlayer(ply, "attachment_update_fields", properties) end function Attachments:Attachment_HideAttach(args) --DebugPrint('Attachment_HideAttach') --DebugPrintTable(args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local properties = args.properties local attach = properties.attach local currentAttach = Attachments.currentAttach if not currentAttach[args.index] or not currentAttach[args.index][attach] then Notify(args.PlayerID, "No Current Attach to Hide for '" .. attach .. "'.") return end local prop = currentAttach[args.index][attach] if prop and IsValidEntity(prop) then prop:RemoveSelf() end currentAttach[args.index][attach] = nil end function Attachments:Attachment_UpdateUnit(args) --DebugPrint('Attachment_UpdateUnit') --DebugPrintTable(args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local cosmetics = {} for i,child in ipairs(unit:GetChildren()) do if child:GetClassname() == "dota_item_wearable" and child:GetModelName() ~= "" then table.insert(cosmetics, child:GetModelName()) end end --DebugPrintTable(cosmetics) CustomGameEventManager:Send_ServerToPlayer(PlayerResource:GetPlayer(args.PlayerID), "attachment_cosmetic_list", cosmetics ) end function Attachments:Attachment_HideCosmetic(args) --DebugPrint('Attachment_HideCosmetic') --DebugPrintTable(args) local unit = EntIndexToHScript(args.index) if not unit then Notify(args.PlayerID, "Invalid Unit.") return end local model = args.model; local cosmetics = {} for i,child in ipairs(unit:GetChildren()) do if child:GetClassname() == "dota_item_wearable" and child:GetModelName() == model then local hiddenCosmetics = Attachments.hiddenCosmetics[args.index] if not hiddenCosmetics then hiddenCosmetics = {} Attachments.hiddenCosmetics[args.index] = hiddenCosmetics end if hiddenCosmetics[model] then child:RemoveEffects(EF_NODRAW) hiddenCosmetics[model] = nil else --print("HIDING") child:AddEffects(EF_NODRAW) hiddenCosmetics[model] = true end end end end function Attachments:GetAttachmentDatabase() return Attachments.attachDB end function Attachments:GetCurrentAttachment(unit, attachPoint) if not Attachments.currentAttach[unit:entindex()] then return nil end local prop = Attachments.currentAttach[unit:entindex()][attachPoint] return prop end function Attachments:AttachProp(unit, attachPoint, model, scale, properties) local unitModel = unit:GetModelName() local propModel = model local db = Attachments.attachDB if propModel.GetModelName then propModel = propModel:GetModelName() end if not properties then if not db[unitModel] or not db[unitModel][attachPoint] or not db[unitModel][attachPoint][propModel] then print("[Attachments.lua] No attach found in attachment database for '" .. unitModel .. "', '" .. attachPoint .. "', '" .. propModel .. "'") return end end local attach = unit:ScriptLookupAttachment(attachPoint) local scale = scale or db[unitModel][attachPoint][propModel]['scale'] or 1.0 properties = properties or db[unitModel][attachPoint][propModel] local pitch = tonumber(properties.pitch) local yaw = tonumber(properties.yaw) local roll = tonumber(properties.roll) --local angleSpace = QAngle(properties.QX, properties.QY, properties.QZ) local offset = Vector(tonumber(properties.XPos), tonumber(properties.YPos), tonumber(properties.ZPos)) * scale * unit:GetModelScale() local animation = properties.Animation --offset = RotatePosition(Vector(0,0,0), RotationDelta(angleSpace, QAngle(0,0,0)), offset) --local new_prop = Entities:CreateByClassname("prop_dynamic") local prop = nil if model.GetName and IsValidEntity(model) then prop = model else prop = SpawnEntityFromTableSynchronous("prop_dynamic", {model = propModel, DefaultAnim=animation, targetname=DoUniqueString("prop_dynamic")}) prop:SetModelScale(scale * unit:GetModelScale()) end local angles = unit:GetAttachmentAngles(attach) angles = QAngle(angles.x, angles.y, angles.z) --angles = RotationDelta(angles,QAngle(pitch, yaw, roll)) --print(prop:GetAngles()) --print(angles) --print(RotationDelta(RotationDelta(angles,QAngle(pitch, yaw, roll)),QAngle(0,0,0))) --angles = QAngle(pitch, yaw, roll) if not Attachments.doAttach then angles = QAngle(pitch, yaw, roll) end angles = RotateOrientation(angles,RotationDelta(QAngle(pitch, yaw, roll), QAngle(0,0,0))) --print('angleSpace = QAngle(' .. angles.x .. ', ' .. angles.y .. ', ' .. angles.z .. ')') local attach_pos = unit:GetAttachmentOrigin(attach) --attach_pos = attach_pos + RotatePosition(Vector(0,0,0), QAngle(angles.x,angles.y,angles.z), offset) attach_pos = attach_pos + RotatePosition(Vector(0,0,0), angles, offset) prop:SetAbsOrigin(attach_pos) prop:SetAngles(angles.x,angles.y,angles.z) -- Attach and store it if Attachments.doAttach then if attachPoint == "attach_origin" then prop:SetParent(unit, "") else prop:SetParent(unit, attachPoint) end end -- From Noya local particle_data = nil if db['Particles'] then particle_data = db['Particles'][propModel] end if particle_data then for particleName,control_points in pairs(particle_data) do prop.fx = ParticleManager:CreateParticle(particleName, PATTACH_ABSORIGIN, prop) -- Loop through the Control Point Entities for k,ent_point in pairs(control_points) do ParticleManager:SetParticleControlEnt(prop.fx, tonumber(k), prop, PATTACH_POINT_FOLLOW, ent_point, prop:GetAbsOrigin(), true) end end end if Attachments.timer then Timers:RemoveTimer(Attachments.timer) end Attachments.timer = Timers:CreateTimer(function() if Attachments.doSphere then if unit and IsValidEntity(unit) then DebugDrawSphere(unit:GetAttachmentOrigin(attach), Vector(255,255,255), 100, 15, true, .03) end if prop and IsValidEntity(prop) then DebugDrawSphere(prop:GetAbsOrigin(), Vector(0,0,0), 100, 15, true, .03) end end return .03 end) if not Attachments.currentAttach[unit:GetEntityIndex()] then Attachments.currentAttach[unit:GetEntityIndex()] = {} end Attachments.currentAttach[unit:GetEntityIndex()][attachPoint] = prop return prop end if not Attachments.initialized then Attachments:start() end
mit
amenophis1er/prosody-modules
mod_password_policy/mod_password_policy.lua
32
1288
-- Password policy enforcement for Prosody -- -- Copyright (C) 2012 Waqas Hussain -- -- -- Configuration: -- password_policy = { -- length = 8; -- } local options = module:get_option("password_policy"); options = options or {}; options.length = options.length or 8; local st = require "util.stanza"; function check_password(password) return #password >= options.length; end function handler(event) local origin, stanza = event.origin, event.stanza; if stanza.attr.type == "set" then local query = stanza.tags[1]; local passwords = {}; local dataform = query:get_child("x", "jabber:x:data"); if dataform then for _,tag in ipairs(dataform.tags) do if tag.attr.var == "password" then table.insert(passwords, tag:get_child_text("value")); end end end table.insert(passwords, query:get_child_text("password")); for _,password in ipairs(passwords) do if password and not check_password(password) then origin.send(st.error_reply(stanza, "cancel", "not-acceptable", "Please use a longer password.")); return true; end end end end module:hook("iq/self/jabber:iq:register:query", handler, 10); module:hook("iq/host/jabber:iq:register:query", handler, 10); module:hook("stanza/iq/jabber:iq:register:query", handler, 10);
mit
Kthulupwns/darkstar
scripts/globals/keyitems.lua
32
120326
--------------------------------------------- -- -- KEYITEMS IDS -- --------------------------------------------- ZERUHN_REPORT = 1; PALBOROUGH_MINES_LOGS = 2; BLUE_ACIDITY_TESTER = 3; RED_ACIDITY_TESTER = 4; LETTER_TO_THE_CONSULS_SANDORIA = 5; LETTER_TO_THE_CONSULS_BASTOK = 6; LETTER_TO_THE_CONSULS_WINDURST = 7; AIRSHIP_PASS = 8; AIRSHIP_PASS_FOR_KAZHAM = 9; OVERDUE_BOOK_NOTIFICATIONS = 10; LETTERS_FROM_DOMIEN = 11; C_L_REPORTS = 12; KINDRED_CREST = 13; MAGICITE_OPTISTONE = 14; MAGICITE_AURASTONE = 15; MAGICITE_ORASTONE = 16; FOOD_OFFERINGS = 17; DRINK_OFFERINGS = 18; CLOCK_TOWER_OIL = 19; YAGUDO_TORCH = 20; CREST_OF_DAVOI_KI = 21; LETTERS_TO_ALDO = 22; BOUQUETS_FOR_THE_PIONEERS = 23; OLD_TOOLBOX = 24; NOTES_FROM_HARIGAORIGA = 25; NOTES_FROM_IPUPU = 26; ART_FOR_EVERYONE = 27; CRACKED_MANA_ORBS = 28; KINDRED_REPORT = 29; LETTER_TO_THE_AMBASSADOR = 30; SWORD_OFFERING = 31; SHIELD_OFFERING = 32; DULL_SWORD = 33; DARK_KEY = 34; ADVENTURERS_CERTIFICATE = 35; STARWAY_STAIRWAY_BAUBLE = 36; FIRST_DARK_MANA_ORB = 37; CREATURE_COUNTER_MAGIC_DOLL = 38; OFF_OFFERING = 39; WINDURST_WATERS_SCOOP = 40; WINDURST_WALLS_SCOOP = 41; PORT_WINDURST_SCOOP = 42; WINDURST_WOODS_SCOOP = 43; TEMPLE_KNIGHTS_DAVOI_REPORT = 44; SILVER_BELL = 45; CORUSCANT_ROSARY = 46; BLACK_MATINEE_NECKLACE = 47; DUCAL_GUARDS_LANTERN = 48; DUCAL_GUARDS_LANTERN_LIT = 49; HOLY_CANDLE = 50; SECOND_DARK_MANA_ORB = 51; THIRD_DARK_MANA_ORB = 52; FOURTH_DARK_MANA_ORB = 53; FIFTH_DARK_MANA_ORB = 54; SIXTH_DARK_MANA_ORB = 55; ARCHDUCAL_AUDIENCE_PERMIT = 56; SUPER_SOUP_POT = 57; TWO_OF_SWORDS = 58; FIRST_GLOWING_MANA_ORB = 59; SECOND_GLOWING_MANA_ORB = 60; THIRD_GLOWING_MANA_ORB = 61; FOURTH_GLOWING_MANA_ORB = 62; FIFTH_GLOWING_MANA_ORB = 63; SIXTH_GLOWING_MANA_ORB = 64; RESCUE_TRAINING_CERTIFICATE = 65; CHARM_OF_LIGHT = 66; HIDEOUT_KEY = 67; LAPIS_CORAL = 68; MESSAGE_TO_JEUNO_SANDORIA = 69; MESSAGE_TO_JEUNO_BASTOK = 70; MESSAGE_TO_JEUNO_WINDURST = 71; NEW_FEIYIN_SEAL = 72; BURNT_SEAL = 73; SHADOW_FRAGMENT = 74; RONFAURE_SUPPLIES = 75; ZULKHEIM_SUPPLIES = 76; NORVALLEN_SUPPLIES = 77; GUSTABERG_SUPPLIES = 78; DERFLAND_SUPPLIES = 79; SARUTABARUTA_SUPPLIES = 80; KOLSHUSHU_SUPPLIES = 81; ARAGONEU_SUPPLIES = 82; FAUREGANDI_SUPPLIES = 83; VALDEAUNIA_SUPPLIES = 84; LITELOR_SUPPLIES = 85; KUZOTZ_SUPPLIES = 86; VOLLBOW_SUPPLIES = 87; LAPIS_MONOCLE = 88; DONATION_ENVELOPE = 89; ARAGONEU_PIZZA = 90; LAND_CRAB_BISQUE = 91; MHAURAN_COUSCOUS = 92; ETCHED_RING = 93; TRADERS_SACK = 94; FAKE_MOUSTACHE = 95; GARDENIA_PASS = 96; WEAPONS_ORDER = 97; WEAPONS_RECEIPT = 98; SMALL_BAG = 99; RANPIMONPIS_SPECIAL_STEW = 100; FERRY_TICKET = 101; STAMP_SHEET = 102; LOST_DOCUMENT = 103; EAST_BLOCK_CODE = 104; SOUTH_BLOCK_CODE = 105; NORTH_BLOCK_CODE = 106; LETTER_FROM_ROH_LATTEH = 107; PAINTING_OF_A_WINDMILL = 108; TATTERED_MISSION_ORDERS = 109; MONASTIC_CAVERN_KEY = 110; MOON_CRYSTAL = 111; SOUTHEASTERN_STAR_CHARM = 112; WONDER_MAGIC_SET = 113; UNFINISHED_LETTER = 114; NEW_MODEL_HAT = 115; ANGELICAS_AUTOGRAPH = 116; OLD_TIGERS_FANG = 117; TENSHODO_MEMBERS_CARD = 118; RECEIPT_FOR_THE_PRINCE = 119; MAGIC_TRASH = 120; TENSHODO_APPLICATION_FORM = 121; SHARP_GRAY_STONE = 122; CATHEDRAL_DONATION = 123; QUFIM_SUPPLIES = 124; TATTERED_TEST_SHEET = 125; A_SONG_OF_LOVE = 126; STEAMING_SHEEP_INVITATION = 127; BROKEN_WAND = 128; GULEMONTS_DOCUMENT = 129; OLD_RING = 130; WHITE_ORB = 131; PINK_ORB = 132; RED_ORB = 133; BLOOD_ORB = 134; CURSED_ORB = 135; CRIMSON_ORB = 136; KEY_TO_THE_OZTROJA_MINES = 137; CHOCOBO_LICENSE = 138; CURSEPAPER = 139; CORRUPTED_DIRT = 140; STALACTITE_DEW = 141; SQUIRE_CERTIFICATE = 142; BOOK_OF_TASKS = 143; BOOK_OF_THE_EAST = 144; BOOK_OF_THE_WEST = 145; KNIGHTS_SOUL = 146; COLD_MEDICINE = 147; AMAURAS_FORMULA = 148; OVERDUE_BOOK_NOTIFICATION = 149; SCRIPTURE_OF_WATER = 150; SCRIPTURE_OF_WIND = 151; TAMIS_NOTE = 152; THYME_MOSS = 153; COUGH_MEDICINE = 154; SCROLL_OF_TREASURE = 155; CODE_OF_BEASTMASTERS = 156; ORCISH_HUT_KEY = 157; STAR_CRESTED_SUMMONS = 158; BRUGAIRE_GOODS = 159; SMALL_TEACUP = 160; SUSPICIOUS_ENVELOPE = 161; CARRIER_PIGEON_LETTER = 162; CARMELOS_SONG_SHEET = 163; CURILLAS_BOTTLE_EMPTY = 164; CURILLAS_BOTTLE_FULL = 165; NEUTRALIZER = 166; GOLDSMITHING_ORDER = 167; MYTHRIL_HEARTS = 168; TESTIMONIAL = 169; LETTER_FROM_ZEID = 170; SHANTOTTOS_NEW_SPELL = 171; SHANTOTTOS_EXSPELL = 172; BUCKET_OF_DIVINE_PAINT = 173; LETTER_FROM_VIRNAGE = 174; SPIRIT_INCENSE = 175; GANTINEUXS_LETTER = 176; SEAL_OF_BANISHING = 177; MAGICAL_PATTERN = 178; FEIYIN_MAGIC_TOME = 179; SLUICE_SURVEYOR_MK_I = 180; FOE_FINDER_MK_I = 181; EARTHEN_CHARM = 182; LETTER_FROM_THE_TENSHODO = 183; TENSHODO_ENVELOPE = 184; SIGNED_ENVELOPE = 185; GANG_WHEREABOUTS_NOTE = 186; FIRST_FORGED_ENVELOPE = 187; SECOND_FORGED_ENVELOPE = 188; FIRST_SIGNED_FORGED_ENVELOPE = 189; SECOND_SIGNED_FORGED_ENVELOPE = 190; LETTER_FROM_DALZAKK = 191; SANDORIAN_MARTIAL_ARTS_SCROLL = 192; BOMB_INCENSE = 193; PERCHONDS_ENVELOPE = 194; PORTAL_CHARM = 195; ORCISH_DRIED_FOOD = 196; OLD_POCKET_WATCH = 197; OLD_BOOTS = 198; BALGA_CHAMPION_CERTIFICATE = 199; HOLY_ONES_OATH = 200; CRAWLER_BLOOD = 201; CAT_BURGLARS_NOTE = 202; CHIEFTAINNESS_TWINSTONE_EARRING = 203; NORTHERN_VINE = 204; SOUTHERN_VINE = 205; EASTERN_VINE = 206; WESTERN_VINE = 207; SWORD_GRIP_MATERIAL = 208; YASINS_SWORD = 209; OLD_GAUNTLETS = 210; SHADOW_FLAMES = 211; FIREBLOOM_TREE_WOOD = 212; LETTER_TO_ANGELICA = 213; FINAL_FANTASY = 214; RIPPED_FINAL_FANTASY_PAINTING = 215; FINAL_FANTASY_PART_II = 216; TAMERS_WHISTLE = 217; KNIGHTS_BOOTS = 218; MIQUES_PAINTBRUSH = 219; STRANGE_SHEET_OF_PAPER = 220; KNIGHTS_CONFESSION = 221; ROUND_FRIGICITE = 222; SQUARE_FRIGICITE = 223; TRIANGULAR_FRIGICITE = 224; STAR_RING1 = 225; STAR_RING2 = 226; MOON_RING = 227; MERTAIRES_BRACELET = 228; AQUAFLORA1 = 229; AQUAFLORA2 = 230; AQUAFLORA3 = 231; GUIDING_BELL = 232; ORDELLE_WHETSTONE = 233; LETTER_FROM_THE_DARKSTEEL_FORGE = 234; DARKSTEEL_FORMULA = 235; KOHS_LETTER = 236; ROYAL_KNIGHTS_DAVOI_REPORT = 237; SACRIFICIAL_CHAMBER_KEY = 238; FIRE_FRAGMENT = 239; WATER_FRAGMENT = 240; EARTH_FRAGMENT = 241; WIND_FRAGMENT = 242; LIGHTNING_FRAGMENT = 243; ICE_FRAGMENT = 244; LIGHT_FRAGMENT = 245; DARK_FRAGMENT = 246; PRISMATIC_FRAGMENT = 247; SOUTHWESTERN_STAR_CHARM = 248; HOLY_ONES_INVITATION = 249; OPTISTERY_RING = 250; BLANK_BOOK_OF_THE_GODS = 251; BOOK_OF_THE_GODS = 252; NONBERRYS_KNIFE = 253; SUBLIME_STATUE_OF_THE_GODDESS = 254; RAUTEINOTS_PARCEL = 255; TREASURE_MAP = 256; STRANGELY_SHAPED_CORAL = 257; SEALED_DAGGER = 258; ANGELICAS_LETTER = 259; EMPTY_BARREL = 260; BARREL_OF_OPOOPO_BREW = 261; ELSHIMO_LOWLANDS_SUPPLIES = 262; ELSHIMO_UPLANDS_SUPPLIES = 263; JOKER_CARD = 264; ORASTERY_RING = 265; ALTEPA_MOONPEBBLE = 266; RHINOSTERY_CERTIFICATE = 267; DREAMROSE = 268; ANCIENT_SANDORIAN_BOOK = 269; PIECE_OF_PAPER = 270; INVISIBLE_MAN_STICKER = 271; PAINTBRUSH_OF_SOULS = 272; OLD_RUSTY_KEY = 273; ANCIENT_TABLET_FRAGMENT = 274; STAR_SEEKER = 275; AURASTERY_RING = 276; TABLET_OF_ANCIENT_MAGIC = 277; LETTER_FROM_ALFESAR = 278; MAGIC_DRAINED_STAR_SEEKER = 279; RHINOSTERY_RING = 280; MANUSTERY_RING = 281; GLOVE_OF_PERPETUAL_TWILIGHT = 282; ANCIENT_SANDORIAN_TABLET = 283; CRYSTAL_DOWSER = 284; PIECE_OF_A_BROKEN_KEY1 = 285; PIECE_OF_A_BROKEN_KEY2 = 286; PIECE_OF_A_BROKEN_KEY3 = 287; DROPS_OF_AMNIO = 288; REINFORCED_CERMET = 289; LETTER_FROM_WEREI = 290; TONBERRY_KEY = 291; THESIS_ON_ALCHEMY = 292; OLD_PIECE_OF_WOOD = 293; DRAGON_CURSE_REMEDY = 294; SEALED_IRON_BOX = 295; SEA_SERPENT_STATUE = 296; ALTEPA_POLISHING_STONE = 297; CHALLENGE_TO_THE_ROYAL_KNIGHTS = 298; RANCHURIOMES_LEGACY = 299; RONFAURE_EF_INSIGNIA = 300; ZULKHEIM_EF_INSIGNIA = 301; NORVALLEN_EF_INSIGNIA = 302; GUSTABERG_EF_INSIGNIA = 303; DERFLAND_EF_INSIGNIA = 304; SARUTABARUTA_EF_INSIGNIA = 305; KOLSHUSHU_EF_INSIGNIA = 306; ARAGONEU_EF_INSIGNIA = 307; FAUREGANDI_EF_INSIGNIA = 308; VALDEAUNIA_EF_INSIGNIA = 309; QUFIM_EF_INSIGNIA = 310; LITELOR_EF_INSIGNIA = 311; KUZOTZ_EF_INSIGNIA = 312; VOLLBOW_EF_INSIGNIA = 313; ELSHIMO_LOWLANDS_EF_INSIGNIA = 314; ELSHIMO_UPLANDS_EF_INSIGNIA = 315; KEY_ITEM316 = 316; KEY_ITEM317 = 317; KEY_ITEM318 = 318; KEY_ITEM319 = 319; WHISPER_OF_FLAMES = 320; WHISPER_OF_TREMORS = 321; WHISPER_OF_TIDES = 322; WHISPER_OF_GALES = 323; WHISPER_OF_FROST = 324; WHISPER_OF_STORMS = 325; WHISPER_OF_THE_MOON = 326; WHISPER_OF_DREAMS = 327; TUNING_FORK_OF_FIRE = 328; TUNING_FORK_OF_EARTH = 329; TUNING_FORK_OF_WATER = 330; TUNING_FORK_OF_WIND = 331; TUNING_FORK_OF_ICE = 332; TUNING_FORK_OF_LIGHTNING = 333; MOON_BAUBLE = 334; VIAL_OF_DREAM_INCENSE = 335; ORCISH_CREST = 336; QUADAV_CREST = 337; YAGUDO_CREST = 338; UN_MOMENT = 339; LEPHEMERE = 340; LANCIENNE = 341; CHANSON_DE_LIBERTE = 342; WEAPON_TRAINING_GUIDE = 343; MAP_TO_THE_ANNALS_OF_TRUTH = 344; ANNALS_OF_TRUTH = 345; COMPLETION_CERTIFICATE = 346; DYNAMIS_DEBUGGER = 347; DROPPED_ITEM = 348; WHITE_CARD = 349; RED_CARD = 350; BLACK_CARD = 351; HOLLA_GATE_CRYSTAL = 352; DEM_GATE_CRYSTAL = 353; MEA_GATE_CRYSTAL = 354; VAHZL_GATE_CRYSTAL = 355; YHOATOR_GATE_CRYSTAL = 356; ALTEPA_GATE_CRYSTAL = 357; PROMYVION_HOLLA_SLIVER = 358; PROMYVION_DEM_SLIVER = 359; PROMYVION_MEA_SLIVER = 360; WHISPER_OF_THE_WYRMKING = 361; NOTE_WRITTEN_BY_ESHANTARL = 362; RAINBOW_RESONATOR = 363; FADED_RUBY = 364; TATTERED_MAZE_MONGER_POUCH = 365; CRIMSON_STRATUM_ABYSSITE = 366; CRIMSON_STRATUM_ABYSSITE_II = 367; CRIMSON_STRATUM_ABYSSITE_III = 368; CRIMSON_STRATUM_ABYSSITE_IV = 369; INDIGO_STRATUM_ABYSSITE = 370; INDIGO_STRATUM_ABYSSITE_II = 371; INDIGO_STRATUM_ABYSSITE_III = 372; INDIGO_STRATUM_ABYSSITE_IV = 373; JADE_STRATUM_ABYSSITE = 374; JADE_STRATUM_ABYSSITE_II = 375; JADE_STRATUM_ABYSSITE_III = 376; JADE_STRATUM_ABYSSITE_IV = 377; SHODDY_METAL_CLASP = 378; BUNDLE_OF_SUNDRY_PLANTS = 379; SQUARE_OF_ULTIMATE_CLOTH = 380; PLIABLE_LIZARD_SKIN = 381; SQUARE_OF_LIZARD_LEATHER = 382; MAP_OF_ABDH_ISLE_PURGONORGO = 383; MAP_OF_THE_SAN_DORIA_AREA = 385; MAP_OF_THE_BASTOK_AREA = 386; MAP_OF_THE_WINDURST_AREA = 387; MAP_OF_THE_JEUNO_AREA = 388; MAP_OF_QUFIM_ISLAND = 389; MAP_OF_THE_NORTHLANDS_AREA = 390; MAP_OF_KING_RANPERRES_TOMB = 391; MAP_OF_THE_DANGRUF_WADI = 392; MAP_OF_THE_HORUTOTO_RUINS = 393; MAP_OF_BOSTAUNIEUX_OUBLIETTE = 394; MAP_OF_THE_ZERUHN_MINES = 395; MAP_OF_THE_TORAIMARAI_CANAL = 396; MAP_OF_ORDELLES_CAVES = 397; MAP_OF_THE_GUSGEN_MINES = 398; MAP_OF_THE_MAZE_OF_SHAKHRAMI = 399; MAP_OF_THE_ELDIEME_NECROPOLIS = 400; MAP_OF_THE_CRAWLERS_NEST = 401; MAP_OF_THE_GARLAIGE_CITADEL = 402; MAP_OF_THE_RANGUEMONT_PASS = 403; MAP_OF_GHELSBA = 404; MAP_OF_DAVOI = 405; MAP_OF_THE_PALBOROUGH_MINES = 406; MAP_OF_BEADEAUX = 407; MAP_OF_GIDDEUS = 408; MAP_OF_CASTLE_OZTROJA = 409; MAP_OF_DELKFUTTS_TOWER = 410; MAP_OF_FEIYIN = 411; MAP_OF_CASTLE_ZVAHL = 412; MAP_OF_THE_ELSHIMO_REGIONS = 413; MAP_OF_THE_KUZOTZ_REGION = 414; MAP_OF_THE_LITELOR_REGION = 415; MAP_OF_THE_RUAUN_GARDENS = 416; MAP_OF_NORG = 417; MAP_OF_THE_TEMPLE_OF_UGGALEPIH = 418; MAP_OF_THE_DEN_OF_RANCOR = 419; MAP_OF_THE_KORROLOKA_TUNNEL = 420; MAP_OF_THE_KUFTAL_TUNNEL = 421; MAP_OF_THE_BOYAHDA_TREE = 422; MAP_OF_THE_VELUGANNON_PALACE = 423; MAP_OF_IFRITS_CAULDRON = 424; MAP_OF_THE_QUICKSAND_CAVES = 425; MAP_OF_THE_SEA_SERPENT_GROTTO = 426; MAP_OF_THE_VOLLBOW_REGION = 427; MAP_OF_THE_LABYRINTH_OF_ONZOZO = 428; MAP_OF_CARPENTERS_LANDING = 429; MAP_OF_BIBIKI_BAY = 430; MAP_OF_THE_ULEGUERAND_RANGE = 431; MAP_OF_THE_ATTOHWA_CHASM = 432; MAP_OF_PSOXJA = 433; MAP_OF_OLDTON_MOVALPOLOS = 434; MAP_OF_NEWTON_MOVALPOLOS = 435; MAP_OF_PROMYVION_HOLLA = 436; MAP_OF_PROMYVION_DEM = 437; MAP_OF_PROMYVION_MEA = 438; MAP_OF_PROMYVION_VAHZL = 439; MAP_OF_TAVNAZIA = 440; MAP_OF_THE_AQUEDUCTS = 441; MAP_OF_THE_SACRARIUM = 442; MAP_OF_CAPE_RIVERNE = 443; MAP_OF_ALTAIEU = 444; MAP_OF_HUXZOI = 445; MAP_OF_RUHMET = 446; MAP_OF_DIO_ABDHALJS_GHELSBA = 447; DAZEBREAKER_CHARM = 448; SHINY_EARRING = 449; CARBUNCLES_TEAR = 450; SCRAP_OF_PAPYRUS = 451; CERULEAN_CRYSTAL = 452; HANDFUL_OF_CRYSTAL_SCALES = 453; CHARRED_HELM = 454; SHARD_OF_APATHY = 455; SHARD_OF_ARROGANCE = 456; SHARD_OF_COWARDICE = 457; SHARD_OF_ENVY = 458; SHARD_OF_RAGE = 459; TRICK_BOX = 460; WASHUS_TASTY_WURST = 461; YOMOTSU_FEATHER = 462; YOMOTSU_HIRASAKA = 463; FADED_YOMOTSU_HIRASAKA = 464; SEANCE_STAFF = 465; SMILING_STONE = 466; SCOWLING_STONE = 467; SOMBER_STONE = 468; SPIRITED_STONE = 469; OLD_TRICK_BOX = 470; LARGE_TRICK_BOX = 471; INDIGESTED_STALAGMITE = 472; INDIGESTED_ORE = 473; INDIGESTED_MEAT = 474; LETTER_FROM_ZONPAZIPPA = 475; MOONDROP = 476; MIRACLESALT = 477; ANCIENT_VERSE_OF_ROMAEVE = 478; ANCIENT_VERSE_OF_ALTEPA = 479; ANCIENT_VERSE_OF_UGGALEPIH = 480; FIGURE_OF_LEVIATHAN = 481; FIGURE_OF_GARUDA = 482; FIGURE_OF_TITAN = 483; DARK_MANA_ORB = 484; MOONGATE_PASS = 485; HYDRA_CORPS_COMMAND_SCEPTER = 486; HYDRA_CORPS_EYEGLASS = 487; HYDRA_CORPS_LANTERN = 488; HYDRA_CORPS_TACTICAL_MAP = 489; HYDRA_CORPS_INSIGNIA = 490; HYDRA_CORPS_BATTLE_STANDARD = 491; VIAL_OF_SHROUDED_SAND = 492; DIARY_OF_MUKUNDA = 493; LETTER_TO_THE_BAS_CONFLICT_CMD1 = 494; LETTER_TO_THE_WIN_CONFLICT_CMD1 = 495; LETTER_TO_THE_SAN_CONFLICT_CMD1 = 496; LETTER_TO_THE_WIN_CONFLICT_CMD2 = 497; LETTER_TO_THE_SAN_CONFLICT_CMD2 = 498; LETTER_TO_THE_BAS_CONFLICT_CMD2 = 499; BALLISTA_EARRING = 500; DRAWING_OF_A_MALE_HUME = 501; DRAWING_OF_A_FEMALE_HUME = 502; DRAWING_OF_A_MALE_ELVAAN = 503; DRAWING_OF_A_FEMALE_ELVAAN = 504; DRAWING_OF_A_MALE_TARUTARU = 505; DRAWING_OF_A_FEMALE_TARUTARU = 506; DRAWING_OF_A_MITHRA = 507; DRAWING_OF_A_GALKA = 508; YE_OLDE_MANNEQUIN_CATALOGUE = 509; MANNEQUIN_JOINT_DIAGRAMS = 510; CLAMMING_KIT = 511; MOGHANCEMENT_FIRE = 512; MOGHANCEMENT_ICE = 513; MOGHANCEMENT_WIND = 514; MOGHANCEMENT_EARTH = 515; MOGHANCEMENT_LIGHTNING = 516; MOGHANCEMENT_WATER = 517; MOGHANCEMENT_LIGHT = 518; MOGHANCEMENT_DARK = 519; MOGHANCEMENT_EXPERIENCE = 520; MOGHANCEMENT_GARDENING = 521; MOGHANCEMENT_DESYNTHESIS = 522; MOGHANCEMENT_FISHING = 523; MOGHANCEMENT_WOODWORKING = 524; MOGHANCEMENT_SMITHING = 525; MOGHANCEMENT_GOLDSMITHING = 526; MOGHANCEMENT_CLOTHCRAFT = 527; MOGHANCEMENT_LEATHERCRAFT = 528; MOGHANCEMENT_BONECRAFT = 529; MOGHANCEMENT_ALCHEMY = 530; MOGHANCEMENT_COOKING = 531; MOGHANCEMENT_CONQUEST = 532; MOGHANCEMENT_REGION = 533; MOGHANCEMENT_FISHINGITEMS = 534; MOGHANCEMENT_SAN_CONQUEST = 535; MOGHANCEMENT_BAS_CONQUEST = 536; MOGHANCEMENT_WIN_CONQUEST = 537; MOGHANCEMENT_MONEY = 538; MOGHANCEMENT_CAMPAIGN = 539; MOGLIFICATION_FISHING = 544; MOGLIFICATION_WOODWORKING = 545; MOGLIFICATION_SMITHING = 546; MOGLIFICATION_GOLDSMITHING = 547; MOGLIFICATION_CLOTHCRAFT = 548; MOGLIFICATION_LEATHERCRAFT = 549; MOGLIFICATION_BONECRAFT = 550; MOGLIFICATION_ALCHEMY = 551; MOGLIFICATION_COOKING = 552; MEGA_MOGLIFICATION_FISHING = 553; MEGA_MOGLIFICATION_WOODWORK = 554; MEGA_MOGLIFICATION_SMITHING = 555; MEGA_MOGLIFICATION_GOLDSMITH = 556; MEGA_MOGLIFICATION_CLOTHCRAFT = 557; MEGA_MOGLIFICATION_LEATHRCRFT = 558; MEGA_MOGLIFICATION_BONECRAFT = 559; MEGA_MOGLIFICATION_ALCHEMY = 560; MEGA_MOGLIFICATION_COOKING = 561; BALLISTA_LICENSE = 576; BALLISTA_INSTAWARP = 577; BALLISTA_INSTAPORT = 578; MYSTERIOUS_AMULET = 579; MYSTERIOUS_AMULET_DRAINED = 580; CRACKED_MIMEO_MIRROR = 581; RELIQUIARIUM_KEY = 582; MIMEO_STONE = 583; MYSTIC_ICE = 584; KEY_ITEM585 = 585; MIMEO_JEWEL = 586; MIMEO_FEATHER = 587; SECOND_MIMEO_FEATHER = 588; THIRD_MIMEO_FEATHER = 589; LIGHT_OF_HOLLA = 590; LIGHT_OF_DEM = 591; LIGHT_OF_MEA = 592; LIGHT_OF_VAHZL = 593; LIGHT_OF_ALTAIEU = 594; BLUE_BRACELET = 595; GREEN_BRACELET = 596; DUSTY_TOME = 597; POINTED_JUG = 598; CRACKED_CLUB = 599; PEELING_HAIRPIN = 600; OLD_NAMETAG = 601; TINY_WRISTLET = 602; WHISPERING_CONCH = 603; PSOXJA_PASS = 604; PIECE_OF_RIPPED_FLOORPLANS = 605; LIMIT_BREAKER = 606; HYPER_ALTIMETER = 607; MOLYBDENUM_BOX = 608; ALABASTER_HAIRPIN = 609; DAWN_TALISMAN = 610; SILVER_COMETS_COLLAR = 611; ENVELOPE_FROM_MONBERAUX = 612; DELKFUTT_RECOGNITION_DEVICE = 613; DEED_TO_PURGONORGO_ISLE = 614; PHOENIX_ARMLET = 615; PHOENIX_PEARL = 616; MANACLIPPER_TICKET = 617; BARGE_TICKET = 618; ALLYOUCANRIDEPASS = 619; TAVNAZIAN_ARCHIPELAGO_SUPPLIES = 620; RIVERNEWORT = 621; TAVNAZIAN_COOKBOOK = 622; WASHUS_FLASK = 623; FLASK_OF_CLAM_WATER = 624; PUNGENT_PROVIDENCE_POT = 625; TORN_OUT_PAGES = 626; TONBERRY_BLACKBOARD = 627; LETTER_FROM_MUCKVIX = 628; LETTER_FROM_MAGRIFFON = 629; PROVIDENCE_POT = 630; CARE_PACKAGE = 631; GLITTERING_FRAGMENT = 632; STOREROOM_KEY = 633; ZEELOZOKS_EARPLUG = 634; POTION_VOUCHER = 635; HIPOTION_VOUCHER = 636; XPOTION_VOUCHER = 637; ETHER_VOUCHER = 638; HIETHER_VOUCHER = 639; SUPER_ETHER_VOUCHER = 640; ELIXER_VOUCHER = 641; REVITALIZER_VOUCHER = 642; BODY_BOOST_VOUCHER = 643; MANA_BOOST_VOUCHER = 644; DRACHENESSENCE_VOUCHER = 645; BARFIRE_OINTMENT_VOUCHER = 646; BARBLIZZARD_OINTMENT_VOUCHER = 647; BARAERO_OINTMENT_VOUCHER = 648; BARSTONE_OINTMENT_VOUCHER = 649; BARTHUNDER_OINTMENT_VOUCHER = 650; BARWATER_OINTMENT_VOUCHER = 651; BARGE_MULTITICKET = 652; MANACLIPPER_MULTITICKET = 653; FIGHTERS_ARMOR_CLAIM_SLIP = 654; TEMPLE_ATTIRE_CLAIM_SLIP = 655; HEALERS_ATTIRE_CLAIM_SLIP = 656; WIZARDS_ATTIRE_CLAIM_SLIP = 657; WARLOCKS_ARMOR_CLAIM_SLIP = 658; ROGUES_ATTIRE_CLAIM_SLIP = 659; GALLANT_ARMOR_CLAIM_SLIP = 660; CHAOS_ARMOR_CLAIM_SLIP = 661; BEAST_ARMOR_CLAIM_SLIP = 662; CHORAL_ATTIRE_CLAIM_SLIP = 663; HUNTERS_ATTIRE_CLAIM_SLIP = 664; MYOCHIN_ARMOR_CLAIM_SLIP = 665; NINJAS_GARB_CLAIM_SLIP = 666; DRACHEN_ARMOR_CLAIM_SLIP = 667; EVOKERS_ATTIRE_CLAIM_SLIP = 668; VESSEL_OF_LIGHT = 669; CENSER_OF_ABANDONMENT = 670; CENSER_OF_ANTIPATHY = 671; CENSER_OF_ANIMUS = 672; CENSER_OF_ACRIMONY = 673; MONARCH_BEARD = 674; ASTRAL_COVENANT = 675; SHAFT_2716_OPERATING_LEVER = 676; ZEPHYR_FAN = 677; MIASMA_FILTER = 678; PARTICULARLY_POIGNANT_PETAL = 679; ANTIQUE_AMULET = 680; CATHEDRAL_MEDALLION = 681; GOLD_BALLISTA_CHEVRON = 682; MYTHRIL_BALLISTA_CHEVRON = 683; SILVER_BALLISTA_CHEVRON = 684; BRONZE_BALLISTA_CHEVRON = 685; BLOODY_BALLISTA_CHEVRON = 686; ORANGE_BALLISTA_CHEVRON = 687; WHITE_BALLISTA_CHEVRON = 688; BLACK_BALLISTA_CHEVRON = 689; RED_BALLISTA_CHEVRON = 690; GREEN_BALLISTA_CHEVRON = 691; SPARKING_BALLISTA_CHEVRON = 692; EBON_BALLISTA_CHEVRON = 693; FURRY_BALLISTA_CHEVRON = 694; BROWN_BALLISTA_CHEVRON = 695; OCHRE_BALLISTA_CHEVRON = 696; JADE_BALLISTA_CHEVRON = 697; TRANSPARENT_BALLISTA_CHEVRON = 698; PURPLE_BALLISTA_CHEVRON = 699; RAINBOW_BALLISTA_CHEVRON = 700; LETTERS_FROM_ULMIA_AND_PRISHE = 701; PETRA_EATER_VOUCHER = 702; CATHOLICON_VOUCHER = 703; RED_OIL = 704; MARBLE_BRIDGE_COASTER = 705; LAMP_LIGHTERS_MEMBERSHIP_CARD = 706; SHAFT_GATE_OPERATING_DIAL = 707; MYSTERIOUS_AMULET = 708; MIRE_INCENSE = 709; BRAND_OF_DAWN = 710; BRAND_OF_TWILIGHT = 711; ORNAMENTED_SCROLL = 712; BETTER_HUMES_AND_MANNEQUINS = 713; PETRA_SHOVEL = 714; CALIGINOUS_BLADE = 715; TEAR_OF_ALTANA = 716; BALLISTA_BAND = 717; SHADED_CRUSE = 718; LETTER_FROM_SHIKAREE_X = 719; MONARCH_LINN_PATROL_PERMIT = 720; LETTER_FROM_SHIKAREE_Y = 721; LETTER_FROM_THE_MITHRAN_TRACKER = 722; COMMUNICATION_FROM_TZEE_XICU = 723; ORCISH_SEEKER_BATS = 724; VAULT_QUIPUS = 725; GOBLIN_RECOMMENDATION_LETTER = 726; COSTUME_KIT = 727; JAR_OF_REVERSION_DUST = 728; REMEDY_VOUCHER = 729; PANACEA_VOUCHER = 730; SMELLING_SALTS_VOUCHER = 731; VITRALLUM = 732; OPALESCENT_STONE = 733; COSMOCLEANSE = 734; OLD_WOMANS_PORTRAIT = 735; GLIMMERING_MICA = 736; MISTROOT = 737; LUNASCENT_LOG = 738; DYNAMIS_VALKURM_SLIVER = 739; DYNAMIS_BUBURIMU_SLIVER = 740; DYNAMIS_QUFIM_SLIVER = 741; DYNAMIS_TAVNAZIA_SLIVER = 742; RED_SENTINEL_BADGE = 743; BLUE_SENTINEL_BADGE = 744; GREEN_SENTINEL_BADGE = 745; WHITE_SENTINEL_BADGE = 746; EYE_OF_FLAMES = 747; EYE_OF_TREMORS = 748; EYE_OF_TIDES = 749; EYE_OF_GALES = 750; EYE_OF_FROST = 751; EYE_OF_STORMS = 752; RED_INVITATION_CARD = 753; BLUE_INVITATION_CARD = 754; GREEN_INVITATION_CARD = 755; WHITE_INVITATION_CARD = 756; HEALING_POWDER_VOUCHER = 757; BRENNER_SHOVEL = 758; BRENNER_BAND = 759; SILVER_SEA_FERRY_TICKET = 760; MOONLIGHT_ORE = 761; LEUJAOAM_ASSAULT_ORDERS = 762; MAMOOL_JA_ASSAULT_ORDERS = 763; LEBROS_ASSAULT_ORDERS = 764; PERIQIA_ASSAULT_ORDERS = 765; ILRUSI_ASSAULT_ORDERS = 766; DKHAAYAS_RESEARCH_JOURNAL = 767; ELECTROCELL = 768; ELECTROPOT = 769; ELECTROLOCOMOTIVE = 770; MARK_OF_ZAHAK = 771; VIAL_OF_LUMINOUS_WATER = 772; IMAGE_RECORDER = 773; CAST_METAL_PLATE = 774; SUPPLIES_PACKAGE = 775; RAINBOW_BERRY = 776; SAPPHIRE_BALLISTA_CHEVRON = 777; CORAL_BALLISTA_CHEVRON = 778; SILK_BALLISTA_CHEVRON = 779; PSC_WILDCAT_BADGE = 780; BOARDING_PERMIT = 781; RUNIC_PORTAL_USE_PERMIT = 782; PFC_WILDCAT_BADGE = 783; SP_WILDCAT_BADGE = 784; RAILLEFALS_LETTER = 785; EPHRAMADIAN_GOLD_COIN = 786; IMPERIAL_ARMY_ID_TAG = 787; RAILLEFALS_NOTE = 788; DARK_RIDER_HOOFPRINT = 789; BAG_OF_GOLD_PIECES = 790; FORGOTTEN_HEXAGUN = 791; PLASMA_OIL = 792; PLASMA_ROCK = 793; LC_WILDCAT_BADGE = 794; C_WILDCAT_BADGE = 795; POT_OF_TSETSEROONS_STEW = 796; ASSAULT_ARMBAND = 797; ANTIQUE_AUTOMATON = 798; RED_BELL = 799; BLUE_BELL = 800; MUSICAL_SCORE_1ST_PAGE = 801; MUSICAL_SCORE_2ND_PAGE = 802; MERROW_HOMUNCULUS = 803; LAMIA_HOMUNCULUS = 804; MUNAHDAS_PACKAGE = 805; WHITE_HANDKERCHIEF = 806; CONFIDENTIAL_IMPERIAL_ORDER = 807; SECRET_IMPERIAL_ORDER = 808; HANDKERCHIEF = 809; DIRTY_HANDKERCHIEF = 810; REPLAY_DEBUGGER = 811; ASTRAL_COMPASS = 812; VIAL_OF_SPECTRAL_SCENT = 813; EMPTY_TEST_TUBE_1 = 814; EMPTY_TEST_TUBE_2 = 815; EMPTY_TEST_TUBE_3 = 816; EMPTY_TEST_TUBE_4 = 817; EMPTY_TEST_TUBE_5 = 818; TEST_TUBE_1 = 819; TEST_TUBE_2 = 820; TEST_TUBE_3 = 821; TEST_TUBE_4 = 822; TEST_TUBE_5 = 823; QUARTZ_TRANSMITTER = 824; S_WILDCAT_BADGE = 825; SM_WILDCAT_BADGE = 826; CS_WILDCAT_BADGE = 827; CHUNK_OF_GLITTERING_ORE = 828; BRAND_OF_THE_SPRINGSERPENT = 829; BRAND_OF_THE_GALESERPENT = 830; BRAND_OF_THE_FLAMESERPENT = 831; BRAND_OF_THE_SKYSERPENT = 832; BRAND_OF_THE_STONESERPENT = 833; MAGUS_ORDER_SLIP = 834; SEALED_IMMORTAL_ENVELOPE = 835; STORY_OF_AN_IMPATIENT_CHOCOBO = 837; STORY_OF_A_CURIOUS_CHOCOBO = 838; STORY_OF_A_WORRISOME_CHOCOBO = 839; STORY_OF_A_YOUTHFUL_CHOCOBO = 840; STORY_OF_A_HAPPY_CHOCOBO = 841; MAMOOL_JA_MANDATE = 842; VALKENGS_MEMORY_CHIP = 843; TOGGLE_SWITCH = 844; LELEROONS_LETTER_GREEN = 845; LELEROONS_LETTER_BLUE = 846; LELEROONS_LETTER_RED = 847; LIFE_FLOAT = 848; WHEEL_LOCK_TRIGGER = 849; STORY_OF_A_DILIGENT_CHOCOBO = 850; PRAIRIE_CHOCOGRAPH = 851; BUSH_CHOCOGRAPH = 852; LETTER_FROM_BERNAHN = 853; REMNANTS_PERMIT = 854; LILAC_RIBBON = 855; COASTAL_CHOCOGRAPH = 856; DUNE_CHOCOGRAPH = 857; JUNGLE_CHOCOGRAPH = 858; DESERT_CHOCOGRAPH = 859; PERIQIA_ASSAULT_AREA_ENTRY_PERMIT = 860; WARRIORS_ARMOR_CLAIM_SLIP = 861; MELEE_ATTIRE_CLAIM_SLIP = 862; CLERICS_ATTIRE_CLAIM_SLIP = 863; SORCERERS_ATTIRE_CLAIM_SLIP = 864; DUELISTS_ARMOR_CLAIM_SLIP = 865; ASSASSINS_ATTIRE_CLAIM_SLIP = 866; VALOR_ARMOR_CLAIM_SLIP = 867; ABYSS_ARMOR_CLAIM_SLIP = 868; MONSTER_ARMOR_CLAIM_SLIP = 869; BARDS_ATTIRE_CLAIM_SLIP = 870; SCOUTS_ATTIRE_CLAIM_SLIP = 871; SAOTOME_ARMOR_CLAIM_SLIP = 872; KOGA_GARB_CLAIM_SLIP = 873; WYRM_ARMOR_CLAIM_SLIP = 874; SUMMONERS_ATTIRE_CLAIM_SLIP = 875; SCOURSHROOM = 876; PERCIPIENT_EYE = 877; NYZUL_ISLE_ASSAULT_ORDERS = 878; RUNIC_DISC = 879; RUNIC_KEY = 880; GYSAHL_MEDAL = 881; ROSSWEISSES_FEATHER = 882; GRIMGERDES_FEATHER = 883; SIEGRUNES_FEATHER = 884; HELMWIGES_FEATHER = 885; SCHWERTLEITES_FEATHER = 886; WALTRAUTES_FEATHER = 887; ORTLINDES_FEATHER = 888; GERHILDES_FEATHER = 889; BRUNHILDES_FEATHER = 890; MARK_OF_THE_EINHERJAR = 891; PHOTOPTICATOR = 892; LUMINIAN_DAGGER = 893; SL_WILDCAT_BADGE = 894; BIYAADAS_LETTER = 895; OFFICER_ACADEMY_MANUAL = 896; ALLIED_COUNCIL_SUMMONS = 897; NYZUL_ISLE_ROUTE = 898; MYTHRIL_MIRROR = 899; FL_WILDCAT_BADGE = 900; CHOCOBO_CIRCUIT_GRANDSTAND_PASS = 908; CAPTAIN_WILDCAT_BADGE = 909; PURE_WHITE_FEATHER = 910; STARDUST_PEBBLE = 911; LEFT_MAP_PIECE = 912; MIDDLE_MAP_PIECE = 913; RIGHT_MAP_PIECE = 914; SEQUINED_BALLISTA_CHEVRON = 915; VELVET_BALLISTA_CHEVRON = 916; BATTLE_RATIONS = 917; CLUMP_OF_ANIMAL_HAIR = 918; XHIFHUT = 919; WARNING_LETTER = 920; RED_RECOMMENDATION_LETTER = 921; BLUE_RECOMMENDATION_LETTER = 922; GREEN_RECOMMENDATION_LETTER = 923; BRONZE_RIBBON_OF_SERVICE = 924; BRASS_RIBBON_OF_SERVICE = 925; ALLIED_RIBBON_OF_BRAVERY = 926; ALLIED_RIBBON_OF_GLORY = 927; BRONZE_STAR = 928; STERLING_STAR = 929; MYTHRIL_STAR = 930; GOLDEN_STAR = 931; COPPER_EMBLEM_OF_SERVICE = 932; IRON_EMBLEM_OF_SERVICE = 933; STEELKNIGHT_EMBLEM = 934; HOLYKNIGHT_EMBLEM = 935; BRASS_WINGS_OF_SERVICE = 936; MYTHRIL_WINGS_OF_SERVICE = 937; WINGS_OF_INTEGRITY = 938; WINGS_OF_HONOR = 939; STARLIGHT_MEDAL = 940; MOONLIGHT_MEDAL = 941; DAWNLIGHT_MEDAL = 942; MEDAL_OF_ALTANA = 943; SLICED_POLE = 944; SUPPLY_ORDER = 945; GRIMOIRE = 946; ZONPAZIPPAS_ALLPURPOSE_PUTTY = 947; SCOOPDEDICATED_LINKPEARL = 948; FIREPOWER_CASE = 949; CHARRED_PROPELLER = 950; PIECE_OF_SHATTERED_LUMBER = 951; OXIDIZED_PLATE = 952; PIECE_OF_KIONITE = 953; RANPIMONPI_SPECIALTY = 954; CULINARY_KNIFE = 955; FIREBLOSSOM = 956; THE_HEALING_HERB = 957; SMALL_STARFRUIT = 958; INKY_BLACK_YAGUDO_FEATHER = 959; CAMPAIGN_SUPPLIES = 960; MINE_SHAFT_KEY = 961; THE_ESSENCE_OF_DANCE = 962; JUGNER_GATE_CRYSTAL = 963; PASHHOW_GATE_CRYSTAL = 964; MERIPHATAUD_GATE_CRYSTAL = 965; VUNKERL_HERB = 966; VUNKERL_HERB_MEMO = 967; EVIL_WARDING_SEAL = 968; ORNATE_PACKAGE = 969; SHEAF_OF_HANDMADE_INCENSE = 970; LEATHERBOUND_BOOK = 971; LYNX_PELT = 972; WYATTS_PROPOSAL = 973; FORT_KEY = 974; ULBRECHTS_SEALED_LETTER = 975; SCHULTS_SEALED_LETTER = 976; UNADDRESSED_SEALED_LETTER = 977; PORTING_MAGIC_TRANSCRIPT = 978; SAMPLE_OF_GRAUBERG_CHERT = 979; DROGAROGAN_BONEMEAL = 980; SLUG_MUCUS = 981; DJINN_EMBER = 982; RAFFLESIA_DREAMSPIT = 983; PEISTE_DUNG = 984; ULBRECHTS_MORTARBOARD = 985; BEASTMEN_CONFEDERATE_CRATE = 986; MILITARY_SCRIP = 987; SILVERMINE_KEY = 988; RED_PRIZE_BALLOON = 989; BLUE_PRIZE_BALLOON = 990; GREEN_PRIZE_BALLOON = 991; TRAVONCES_ESCORT_AWARD = 992; KENS_ESCORT_AWARD = 993; EMPTINESS_INVESTIGATION_NOTE = 994; TIGRIS_STONE = 995; DIAMOND_SEAL = 996; XICUS_ROSARY = 997; MAROON_SEAL = 998; APPLE_GREEN_SEAL = 999; CHARCOAL_GREY_SEAL = 1000; DEEP_PURPLE_SEAL = 1001; CHESTNUT_COLORED_SEAL = 1002; LILAC_COLORED_SEAL = 1003; CERISE_SEAL = 1004; SALMON_COLORED_SEAL = 1005; PURPLISH_GREY_SEAL = 1006; GOLD_COLORED_SEAL = 1007; COPPER_COLORED_SEAL = 1008; BRIGHT_BLUE_SEAL = 1009; PINE_GREEN_SEAL = 1010; AMBER_COLORED_SEAL = 1011; FALLOW_COLORED_SEAL = 1012; TAUPE_COLORED_SEAL = 1013; SIENNA_COLORED_SEAL = 1014; LAVENDER_COLORED_SEAL = 1015; SICKLEMOON_SALT = 1016; SILVER_SEA_SALT = 1017; CYAN_DEEP_SALT = 1018; ORCISH_WARMACHINE_BODY = 1019; PAPAROONS_SEALED_INVITATION = 1020; DATA_ANALYZER_AND_LOGGER_EX = 1021; MAYAKOV_SHOW_TICKET = 1022; SERPENTKING_ZAHAK_RELIEF = 1023; SAKURA_RACING_BADGE = 1024; SERPENTKING_ZAHAK_RELIEF_SHARD = 1025; IMPERIAL_LINEAGE_CHAPTER_I = 1026; IMPERIAL_LINEAGE_CHAPTER_II = 1027; IMPERIAL_LINEAGE_CHAPTER_III = 1028; IMPERIAL_LINEAGE_CHAPTER_IV = 1029; IMPERIAL_LINEAGE_CHAPTER_V = 1030; IMPERIAL_LINEAGE_CHAPTER_VI = 1031; IMPERIAL_LINEAGE_CHAPTER_VII = 1032; IMPERIAL_LINEAGE_CHAPTER_VIII = 1033; THE_WORDS_OF_DONHU_I = 1034; THE_WORDS_OF_DONHU_II = 1035; THE_WORDS_OF_DONHU_III = 1036; THE_WORDS_OF_DONHU_IV = 1037; THE_WORDS_OF_DONHU_V = 1038; THE_WORDS_OF_DONHU_VI = 1039; THE_WORDS_OF_DONHU_VII = 1040; THE_WORDS_OF_DONHU_VIII = 1041; HABALOS_ECLOGUE_VERSE_I = 1042; HABALOS_ECLOGUE_VERSE_II = 1043; HABALOS_ECLOGUE_VERSE_III = 1044; HABALOS_ECLOGUE_VERSE_IV = 1045; HABALOS_ECLOGUE_VERSE_V = 1046; HABALOS_ECLOGUE_VERSE_VI = 1047; HABALOS_ECLOGUE_VERSE_VII = 1048; HABALOS_ECLOGUE_VERSE_VIII = 1049; SIGNAL_FIRECRACKER = 1050; NUMBER_EIGHT_SHELTER_KEY = 1051; TORN_PATCHES_OF_LEATHER = 1052; REPAIRED_HANDBAG = 1053; MIRAGE_ATTIRE_CLAIM_SLIP = 1054; COMMODORE_ATTIRE_CLAIM_SLIP = 1055; PANTIN_ATTIRE_CLAIM_SLIP = 1056; ETOILE_ATTIRE_CLAIM_SLIP = 1057; ARGUTE_ATTIRE_CLAIM_SLIP = 1058; ARGENT_ATTIRE_CLAIM_SLIP = 1059; CONQUEST_PROMOTION_VOUCHER = 1060; CERNUNNOS_RESIN = 1061; COUNT_BORELS_LETTER = 1062; UNDERPASS_HATCH_KEY = 1063; BOTTLE_OF_TREANT_TONIC = 1064; TIMBER_SURVEY_CHECKLIST = 1065; SNOWTHEMED_GIFT_TOKEN = 1066; STARTHEMED_GIFT_TOKEN = 1067; BELLTHEMED_GIFT_TOKEN = 1068; FLARE_GRENADE = 1069; RONFAURE_MAPLE_SYRUP = 1070; LONGLIFE_BISCUITS = 1071; FLASK_OF_KINGDOM_WATER = 1072; BISCUIT_A_LA_RHOLONT = 1073; LETTER_TO_COUNT_AURCHIAT = 1074; LENGTH_OF_JUGNER_IVY = 1075; DARKFIRE_CINDER = 1076; FLOELIGHT_STONE = 1077; LIQUID_QUICKSILVER = 1078; GELID_SULFUR = 1079; BEASTBANE_BULLETS = 1080; GLEIPNIR = 1081; SCINTILLANT_STRAND = 1082; REFULGENT_STRAND = 1083; IRRADIANT_STRAND = 1084; BOWL_OF_BLAND_GOBLIN_SALAD = 1085; JUG_OF_GREASY_GOBLIN_JUICE = 1086; CHUNK_OF_SMOKED_GOBLIN_GRUB = 1087; SEEDSPALL_ROSEUM = 1088; SEEDSPALL_CAERULUM = 1089; SEEDSPALL_VIRIDIS = 1090; MARK_OF_SEED = 1091; AMICITIA_STONE = 1092; VERITAS_STONE = 1093; SAPIENTIA_STONE = 1094; SANCTITAS_STONE = 1095; FELICITAS_STONE = 1096; DIVITIA_STONE = 1097; STUDIUM_STONE = 1098; AMORIS_STONE = 1099; CARITAS_STONE = 1100; CONSTANTIA_STONE = 1101; SPEI_STONE = 1102; SALUS_STONE = 1103; OMNIS_STONE = 1104; CRIMSON_KEY = 1105; VIRIDIAN_KEY = 1106; AMBER_KEY = 1107; AZURE_KEY = 1108; IVORY_KEY = 1109; EBON_KEY = 1110; DELKFUTT_KEY = 1111; BEASTBANE_ARROWHEADS = 1112; RED_LABELED_CRATE = 1113; BLUE_LABELED_CRATE = 1114; GREEN_LABELED_CRATE = 1115; ELITE_TRAINING_INTRODUCTION = 1116; ELITE_TRAINING_CHAPTER_1 = 1117; ELITE_TRAINING_CHAPTER_2 = 1118; ELITE_TRAINING_CHAPTER_3 = 1119; ELITE_TRAINING_CHAPTER_4 = 1120; ELITE_TRAINING_CHAPTER_5 = 1121; ELITE_TRAINING_CHAPTER_6 = 1122; ELITE_TRAINING_CHAPTER_7 = 1123; UNADORNED_RING = 1124; MOG_KUPON_A_DBCD = 1125; MOG_KUPON_A_DXAR = 1126; PRISMATIC_KEY = 1127; SHADOW_BUG = 1128; WHITE_CORAL_KEY = 1129; BLUE_CORAL_KEY = 1130; PEACH_CORAL_KEY = 1131; BLACK_CORAL_KEY = 1132; RED_CORAL_KEY = 1133; ANGEL_SKIN_KEY = 1134; OXBLOOD_KEY = 1135; STURDY_METAL_STRIP = 1136; PIECE_OF_RUGGED_TREE_BARK = 1137; SAVORY_LAMB_ROAST = 1138; ORB_OF_SWORDS = 1139; ORB_OF_CUPS = 1140; ORB_OF_BATONS = 1141; ORB_OF_COINS = 1142; RIPE_STARFRUIT = 1143; MOLDY_WORMEATEN_CHEST = 1144; STONE_OF_SURYA = 1145; STONE_OF_CHANDRA = 1146; STONE_OF_MANGALA = 1147; STONE_OF_BUDHA = 1148; STONE_OF_BRIHASPATI = 1149; STONE_OF_SHUKRA = 1150; STONE_OF_SHANI = 1151; STONE_OF_RAHU = 1152; STONE_OF_KETU = 1153; TRIVIA_CHALLENGE_KUPON = 1154; GAUNTLET_CHALLENGE_KUPON = 1155; FESTIVAL_SOUVENIR_KUPON = 1156; POCKET_MOGBOMB = 1157; NAVARATNA_TALISMAN = 1158; MEGA_BONANZA_KUPON = 1159; AROMA_BUG = 1160; UMBRA_BUG = 1161; NORTHBOUND_PETITION = 1162; PONONOS_CHARM = 1163; DELICATE_WOOL_THREAD = 1164; DELICATE_LINEN_THREAD = 1165; DELICATE_COTTON_THREAD = 1166; ENCHANTED_WOOL_THREAD = 1167; ENCHANTED_LINEN_THREAD = 1168; ENCHANTED_COTTON_THREAD = 1169; WAX_SEAL = 1170; SACK_OF_VICTUALS = 1171; COMMANDERS_ENDORSEMENT = 1172; SUCCULENT_DRAGON_FRUIT = 1173; SHARD_OF_OPTISTONE = 1174; SHARD_OF_AURASTONE = 1175; SHARD_OF_ORASTONE = 1176; PROSPECTORS_PAN = 1177; CORKED_AMPOULE = 1178; AMPOULE_OF_GOLD_DUST = 1179; VIAL_OF_MILITARY_PRISM_POWDER = 1180; LANCE_FISH = 1181; PALADIN_LOBSTER = 1182; SCUTUM_CRAB = 1183; MOOGLE_KEY = 1184; BIRD_KEY = 1185; CACTUAR_KEY = 1186; BOMB_KEY = 1187; CHOCOBO_KEY = 1188; TONBERRY_KEY = 1189; BEHEMOTH_KEY = 1190; DOMINAS_SCARLET_SEAL = 1191; DOMINAS_CERULEAN_SEAL = 1192; DOMINAS_EMERALD_SEAL = 1193; DOMINAS_AMBER_SEAL = 1194; DOMINAS_VIOLET_SEAL = 1195; DOMINAS_AZURE_SEAL = 1196; SCARLET_COUNTERSEAL = 1197; CERULEAN_COUNTERSEAL = 1198; EMERALD_COUNTERSEAL = 1199; AMBER_COUNTERSEAL = 1200; VIOLET_COUNTERSEAL = 1201; AZURE_COUNTERSEAL = 1202; BLACK_BOOK = 1203; LUMINOUS_RED_FRAGMENT = 1204; LUMINOUS_BEIGE_FRAGMENT = 1205; LUMINOUS_GREEN_FRAGMENT = 1206; LUMINOUS_YELLOW_FRAGMENT = 1207; LUMINOUS_PURPLE_FRAGMENT = 1208; LUMINOUS_BLUE_FRAGMENT = 1209; FIRE_SAP_CRYSTAL = 1210; WATER_SAP_CRYSTAL = 1211; WIND_SAP_CRYSTAL = 1212; EARTH_SAP_CRYSTAL = 1213; LIGHTNING_SAP_CRYSTAL = 1214; ICE_SAP_CRYSTAL = 1215; LIGHT_SAP_CRYSTAL = 1216; DARK_SAP_CRYSTAL = 1217; TABLET_OF_HEXES_GREED = 1218; TABLET_OF_HEXES_ENVY = 1219; TABLET_OF_HEXES_MALICE = 1220; TABLET_OF_HEXES_DECEIT = 1221; TABLET_OF_HEXES_PRIDE = 1222; TABLET_OF_HEXES_BALE = 1223; TABLET_OF_HEXES_DESPAIR = 1224; TABLET_OF_HEXES_REGRET = 1225; TABLET_OF_HEXES_RAGE = 1226; TABLET_OF_HEXES_AGONY = 1227; TABLET_OF_HEXES_DOLOR = 1228; TABLET_OF_HEXES_RANCOR = 1229; TABLET_OF_HEXES_STRIFE = 1230; TABLET_OF_HEXES_PENURY = 1231; TABLET_OF_HEXES_BLIGHT = 1232; TABLET_OF_HEXES_DEATH = 1233; SYNERGY_CRUCIBLE = 1234; MOG_KUPON_AW_ABS = 1235; MOG_KUPON_AW_PAN = 1236; MAGELIGHT_SIGNAL_FLARE = 1237; ALCHEMICAL_SIGNAL_FLARE = 1238; DISTRESS_SIGNAL_FLARE = 1239; IMPERIAL_MISSIVE = 1240; SANDORIAN_APPROVAL_LETTER = 1241; BASTOKAN_APPROVAL_LETTER = 1242; WINDURSTIAN_APPROVAL_LETTER = 1243; JEUNOAN_APPROVAL_LETTER = 1244; PRESENT_FOR_MEGOMAK = 1245; LIGHTNING_CELL = 1246; MEGOMAKS_SHOPPING_LIST = 1247; WHISPER_OF_RADIANCE = 1248; TALISMAN_OF_THE_REBEL_GODS = 1249; MESSAGE_FROM_YOYOROON = 1250; WHISPER_OF_GLOOM = 1251; SPATIAL_PRESSURE_BAROMETER = 1252; CLEAR_ABYSSITE = 1253; COLORFUL_ABYSSITE = 1254; BLUE_ABYSSITE = 1255; ORANGE_ABYSSITE = 1256; BROWN_ABYSSITE = 1257; YELLOW_ABYSSITE = 1258; PURPLE_ABYSSITE = 1259; BLACK_ABYSSITE = 1260; MAGIAN_TRIAL_LOG = 1261; MOG_KUPON_A_LUM = 1262; TALISMAN_KEY = 1263; LETTER_FROM_HALVER = 1264; LETTER_FROM_NAJI = 1265; LETTER_FROM_ZUBABA = 1266; LETTER_FROM_MAAT = 1267; LETTER_FROM_DESPACHIAIRE = 1268; LETTER_FROM_JAKOH_WAHCONDALO = 1269; ZVAHL_PASSKEY = 1270; TRAVERSER_STONE1 = 1271; TRAVERSER_STONE2 = 1272; TRAVERSER_STONE3 = 1273; TRAVERSER_STONE4 = 1274; TRAVERSER_STONE5 = 1275; TRAVERSER_STONE6 = 1276; POET_GODS_KEY = 1277; ORCISH_INFILTRATION_KIT = 1278; ATMA_OF_THE_LION = 1279; ATMA_OF_THE_STOUT_ARM = 1280; ATMA_OF_THE_TWIN_CLAW = 1281; ATMA_OF_ALLURE = 1282; ATMA_OF_ETERNITY = 1283; ATMA_OF_THE_HEAVENS = 1284; ATMA_OF_THE_BAYING_MOON = 1285; ATMA_OF_THE_EBON_HOOF = 1286; ATMA_OF_TREMORS = 1287; ATMA_OF_THE_SAVAGE_TIGER = 1288; ATMA_OF_THE_VORACIOUS_VIOLET = 1289; ATMA_OF_CLOAK_AND_DAGGER = 1290; ATMA_OF_THE_STORMBIRD = 1291; ATMA_OF_THE_NOXIOUS_FANG = 1292; ATMA_OF_VICISSITUDE = 1293; ATMA_OF_THE_BEYOND = 1294; ATMA_OF_STORMBREATH = 1295; ATMA_OF_GALES = 1296; ATMA_OF_THRASHING_TENDRILS = 1297; ATMA_OF_THE_DRIFTER = 1298; ATMA_OF_THE_STRONGHOLD = 1299; ATMA_OF_THE_HARVESTER = 1300; ATMA_OF_DUNES = 1301; ATMA_OF_THE_COSMOS = 1302; ATMA_OF_THE_SIREN_SHADOW = 1303; ATMA_OF_THE_IMPALER = 1304; ATMA_OF_THE_ADAMANTINE = 1305; ATMA_OF_CALAMITY = 1306; ATMA_OF_THE_CLAW = 1307; ATMA_OF_BALEFUL_BONES = 1308; ATMA_OF_THE_CLAWED_BUTTERFLY = 1309; ATMA_OF_THE_DESERT_WORM = 1310; ATMA_OF_THE_UNDYING = 1311; ATMA_OF_THE_IMPREGNABLE_TOWER = 1312; ATMA_OF_THE_SMOLDERING_SKY = 1313; ATMA_OF_THE_DEMONIC_SKEWER = 1314; ATMA_OF_THE_GOLDEN_CLAW = 1315; ATMA_OF_THE_GLUTINOUS_OOZE = 1316; ATMA_OF_THE_LIGHTNING_BEAST = 1317; ATMA_OF_THE_NOXIOUS_BLOOM = 1318; ATMA_OF_THE_GNARLED_HORN = 1319; ATMA_OF_THE_STRANGLING_WIND = 1320; ATMA_OF_THE_DEEP_DEVOURER = 1321; ATMA_OF_THE_MOUNTED_CHAMPION = 1322; ATMA_OF_THE_RAZED_RUINS = 1323; ATMA_OF_THE_BLUDGEONING_BRUTE = 1324; ATMA_OF_THE_RAPID_REPTILIAN = 1325; ATMA_OF_THE_WINGED_ENIGMA = 1326; ATMA_OF_THE_CRADLE = 1327; ATMA_OF_THE_UNTOUCHED = 1328; ATMA_OF_THE_SANGUINE_SCYTHE = 1329; ATMA_OF_THE_TUSKED_TERROR = 1330; ATMA_OF_THE_MINIKIN_MONSTROSITY = 1331; ATMA_OF_THE_WOULD_BE_KING = 1332; ATMA_OF_THE_BLINDING_HORN = 1333; ATMA_OF_THE_DEMONIC_LASH = 1334; ATMA_OF_APPARITIONS = 1335; ATMA_OF_THE_SHIMMERING_SHELL = 1336; ATMA_OF_THE_MURKY_MIASMA = 1337; ATMA_OF_THE_AVARICIOUS_APE = 1338; ATMA_OF_THE_MERCILESS_MATRIARCH = 1339; ATMA_OF_THE_BROTHER_WOLF = 1340; ATMA_OF_THE_EARTH_WYRM = 1341; ATMA_OF_THE_ASCENDING_ONE = 1342; ATMA_OF_THE_SCORPION_QUEEN = 1343; ATMA_OF_A_THOUSAND_NEEDLES = 1344; ATMA_OF_THE_BURNING_EFFIGY = 1345; ATMA_OF_THE_SMITING_BLOW = 1346; ATMA_OF_THE_LONE_WOLF = 1347; ATMA_OF_THE_CRIMSON_SCALE = 1348; ATMA_OF_THE_SCARLET_WING = 1349; ATMA_OF_THE_RAISED_TAIL = 1350; ATMA_OF_THE_SAND_EMPEROR = 1351; ATMA_OF_THE_OMNIPOTENT = 1352; ATMA_OF_THE_WAR_LION = 1353; ATMA_OF_THE_FROZEN_FETTERS = 1354; ATMA_OF_THE_PLAGUEBRINGER = 1355; ATMA_OF_THE_SHRIEKING_ONE = 1356; ATMA_OF_THE_HOLY_MOUNTAIN = 1357; ATMA_OF_THE_LAKE_LURKER = 1358; ATMA_OF_THE_CRUSHING_CUDGEL = 1359; ATMA_OF_PURGATORY = 1360; ATMA_OF_BLIGHTED_BREATH = 1361; ATMA_OF_THE_PERSISTENT_PREDATOR = 1362; ATMA_OF_THE_STONE_GOD = 1363; ATMA_OF_THE_SUN_EATER = 1364; ATMA_OF_THE_DESPOT = 1365; ATMA_OF_THE_SOLITARY_ONE = 1366; ATMA_OF_THE_WINGED_GLOOM = 1367; ATMA_OF_THE_SEA_DAUGHTER = 1368; ATMA_OF_THE_HATEFUL_STREAM = 1369; ATMA_OF_THE_FOE_FLAYER = 1370; ATMA_OF_THE_ENDLESS_NIGHTMARE = 1371; ATMA_OF_THE_SUNDERING_SLASH = 1372; ATMA_OF_ENTWINED_SERPENTS = 1373; ATMA_OF_THE_HORNED_BEAST = 1374; ATMA_OF_AQUATIC_ARDOR = 1375; ATMA_OF_THE_FALLEN_ONE = 1376; ATMA_OF_FIRES_AND_FLARES = 1377; ATMA_OF_THE_APOCALYPSE = 1378; IVORY_ABYSSITE_OF_SOJOURN = 1379; SCARLET_ABYSSITE_OF_SOJOURN = 1380; JADE_ABYSSITE_OF_SOJOURN = 1381; SAPPHIRE_ABYSSITE_OF_SOJOURN = 1382; INDIGO_ABYSSITE_OF_SOJOURN = 1383; EMERALD_ABYSSITE_OF_SOJOURN = 1384; AZURE_ABYSSITE_OF_CELERITY = 1385; CRIMSON_ABYSSITE_OF_CELERITY = 1386; IVORY_ABYSSITE_OF_CELERITY = 1387; VIRIDIAN_ABYSSITE_OF_AVARICE = 1388; IVORY_ABYSSITE_OF_AVARICE = 1389; VERMILLION_ABYSSITE_OF_AVARICE = 1390; IVORY_ABYSSITE_OF_CONFLUENCE = 1391; CRIMSON_ABYSSITE_OF_CONFLUENCE = 1392; INDIGO_ABYSSITE_OF_CONFLUENCE = 1393; IVORY_ABYSSITE_OF_EXPERTISE = 1394; JADE_ABYSSITE_OF_EXPERTISE = 1395; EMERALD_ABYSSITE_OF_EXPERTISE = 1396; IVORY_ABYSSITE_OF_FORTUNE = 1397; SAPPHIRE_ABYSSITE_OF_FORTUNE = 1398; EMERALD_ABYSSITE_OF_FORTUNE = 1399; SCARLET_ABYSSITE_OF_KISMET = 1400; IVORY_ABYSSITE_OF_KISMET = 1401; VERMILLION_ABYSSITE_OF_KISMET = 1402; AZURE_ABYSSITE_OF_PROSPERITY = 1403; JADE_ABYSSITE_OF_PROSPERITY = 1404; IVORY_ABYSSITE_OF_PROSPERITY = 1405; VIRIDIAN_ABYSSITE_OF_DESTINY = 1406; CRIMSON_ABYSSITE_OF_DESTINY = 1407; IVORY_ABYSSITE_OF_DESTINY = 1408; IVORY_ABYSSITE_OF_ACUMEN = 1409; CRIMSON_ABYSSITE_OF_ACUMEN = 1410; EMERALD_ABYSSITE_OF_ACUMEN = 1411; SCARLET_ABYSSITE_OF_LENITY = 1412; AZURE_ABYSSITE_OF_LENITY = 1413; VIRIDIAN_ABYSSITE_OF_LENITY = 1414; JADE_ABYSSITE_OF_LENITY = 1415; SAPPHIRE_ABYSSITE_OF_LENITY = 1416; CRIMSON_ABYSSITE_OF_LENITY = 1417; VERMILLION_ABYSSITE_OF_LENITY = 1418; INDIGO_ABYSSITE_OF_LENITY = 1419; EMERALD_ABYSSITE_OF_LENITY = 1420; SCARLET_ABYSSITE_OF_PERSPICACITY = 1421; IVORY_ABYSSITE_OF_PERSPICACITY = 1422; VERM_ABYSSITE_OF_PERSPICACITY = 1423; AZURE_ABYSSITE_OF_THE_REAPER = 1424; IVORY_ABYSSITE_OF_THE_REAPER = 1425; INDIGO_ABYSSITE_OF_THE_REAPER = 1426; VIRIDIAN_ABYSSITE_OF_GUERDON = 1427; IVORY_ABYSSITE_OF_GUERDON = 1428; VERMILLION_ABYSSITE_OF_GUERDON = 1429; SCARLET_ABYSSITE_OF_FURTHERANCE = 1430; SAPPHIRE_ABYSSITE_OF_FURTHERANCE = 1431; IVORY_ABYSSITE_OF_FURTHERANCE = 1432; AZURE_ABYSSITE_OF_MERIT = 1433; VIRIDIAN_ABYSSITE_OF_MERIT = 1434; JADE_ABYSSITE_OF_MERIT = 1435; SAPPHIRE_ABYSSITE_OF_MERIT = 1436; IVORY_ABYSSITE_OF_MERIT = 1437; INDIGO_ABYSSITE_OF_MERIT = 1438; LUNAR_ABYSSITE1 = 1439; LUNAR_ABYSSITE2 = 1440; LUNAR_ABYSSITE3 = 1441; ABYSSITE_OF_DISCERNMENT = 1442; ABYSSITE_OF_THE_COSMOS = 1443; WHITE_STRATUM_ABYSSITE = 1444; WHITE_STRATUM_ABYSSITE_II = 1445; WHITE_STRATUM_ABYSSITE_III = 1446; ASHEN_STRATUM_ABYSSITE = 1447; ASHEN_STRATUM_ABYSSITE_II = 1448; ASHEN_STRATUM_ABYSSITE_III = 1449; WHITE_STRATUM_ABYSSITE_IV = 1450; WHITE_STRATUM_ABYSSITE_V = 1451; WHITE_STRATUM_ABYSSITE_VI = 1452; LEGION_TOME_PAGE_MAXIMUS = 1453; LEGION_MEDAL_AN = 1454; LEGION_MEDAL_KI = 1455; LEGION_MEDAL_IM = 1456; LEGION_MEDAL_MURU = 1457; LEGION_TOME_PAGE_MINIMUS = 1458; FRAGRANT_TREANT_PETAL = 1459; FETID_RAFFLESIA_STALK = 1460; DECAYING_MORBOL_TOOTH = 1461; TURBID_SLIME_OIL = 1462; VENOMOUS_PEISTE_CLAW = 1463; TATTERED_HIPPOGRYPH_WING = 1464; CRACKED_WIVRE_HORN = 1465; MUCID_AHRIMAN_EYEBALL = 1466; TWISTED_TONBERRY_CROWN = 1467; VEINOUS_HECTEYES_EYELID = 1468; TORN_BAT_WING = 1469; GORY_SCORPION_CLAW = 1470; MOSSY_ADAMANTOISE_SHELL = 1471; FAT_LINED_COCKATRICE_SKIN = 1472; SODDEN_SANDWORM_HUSK = 1473; LUXURIANT_MANTICORE_MANE = 1474; STICKY_GNAT_WING = 1475; OVERGROWN_MANDRAGORA_FLOWER = 1476; CHIPPED_SANDWORM_TOOTH = 1477; MARBLED_MUTTON_CHOP = 1478; BLOODIED_SABER_TOOTH = 1479; BLOOD_SMEARED_GIGAS_HELM = 1480; GLITTERING_PIXIE_CHOKER = 1481; DENTED_GIGAS_SHIELD = 1482; WARPED_GIGAS_ARMBAND = 1483; SEVERED_GIGAS_COLLAR = 1484; PELLUCID_FLY_EYE = 1485; SHIMMERING_PIXIE_PINION = 1486; SMOLDERING_CRAB_SHELL = 1487; VENOMOUS_WAMOURA_FEELER = 1488; BULBOUS_CRAWLER_COCOON = 1489; DISTENDED_CHIGOE_ABDOMEN = 1490; MUCID_WORM_SEGMENT = 1491; SHRIVELED_HECTEYES_STALK = 1492; BLOTCHED_DOOMED_TONGUE = 1493; CRACKED_SKELETON_CLAVICLE = 1494; WRITHING_GHOST_FINGER = 1495; RUSTED_HOUND_COLLAR = 1496; HOLLOW_DRAGON_EYE = 1497; BLOODSTAINED_BUGARD_FANG = 1498; GNARLED_LIZARD_NAIL = 1499; MOLTED_PEISTE_SKIN = 1500; JAGGED_APKALLU_BEAK = 1501; CLIPPED_BIRD_WING = 1502; BLOODIED_BAT_FUR = 1503; GLISTENING_OROBON_LIVER = 1504; DOFFED_POROGGO_HAT = 1505; SCALDING_IRONCLAD_SPIKE = 1506; BLAZING_CLUSTER_SOUL = 1507; INGROWN_TAURUS_NAIL = 1508; OSSIFIED_GARGOUILLE_HAND = 1509; IMBRUED_VAMPYR_FANG = 1510; GLOSSY_SEA_MONK_SUCKER = 1511; SHIMMERING_PUGIL_SCALE = 1512; DECAYED_DVERGR_TOOTH = 1513; PULSATING_SOULFLAYER_BEARD = 1514; CHIPPED_IMPS_OLIFANT = 1515; WARPED_SMILODON_CHOKER = 1516; MALODOROUS_MARID_FUR = 1517; BROKEN_IRON_GIANT_SPIKE = 1518; RUSTED_CHARIOT_GEAR = 1519; STEAMING_CERBERUS_TONGUE = 1520; BLOODIED_DRAGON_EAR = 1521; RESPLENDENT_ROC_QUILL = 1522; WARPED_IRON_GIANT_NAIL = 1523; DENTED_CHARIOT_SHIELD = 1524; TORN_KHIMAIRA_WING = 1525; BEGRIMED_DRAGON_HIDE = 1526; DECAYING_DIREMITE_FANG = 1527; SHATTERED_IRON_GIANT_CHAIN = 1528; WARPED_CHARIOT_PLATE = 1529; VENOMOUS_HYDRA_FANG = 1530; VACANT_BUGARD_EYE = 1531; VARIEGATED_URAGNITE_SHELL = 1532; BATTLE_TROPHY_1ST_ECHELON = 1533; BATTLE_TROPHY_2ND_ECHELON = 1534; BATTLE_TROPHY_3RD_ECHELON = 1535; BATTLE_TROPHY_4TH_ECHELON = 1536; BATTLE_TROPHY_5TH_ECHELON = 1537; CRIMSON_TRAVERSER_STONE = 1538; VOIDSTONE1 = 1539; VOIDSTONE2 = 1540; VOIDSTONE3 = 1541; VOIDSTONE4 = 1542; VOIDSTONE5 = 1543; VOIDSTONE6 = 1544; CRIMSON_GRANULES_OF_TIME = 1545; AZURE_GRANULES_OF_TIME = 1546; AMBER_GRANULES_OF_TIME = 1547; ALABASTER_GRANULES_OF_TIME = 1548; OBSIDIAN_GRANULES_OF_TIME = 1549; PRISMATIC_HOURGLASS = 1550; MOG_KUPON_W_R90 = 1551; MOG_KUPON_W_M90 = 1552; MOG_KUPON_W_E90 = 1553; MOG_KUPON_A_E2 = 1554; MOG_KUPON_I_SEAL = 1555; BEGUILING_PETRIFACT = 1556; SEDUCTIVE_PETRIFACT = 1557; MADDENING_PETRIFACT = 1558; VAT_OF_MARTELLO_FUEL = 1559; FUEL_RESERVOIR = 1560; EMPTY_FUEL_VAT = 1561; CRACKED_FUEL_RESERVOIR = 1562; VIAL_OF_LAMBENT_POTION = 1563; CLEAR_DEMILUNE_ABYSSITE = 1564; COLORFUL_DEMILUNE_ABYSSITE = 1565; SCARLET_DEMILUNE_ABYSSITE = 1566; AZURE_DEMILUNE_ABYSSITE = 1567; VIRIDIAN_DEMILUNE_ABYSSITE = 1568; ANTI_ABYSSEAN_GRENADE_01 = 1569; ANTI_ABYSSEAN_GRENADE_02 = 1570; ANTI_ABYSSEAN_GRENADE_03 = 1571; RAINBOW_PEARL = 1572; CHIPPED_WIND_CLUSTER = 1573; PIECE_OF_DRIED_EBONY_LUMBER = 1574; CAPTAIN_RASHIDS_LINKPEARL = 1575; CAPTAIN_ARGUSS_LINKPEARL = 1576; CAPTAIN_HELGAS_LINKPEARL = 1577; SEAL_OF_THE_RESISTANCE = 1578; SUNBEAM_FRAGMENT = 1579; LUGARHOOS_EYEBALL = 1580; VIAL_OF_PURIFICATION_AGENT_BLK = 1581; VIAL_OF_PURIFICATION_AGENT_BRZ = 1582; VIAL_OF_PURIFICATION_AGENT_SLV = 1583; VIAL_OF_PURIFICATION_AGENT_GLD = 1584; BLACK_LABELED_VIAL = 1585; BRONZE_LABELED_VIAL = 1586; SILVER_LABELED_VIAL = 1587; GOLD_LABELED_VIAL = 1588; RAINBOW_COLORED_LINKPEARL = 1589; GREY_ABYSSITE = 1590; RIPE_STARFRUIT_ABYSSEA = 1591; VIAL_OF_FLOWER_WOWER_FERTILIZER = 1592; TAHRONGI_TREE_NUT = 1593; BUCKET_OF_COMPOUND_COMPOST = 1594; CUP_OF_TAHRONGI_CACTUS_WATER = 1595; HASTILY_SCRAWLED_POSTER = 1596; BLOODIED_ARROW = 1597; CRIMSON_BLOODSTONE = 1598; KUPOFRIEDS_MEDALLION = 1599; PINCH_OF_MOIST_DANGRUF_SULFUR = 1600; NAJIS_GAUGER_PLATE = 1601; NAJIS_LINKPEARL = 1602; POT_OF_MARTIAL_RELISH = 1603; THIERRIDES_BEAN_CREATION = 1604; TINY_MEMORY_FRAGMENT1 = 1605; LARGE_MEMORY_FRAGMENT1 = 1606; FEY_STONE = 1607; LARGE_MEMORY_FRAGMENT2 = 1608; TORN_RECIPE_PAGE = 1609; MINERAL_GAUGE_FOR_DUMMIES = 1610; TUBE_OF_ALCHEMICAL_FERTILIZER = 1611; LARGE_MEMORY_FRAGMENT3 = 1612; LARGE_MEMORY_FRAGMENT4 = 1613; PULSE_MARTELLO_REPAIR_PACK = 1614; CLONE_WARD_REINFORCEMENT_PACK = 1615; PACK_OF_OUTPOST_REPAIR_TOOLS = 1616; PARRADAMO_SUPPLY_PACK1 = 1617; PARRADAMO_SUPPLY_PACK2 = 1618; PARRADAMO_SUPPLY_PACK3 = 1619; PARRADAMO_SUPPLY_PACK4 = 1620; PARRADAMO_SUPPLY_PACK5 = 1621; GASPONIA_STAMEN = 1622; ROCKHOPPER = 1623; PHIAL_OF_COUNTERAGENT = 1624; DAMAGED_STEWPOT = 1625; NARURUS_STEWPOT = 1626; MAGICKED_HEMPEN_SACK = 1627; MAGICKED_FLAXEN_SACK = 1628; PARALYSIS_TRAP_FLUID = 1629; PARALYSIS_TRAP_FLUID_BOTTLE = 1630; WEAKENING_TRAP_FLUID = 1631; WEAKENING_TRAP_FLUID_BOTTLE = 1632; IRON_EATERS_PEARLSACK = 1633; MEDICAL_SUPPLY_CHEST = 1635; WOODWORKERS_BELT = 1636; ESPIONAGE_PEARLSACK = 1637; CHIPPED_LINKSHELL = 1638; GRIMY_LINKSHELL = 1639; CRACKED_LINKSHELL = 1640; POCKET_SUPPLY_PACK = 1641; STANDARD_SUPPLY_PACK = 1642; HEFTY_SUPPLY_PACK = 1643; PACK_OF_MOLTEN_SLAG = 1644; LETTER_OF_RECEIPT = 1645; SMUDGED_LETTER = 1646; YELLOW_LINKPEARL = 1647; JESTERS_HAT = 1648; JADE_DEMILUNE_ABYSSITE = 1649; SAPPHIRE_DEMILUNE_ABYSSITE = 1650; CRIMSON_DEMILUNE_ABYSSITE = 1651; EMERALD_DEMILUNE_ABYSSITE = 1652; VERMILLION_DEMILUNE_ABYSSITE = 1653; INDIGO_DEMILUNE_ABYSSITE = 1654; ATMA_OF_THE_HEIR = 1655; ATMA_OF_THE_HERO = 1656; ATMA_OF_THE_FULL_MOON = 1657; ATMA_OF_ILLUSIONS = 1658; ATMA_OF_THE_BANISHER = 1659; ATMA_OF_THE_SELLSWORD = 1660; ATMA_OF_A_FUTURE_FABULOUS = 1661; ATMA_OF_CAMARADERIE = 1662; ATMA_OF_THE_TRUTHSEEKER = 1663; ATMA_OF_THE_AZURE_SKY = 1664; ATMA_OF_ECHOES = 1665; ATMA_OF_DREAD = 1666; ATMA_OF_AMBITION = 1667; ATMA_OF_THE_BEAST_KING = 1668; ATMA_OF_THE_KIRIN = 1669; ATMA_OF_HELLS_GUARDIAN = 1670; ATMA_OF_LUMINOUS_WINGS = 1671; ATMA_OF_THE_DRAGON_RIDER = 1672; ATMA_OF_THE_IMPENETRABLE = 1673; ATMA_OF_ALPHA_AND_OMEGA = 1674; ATMA_OF_THE_ULTIMATE = 1675; ATMA_OF_THE_HYBRID_BEAST = 1676; ATMA_OF_THE_DARK_DEPTHS = 1677; ATMA_OF_THE_ZENITH = 1678; ATMA_OF_PERFECT_ATTENDANCE = 1679; ATMA_OF_THE_RESCUER = 1680; ATMA_OF_NIGHTMARES = 1681; ATMA_OF_THE_EINHERJAR = 1682; ATMA_OF_THE_ILLUMINATOR = 1683; ATMA_OF_THE_BUSHIN = 1684; ATMA_OF_THE_ACE_ANGLER = 1685; ATMA_OF_THE_MASTER_CRAFTER = 1686; ATMA_OF_INGENUITY = 1687; ATMA_OF_THE_GRIFFONS_CLAW = 1688; ATMA_OF_THE_FETCHING_FOOTPAD = 1689; ATMA_OF_UNDYING_LOYALTY = 1690; ATMA_OF_THE_ROYAL_LINEAGE = 1691; ATMA_OF_THE_SHATTERING_STAR = 1692; ATMA_OF_THE_COBRA_COMMANDER = 1693; ATMA_OF_ROARING_LAUGHTER = 1694; ATMA_OF_THE_DARK_BLADE = 1695; ATMA_OF_THE_DUCAL_GUARD = 1696; ATMA_OF_HARMONY = 1697; ATMA_OF_REVELATIONS = 1698; ATMA_OF_THE_SAVIOR = 1699; TINY_MEMORY_FRAGMENT2 = 1700; TINY_MEMORY_FRAGMENT3 = 1701; EX_01_MARTELLO_CORE = 1702; EX_02_MARTELLO_CORE = 1703; EX_03_MARTELLO_CORE = 1704; EX_04_MARTELLO_CORE = 1705; EX_05_MARTELLO_CORE = 1706; EX_06_MARTELLO_CORE = 1707; EX_07_MARTELLO_CORE = 1708; MOG_KUPON_W_E85 = 1709; MOG_KUPON_A_RJOB = 1710; SILVER_POCKET_WATCH = 1711; ELEGANT_GEMSTONE = 1712; WIVRE_EGG1 = 1713; WIVRE_EGG2 = 1714; WIVRE_EGG3 = 1715; TORCH_COAL = 1716; SUBNIVEAL_MINES = 1717; PIECE_OF_SODDEN_OAK_LUMBER = 1718; SODDEN_LINEN_CLOTH = 1719; DHORME_KHIMAIRAS_MANE = 1720; IMPERIAL_PEARL = 1721; RONFAURE_DAWNDROP = 1722; LA_VAULE_DAWNDROP = 1723; JUGNER_DAWNDROP = 1724; BEAUCEDINE_DAWNDROP = 1725; XARCABARD_DAWNDROP = 1726; THRONE_ROOM_DAWNDROP = 1727; WALK_OF_ECHOES_DAWNDROP = 1728; SANDORIA_DAWNDROP = 1729; BOTTLED_PUNCH_BUG = 1730; PRIMAL_GLOW = 1731; MOONSHADE_EARRING = 1732; PINCH_OF_PIXIE_DUST = 1733; WEDDING_INVITATION = 1734; SNOLL_REFLECTOR = 1735; FROSTED_SNOLL_REFLECTOR = 1736; EXPERIMENT_CHEAT_SHEET = 1737; JOB_GESTURE_WARRIOR = 1738; JOB_GESTURE_MONK = 1739; JOB_GESTURE_WHITE_MAGE = 1740; JOB_GESTURE_BLACK_MAGE = 1741; JOB_GESTURE_RED_MAGE = 1742; JOB_GESTURE_THIEF = 1743; JOB_GESTURE_PALADIN = 1744; JOB_GESTURE_DARK_KNIGHT = 1745; JOB_GESTURE_BEASTMASTER = 1746; JOB_GESTURE_BARD = 1747; JOB_GESTURE_RANGER = 1748; JOB_GESTURE_SAMURAI = 1749; JOB_GESTURE_NINJA = 1750; JOB_GESTURE_DRAGOON = 1751; JOB_GESTURE_SUMMONER = 1752; JOB_GESTURE_BLUE_MAGE = 1753; JOB_GESTURE_CORSAIR = 1754; JOB_GESTURE_PUPPETMASTER = 1755; JOB_GESTURE_DANCER = 1756; JOB_GESTURE_SCHOLAR = 1757; FROSTBLOOM1 = 1758; FROSTBLOOM2 = 1759; FROSTBLOOM3 = 1760; MOON_PENDANT = 1761; WYVERN_EGG = 1762; WYVERN_EGG_SHELL = 1763; WAUGYLS_CLAW = 1764; BOTTLE_OF_MILITARY_INK = 1765; MILITARY_INK_PACKAGE = 1766; MAGIAN_LEARNERS_LOG = 1767; MAGIAN_MOOGLEHOOD_MISSIVE1 = 1768; MAGIAN_MOOGLEHOOD_MISSIVE2 = 1769; MAGIAN_MOOGLEHOOD_MISSIVE3 = 1770; MAGIAN_MOOGLEHOOD_MISSIVE4 = 1771; MAGIAN_MOOGLEHOOD_MISSIVE5 = 1772; MAGIAN_MOOGLEHOOD_MISSIVE6 = 1773; PERIAPT_OF_EMERGENCE1 = 1774; PERIAPT_OF_EMERGENCE2 = 1775; PERIAPT_OF_EMERGENCE3 = 1776; PERIAPT_OF_GUIDANCE = 1777; PERIAPT_OF_PERCIPIENCE = 1778; VIVID_PERIAPT_OF_CONCORD = 1779; DUSKY_PERIAPT_OF_CONCORD = 1780; VIVID_PERIAPT_OF_CATALYSIS = 1781; DUSKY_PERIAPT_OF_CATALYSIS = 1782; VIVID_PERIAPT_OF_EXPLORATION = 1783; DUSKY_PERIAPT_OF_EXPLORATION = 1784; VIVID_PERIAPT_OF_FRONTIERS = 1785; DUSKY_PERIAPT_OF_FRONTIERS = 1786; NEUTRAL_PERIAPT_OF_FRONTIERS = 1787; VIVID_PERIAPT_OF_CONCENTRATION = 1788; DUSKY_PERIAPT_OF_CONCENTRATION = 1789; VIVID_PERIAPT_OF_GLORY = 1790; DUSKY_PERIAPT_OF_GLORY = 1791; VIVID_PERIAPT_OF_FOCUS = 1792; DUSKY_PERIAPT_OF_FOCUS = 1793; VIVID_PERIAPT_OF_INTENSITY = 1794; DUSKY_PERIAPT_OF_INTENSITY = 1795; VIVID_PERIAPT_OF_READINESS = 1796; DUSKY_PERIAPT_OF_READINESS = 1797; VIVID_PERIAPT_OF_ADAPTABILITY = 1798; DUSKY_PERIAPT_OF_ADAPTABILITY = 1799; VIVID_PERIAPT_OF_VIGILANCE = 1800; DUSKY_PERIAPT_OF_VIGILANCE = 1801; VIVID_PERIAPT_OF_PRUDENCE = 1802; DUSKY_PERIAPT_OF_PRUDENCE = 1803; PERIAPT_OF_RECOMPENSE = 1804; VOID_CLUSTER = 1805; ATMACITE_OF_DEVOTION = 1806; ATMACITE_OF_PERSISTENCE = 1807; ATMACITE_OF_EMINENCE = 1808; ATMACITE_OF_ONSLAUGHT = 1809; ATMACITE_OF_INCURSION = 1810; ATMACITE_OF_ENTICEMENT = 1811; ATMACITE_OF_DESTRUCTION = 1812; ATMACITE_OF_TEMPERANCE = 1813; ATMACITE_OF_DISCIPLINE = 1814; ATMACITE_OF_COERCION = 1815; ATMACITE_OF_FINESSE = 1816; ATMACITE_OF_LATITUDE = 1817; ATMACITE_OF_MYSTICISM = 1818; ATMACITE_OF_RAPIDITY = 1819; ATMACITE_OF_PREPAREDNESS = 1820; ATMACITE_OF_DELUGES = 1821; ATMACITE_OF_UNITY = 1822; ATMACITE_OF_EXHORTATION = 1823; ATMACITE_OF_SKYBLAZE = 1824; ATMACITE_OF_THE_SLAYER = 1825; ATMACITE_OF_THE_ADAMANT = 1826; ATMACITE_OF_THE_VALIANT = 1827; ATMACITE_OF_THE_SHREWD = 1828; ATMACITE_OF_THE_VANGUARD = 1829; ATMACITE_OF_ASSAILMENT = 1830; ATMACITE_OF_CATAPHRACT = 1831; ATMACITE_OF_THE_PARAPET = 1832; ATMACITE_OF_IMPERIUM = 1833; ATMACITE_OF_THE_SOLIPSIST = 1834; ATMACITE_OF_PROVENANCE = 1835; ATMACITE_OF_DARK_DESIGNS = 1836; ATMACITE_OF_THE_FORAGER = 1837; ATMACITE_OF_GLACIERS = 1838; ATMACITE_OF_AFFINITY = 1839; ATMACITE_OF_THE_DEPTHS = 1840; ATMACITE_OF_THE_ASSASSIN = 1841; ATMACITE_OF_APLOMB = 1842; ATMACITE_OF_THE_TROPICS = 1843; ATMACITE_OF_CURSES = 1844; ATMACITE_OF_PRESERVATION = 1845; POUCH_OF_WEIGHTED_STONES = 1846; GOSSAMER_BALLISTA_CHEVRON = 1847; STEEL_BALLISTA_CHEVRON = 1848; PERIAPT_OF_SAPIENCE = 1854; PERIAPT_OF_CLARITY = 1855; MAP_OF_AL_ZAHBI = 1856; MAP_OF_NASHMAU = 1857; MAP_OF_WAJAOM_WOODLANDS = 1858; MAP_OF_CAEDARVA_MIRE = 1859; MAP_OF_MOUNT_ZHAYOLM = 1860; MAP_OF_AYDEEWA_SUBTERRANE = 1861; MAP_OF_MAMOOK = 1862; MAP_OF_HALVUNG = 1863; MAP_OF_ARRAPAGO_REEF = 1864; MAP_OF_ALZADAAL_RUINS = 1865; MAP_OF_LEUJAOAM_SANCTUM = 1866; MAP_OF_THE_TRAINING_GROUNDS = 1867; MAP_OF_LEBROS_CAVERN = 1868; MAP_OF_ILRUSI_ATOLL = 1869; MAP_OF_PERIQIA = 1870; MAP_OF_NYZUL_ISLE = 1871; MAP_OF_THE_CHOCOBO_CIRCUIT = 1872; MAP_OF_THE_COLOSSEUM = 1873; MAP_OF_BHAFLAU_THICKETS = 1874; MAP_OF_ZHAYOLM_REMNANTS = 1875; MAP_OF_ARRAPAGO_REMNANTS = 1876; MAP_OF_BHAFLAU_REMNANTS = 1877; MAP_OF_SILVER_SEA_REMNANTS = 1878; MAP_OF_VUNKERL_INLET = 1879; MAP_OF_EVERBLOOM_HOLLOW = 1880; MAP_OF_GRAUBERG = 1881; MAP_OF_RUHOTZ_SILVERMINES = 1882; MAP_OF_FORT_KARUGONARUGO = 1883; MAP_OF_GHOYUS_REVERIE = 1884; MAP_OF_ABYSSEA_LA_THEINE = 1885; MAP_OF_ABYSSEA_KONSCHTAT = 1886; MAP_OF_ABYSSEA_TAHRONGI = 1887; MAP_OF_ABYSSEA_ATTOHWA = 1888; MAP_OF_ABYSSEA_MISAREAUX = 1889; MAP_OF_ABYSSEA_VUNKERL = 1890; MAP_OF_ABYSSEA_ALTEPA = 1891; MAP_OF_ABYSSEA_ULEGUERAND = 1892; MAP_OF_ABYSSEA_GRAUBERG = 1893; MAP_OF_DYNAMIS_SANDORIA = 1894; MAP_OF_DYNAMIS_BASTOK = 1895; MAP_OF_DYNAMIS_WINDURST = 1896; MAP_OF_DYNAMIS_JEUNO = 1897; MAP_OF_DYNAMIS_BEAUCEDINE = 1898; MAP_OF_DYNAMIS_XARCABARD = 1899; MAP_OF_DYNAMIS_VALKURM = 1900; MAP_OF_DYNAMIS_BUBURIMU = 1901; MAP_OF_DYNAMIS_QUFIM = 1902; MAP_OF_DYNAMIS_TAVNAZIA = 1903; MAP_OF_ADOULIN = 1904; MAP_OF_RALA_WATERWAYS = 1905; MAP_OF_YAHSE_HUNTING_GROUNDS = 1906; MAP_OF_CEIZAK_BATTLEGROUNDS = 1907; MAP_OF_FORET_DE_HENNETIEL = 1908; MAP_OF_YORCIA_WEALD = 1909; MAP_OF_MORIMAR_BASALT_FIELDS = 1910; MAP_OF_MARJAMI_RAVINE = 1911; MAP_OF_KAMIHR_DRIFTS = 1912; MAP_OF_SIH_GATES = 1913; MAP_OF_MOH_GATES = 1914; MAP_OF_CIRDAS_CAVERNS = 1915; MAP_OF_DHO_GATES = 1916; MAP_OF_WOH_GATES = 1917; MAP_OF_OUTER_RAKAZNAR = 1918; IRON_CHAINMAIL_CLAIM_SLIP = 1920; SHADE_HARNESS_CLAIM_SLIP = 1921; BRASS_SCALE_MAIL_CLAIM_SLIP = 1922; WOOL_ROBE_CLAIM_SLIP = 1923; EISENPLATTE_ARMOR_CLAIM_SLIP = 1924; SOIL_GI_CLAIM_SLIP = 1925; SEERS_TUNIC_CLAIM_SLIP = 1926; STUDDED_ARMOR_CLAIM_SLIP = 1927; CENTURION_SCALE_MAIL_CLAIM_SLIP = 1928; MRCCPT_DOUBLET_CLAIM_SLIP = 1929; GARISH_TUNIC_CLAIM_SLIP = 1930; NOCT_DOUBLET_CLAIM_SLIP = 1931; CUSTOM_ARMOR_MALE_CLAIM_SLIP = 1932; CUSTOM_ARMOR_FEMALE_CLAIM_SLIP = 1933; MAGNA_ARMOR_MALE_CLAIM_SLIP = 1934; MAGNA_ARMOR_FEMALE_CLAIM_SLIP = 1935; WONDER_ARMOR_CLAIM_SLIP = 1936; SAVAGE_ARMOR_CLAIM_SLIP = 1937; ELDER_ARMOR_CLAIM_SLIP = 1938; LINEN_CLOAK_CLAIM_SLIP = 1939; PADDED_ARMOR_CLAIM_SLIP = 1940; SILVER_CHAINMAIL_CLAIM_SLIP = 1941; GAMBISON_CLAIM_SLIP = 1942; IRON_SCALE_ARMOR_CLAIM_SLIP = 1943; CUIR_ARMOR_CLAIM_SLIP = 1944; VELVET_ROBE_CLAIM_SLIP = 1945; OPALINE_DRESS_CLAIM_SLIP = 1946; RYLSQR_CHAINMAIL_CLAIM_SLIP = 1947; PLATE_ARMOR_CLAIM_SLIP = 1948; COMBAT_CASTERS_CLOAK_CLAIM_SLIP = 1949; ALUMINE_HAUBERT_CLAIM_SLIP = 1950; CARAPACE_HARNESS_CLAIM_SLIP = 1951; BANDED_MAIL_CLAIM_SLIP = 1952; HARA_ATE_CLAIM_SLIP = 1953; RAPTOR_ARMOR_CLAIM_SLIP = 1954; STEEL_SCALE_CLAIM_SLIP = 1955; WOOL_GAMBISON_CLAIM_SLIP = 1956; SHINOBI_GI_CLAIM_SLIP = 1957; IRNMSK_CUIRASS_CLAIM_SLIP = 1958; TCTMGC_CLOAK_CLAIM_SLIP = 1959; WHITE_CLOAK_CLAIM_SLIP = 1960; AUSTERE_ROBE_CLAIM_SLIP = 1961; MYTHRIL_PLATE_ARMOR_CLAIM_SLIP = 1962; CROW_JUPON_CLAIM_SLIP = 1963; MAGUS_ATTIRE_CLAIM_SLIP = 1964; CORSAIRS_ATTIRE_CLAIM_SLIP = 1965; PUPPETRY_ATTIRE_CLAIM_SLIP = 1966; DANCERS_ATTIRE_CLAIM_SLIP = 1967; DANCERS_ATTIRE_CLAIM_SLIP = 1968; SCHOLARS_ATTIRE_CLAIM_SLIP = 1969; AMIR_ARMOR_CLAIM_SLIP = 1970; PAHLUWAN_ARMOR_CLAIM_SLIP = 1971; YIGIT_ARMOR_CLAIM_SLIP = 1972; FROG_FISHING = 1976; SERPENT_RUMORS = 1977; MOOCHING = 1978; ANGLERS_ALMANAC = 1979; SPIFFY_SYNTH1 = 1980; SPIFFY_SYNTH2 = 1981; SPIFFY_SYNTH3 = 1982; SPIFFY_SYNTH4 = 1983; WOOD_PURIFICATION = 1984; WOOD_ENSORCELLMENT = 1985; LUMBERJACK = 1986; BOLTMAKER = 1987; WAY_OF_THE_CARPENTER = 1988; SPIFFY_SYNTH5 = 1989; SPIFFY_SYNTH6 = 1990; SPIFFY_SYNTH7 = 1991; METAL_PURIFICATION = 1992; METAL_ENSORCELLMENT = 1993; CHAINWORK = 1994; SHEETING = 1995; WAY_OF_THE_BLACKSMITH = 1996; SPIFFY_SYNTH8 = 1997; SPIFFY_SYNTH9 = 1998; SPIFFY_SYNTH10 = 1999; GOLD_PURIFICATION = 2000; GOLD_ENSORCELLMENT = 2001; CLOCKMAKING = 2002; WAY_OF_THE_GOLDSMITH = 2003; SPIFFY_SYNTH11 = 2004; SPIFFY_SYNTH12 = 2005; SPIFFY_SYNTH13 = 2006; SPIFFY_SYNTH14 = 2007; CLOTH_PURIFICATION = 2008; CLOTH_ENSORCELLMENT = 2009; SPINNING = 2010; FLETCHING = 2011; WAY_OF_THE_WEAVER = 2012; SPIFFY_SYNTH15 = 2013; SPIFFY_SYNTH16 = 2014; SPIFFY_SYNTH17 = 2015; LEATHER_PURIFICATION = 2016; LEATHER_ENSORCELLMENT = 2017; TANNING = 2018; WAY_OF_THE_TANNER = 2019; SPIFFY_SYNTH18 = 2020; SPIFFY_SYNTH19 = 2021; SPIFFY_SYNTH20 = 2022; SPIFFY_SYNTH21 = 2023; BONE_PURIFICATION = 2024; BONE_ENSORCELLMENT = 2025; FILING = 2026; WAY_OF_THE_BONEWORKER = 2027; SPIFFY_SYNTH22 = 2028; SPIFFY_SYNTH23 = 2029; SPIFFY_SYNTH24 = 2030; SPIFFY_SYNTH25 = 2031; ANIMA_SYNTHESIS = 2032; ALCHEMIC_PURIFICATION = 2033; ALCHEMIC_ENSORCELLMENT = 2034; TRITURATION = 2035; CONCOCTION = 2036; IATROCHEMISTRY = 2037; MIASMAL_COUNTERAGENT_RECIPE = 2038; WAY_OF_THE_ALCHEMIST = 2039; RAW_FISH_HANDLING = 2040; NOODLE_KNEADING = 2041; PATISSIER = 2042; STEWPOT_MASTERY = 2043; WAY_OF_THE_CULINARIAN = 2044; SPIFFY_SYNTH26 = 2045; SPIFFY_SYNTH27 = 2046; SPIFFY_SYNTH28 = 2047; VOIDWATCH_ALARUM = 2048; VOIDWATCHERS_EMBLEM_JEUNO = 2049; VOIDWATCHERS_EMBLEM_QUFIM = 2050; LOADSTONE = 2051; SOUL_GEM = 2052; SOUL_GEM_CLASP = 2053; TRICOLOR_VOIDWATCHERS_EMBLEM = 2054; STARLIGHT_VOIDWATCHERS_EMBLEM = 2055; RED_PRESENT = 2056; BLUE_PRESENT = 2057; GREEN_PRESENT = 2058; HEART_OF_THE_BUSHIN = 2059; HYACINTH_STRATUM_ABYSSITE = 2060; HYACINTH_STRATUM_ABYSSITE_II = 2061; AMBER_STRATUM_ABYSSITE = 2062; AMBER_STRATUM_ABYSSITE_II = 2063; CLAIRVOY_ANT = 2064; KUPOFRIEDS_CORUNDUM = 2065; KUPOFRIEDS_CORUNDUM = 2066; KUPOFRIEDS_CORUNDUM = 2067; BRONZE_ASTRARIUM = 2068; SILVER_ASTRARIUM = 2069; MYTHRIL_ASTRARIUM = 2070; GOLD_ASTRARIUM = 2071; PLATINUM_ASTRARIUM = 2072; DEMONS_IN_THE_RYE_CHRONICLE = 2073; MONSTROUS_MAYHEM_REPORT = 2074; CULLING_IS_CARING_POSTER = 2075; MERRY_MOOGLE_MEMORIAL_GUIDE = 2076; CONNORS_COMMUNIQUE = 2077; PERNICIOUS_PRESENTS_BRIEF = 2078; LITTLE_GOBLINS_ADVENTURE_VOL1 = 2079; LITTLE_GOBLINS_ADVENTURE_VOL2 = 2080; LITTLE_GOBLINS_ADVENTURE_VOL3 = 2081; LITTLE_GOBLINS_ADVENTURE_VOL4 = 2082; LITTLE_GOBLINS_ADVENTURE_VOL5 = 2083; LITTLE_GOBLINS_ADVENTURE_VOL6 = 2084; LITTLE_GOBLINS_ADVENTURE_VOL7 = 2085; LITTLE_GOBLINS_ADVENTURE_VOL8 = 2086; VANADIEL_TRIBUNE_VOL00 = 2087; VANADIEL_TRIBUNE_VOL01 = 2088; VANADIEL_TRIBUNE_VOL02 = 2089; VANADIEL_TRIBUNE_VOL03 = 2090; VANADIEL_TRIBUNE_VOL04 = 2091; VANADIEL_TRIBUNE_VOL05 = 2092; VANADIEL_TRIBUNE_VOL06 = 2093; VANADIEL_TRIBUNE_VOL07 = 2094; VANADIEL_TRIBUNE_VOL08 = 2095; VANADIEL_TRIBUNE_VOL09 = 2096; VANADIEL_TRIBUNE_VOL10 = 2097; VANADIEL_TRIBUNE_VOL11 = 2098; VANADIEL_TRIBUNE_VOL12 = 2099; VANADIEL_TRIBUNE_VOL13 = 2100; VANADIEL_TRIBUNE_VOL15 = 2102; VANADIEL_TRIBUNE_VOL16 = 2103; VANADIEL_TRIBUNE_VOL17 = 2104; VANADIEL_TRIBUNE_VOL18 = 2105; VANADIEL_TRIBUNE_VOL19 = 2106; VANADIEL_TRIBUNE_VOL20 = 2107; VANADIEL_TRIBUNE_VOL21 = 2108; VANADIEL_TRIBUNE_VOL22 = 2109; VANADIEL_TRIBUNE_VOL23 = 2110; VANADIEL_TRIBUNE_VOL24 = 2111; VANADIEL_TRIBUNE_VOL25 = 2112; VANADIEL_TRIBUNE_VOL26 = 2113; VANADIEL_TRIBUNE_VOL27 = 2114; VANADIEL_TRIBUNE_II_NO01 = 2115; VANADIEL_TRIBUNE_II_NO02 = 2116; VANADIEL_TRIBUNE_II_NO03 = 2117; VANADIEL_TRIBUNE_II_NO04 = 2118; VANADIEL_TRIBUNE_II_NO05 = 2119; VANADIEL_TRIBUNE_II_NO06 = 2120; VANADIEL_TRIBUNE_II_NO07 = 2121; VANADIEL_TRIBUNE_II_NO08 = 2122; VANADIEL_TRIBUNE_II_NO09 = 2123; VANADIEL_TRIBUNE_II_NO10 = 2124; VANADIEL_TRIBUNE_II_NO11 = 2125; VANADIEL_TRIBUNE_II_NO12 = 2126; VANADIEL_TRIBUNE_II_NO13 = 2127; VANADIEL_TRIBUNE_II_NO14 = 2128; VANADIEL_TRIBUNE_II_NO15 = 2129; VANADIEL_TRIBUNE_II_NO16 = 2130; HANDCRAFTED_SPATULA = 2131; TRANSMUTED_CANDLE = 2132; GOURMET_WHIPPED_CREAM = 2133; ANCIENT_PAPYRUS_SHRED1 = 2134; ANCIENT_PAPYRUS_SHRED2 = 2135; ANCIENT_PAPYRUS_SHRED3 = 2136; EXORAY_MOLD_CRUMB1 = 2137; EXORAY_MOLD_CRUMB2 = 2138; EXORAY_MOLD_CRUMB3 = 2139; BOMB_COAL_FRAGMENT1 = 2140; BOMB_COAL_FRAGMENT2 = 2141; BOMB_COAL_FRAGMENT3 = 2142; SHINING_FRAGMENT = 2143; GLOSSY_FRAGMENT = 2144; GRIMOIRE_PAGE = 2145; MOBLIN_PHEROMONE_SACK = 2146; GOLDEN_WING = 2147; MOSS_COVERED_SHARD = 2148; ESSENCE_OF_PERFERVIDITY = 2149; BRANDED_WING = 2150; MALICIOUS_HORN = 2151; SHEET_OF_SAN_DORIAN_TUNES = 2152; SHEET_OF_BASTOKAN_TUNES = 2153; SHEET_OF_WINDURSTIAN_TUNES = 2154; GEOMAGNETRON = 2155; ADOULINIAN_CHARTER_PERMIT = 2156; PIONEERS_BADGE = 2157; TEMPORARY_GEOMAGNETRON = 2158; AGED_MATRIARCH_NAAKUAL_CREST = 2159; AGED_RIPTIDE_NAAKUAL_CREST = 2160; AGED_FIREBRAND_NAAKUAL_CREST = 2161; AGED_LIGNEOUS_NAAKUAL_CREST = 2162; AGED_BOOMING_NAAKUAL_CREST = 2163; AGED_FLASHFROST_NAAKUAL_CREST = 2164; PROTOTYPE_ATTUNER = 2166; WATERCRAFT = 2167; RESTRAINMENT_RESILIENCE = 2171; CUPFUL_OF_DUST_LADEN_SAP = 2179; MANTID_BAIT = 2180; VIAL_OF_TOXIC_ZOLDEFF_WATER = 2185; FISTFUL_OF_PRISTINE_SAND = 2186; RIME_ICE_FRAGMENT = 2190; BROKEN_HARPOON = 2192; EXTRAVAGANT_HARPOON = 2193; GEOMAGNETIC_COMPASS = 2196; OCULAR_ORB = 2197; PILE_OF_NOXIOUS_GRIME = 2198; PULSATING_SHARD = 2199; DINNER_INVITATION = 2200; ROCKBERRY1 = 2201; ROCKBERRY2 = 2202; ROCKBERRY3 = 2203; LOGGING = 2204; WATERCRAFTING = 2205; DEMOLISHING = 2206; TOXIN_RESILIENCE = 2207; PARESIS_RESILIENCE = 2208; CALOR_RESILIENCE = 2209; HEN_FS_BUILDING_MAT_CONTAINER = 2210; MOR_FS_BUILDING_MAT_CONTAINER = 2211; HEN_FS_RESOURCE_CONTAINER = 2212; MOR_FS_RESOURCE_CONTAINER = 2213; CEI_FB_OP_MATERIALS_CONTAINER = 2214; HEN_FB_OP_MATERIALS_CONTAINER = 2215; MOR_FB_OP_MATERIALS_CONTAINER = 2216; LOST_ARTICLE1 = 2217; LOST_ARTICLE2 = 2218; FLAYED_MANTID_CORPSE = 2220; CHAPULI_HORN = 2221; HOT_SPRING_REPORT_1 = 2225; HOT_SPRING_REPORT_2 = 2226; HOT_SPRING_REPORT_3 = 2227; HOT_SPRING_REPORT_4 = 2228; HOT_SPRING_REPORT_5 = 2229; MAGMA_SURVEY_REPORT = 2232; REIVE_UNITY = 2234; CRITICAL_CHOP = 2236; CHERISHED_AXE = 2237; CRITICAL_SMASH = 2238; CHERISHED_PICK = 2239; CRITICAL_SLICE = 2240; CHERISHED_SICKLE = 2241; SAN_DORIA_WARP_RUNE = 2248; BASTOK_WARP_RUNE = 2249; WINDURST_WARP_RUNE = 2250; SELBINA_WARP_RUNE = 2251; MHAURA_WARP_RUNE = 2252; KAZHAM_WARP_RUNE = 2253; RABAO_WARP_RUNE = 2254; NORG_WARP_RUNE = 2255; TAVNAZIA_WARP_RUNE = 2256; WHITEGATE_WARP_RUNE = 2257; NASHMAU_WARP_RUNE = 2258; RUSTED_PICKAXE = 2261; TINY_SEED = 2262; BOTTLE_OF_FERTILIZER_X = 2263; WAYPOINT_SCANNER_KIT = 2264; ROYAL_FIAT_BANNING_COLONIZATION = 2265; RECORD_OF_THE_17TH_ASSEMBLY = 2266; COPY_OF_THE_ALLIANCE_AGREEMENT = 2267; ULBUKAN_NAVIGATION_CHART = 2268; COPY_OF_ADOULINS_PATRONESS = 2269; MEMO_FROM_MIDRAS = 2270; CIDS_CATALYST = 2271; CHUNK_OF_MILKY_WHITE_MINERALS = 2272; FAIL_BADGE = 2273; WESTERN_ADOULIN_PATROL_ROUTE = 2274; MISDELIVERED_PARCEL = 2275; EASTERN_ADOULIN_PATROL_ROUTE = 2276; HOT_SPRINGS_CARE_PACKAGE = 2277; FISTFUL_OF_HOMELAND_SOIL = 2278; YAHSE_WILDFLOWER_PETAL = 2279; HABITUAL_BEHAVIOR_BAROMETER = 2280; BRIER_PROOF_NET = 2281; COMPASS_OF_TRANSFERENCE = 2282; MAGMA_MITIGATION_SET = 2283; RESURRECTION_RETARDANT_AXE = 2284; INSULATOR_TABLET = 2285; ANTI_GLACIATION_GEAR = 2286; LAND_OF_MILK_AND_HONEY_HIVE = 2288; FULL_LAND_OF_MILK_AND_HONEY_HIVE = 2289; LUOPAN = 2290; RALA_SIMULACRUM = 2291; YORCIA_SIMULACRUM = 2292; CIRDAS_SIMULACRUM = 2293; RAKAZNAR_SIMULACRUM = 2294; CELADON_YANTRIC_PLANCHETTE = 2296; ZAFFRE_YANTRIC_PLANCHETTE = 2297; ALIZARIN_YANTRIC_PLANCHETTE = 2298; DETACHED_STINGER = 2299; CRAGGY_FIN = 2300; FLAME_SCARRED_SKULL = 2301; MAP_OF_RALA_WATERWAYS_U = 2302; MAP_OF_YORCIA_WEALD_U = 2303; MAP_OF_CIRDAS_CAVERNS_U = 2304; MAP_OF_OUTER_RAKAZNAR_U = 2305; MOG_KUPON_A_DEII = 2334; MOG_KUPON_A_DE = 2335; MOG_KUPON_A_SAL = 2336; MOG_KUPON_A_NYZ = 2337; MOG_KUPON_I_S5 = 2338; MOG_KUPON_I_S2 = 2339; MOG_KUPON_I_ORCHE = 2340; SHEET_OF_E_ADOULINIAN_TUNES = 2341; SHEET_OF_W_ADOULINIAN_TUNES = 2342; HENNEBLOOM_LEAF = 2343; IMPURE_CELADON_YGGZI = 2344; SEMI_PURE_CELADON_YGGZI = 2345; IMPURE_ZAFFRE_YGGZI = 2346; SEMI_PURE_ZAFFRE_YGGZI = 2347; IMPURE_ALIZARIN_YGGZI = 2348; SEMI_PURE_ALIZARIN_YGGZI = 2349; RING_OF_SUPERNAL_DISJUNCTION = 2350; EPHEMERAL_ENDEAVOR = 2352; ENLIGHTENED_ENDEAVOR = 2353; RUNE_SABER = 2354; FLASK_OF_FRUISERUM = 2355; FROST_ENCRUSTED_FLAME_GEM = 2356; LETTER_FROM_OCTAVIEN = 2357; STONE_OF_IGNIS = 2358; STONE_OF_GELUS = 2359; STONE_OF_FLABRA = 2360; STONE_OF_TELLUS = 2361; STONE_OF_SULPOR = 2362; STONE_OF_UNDA = 2363; STONE_OF_LUX = 2364; STONE_OF_TENEBRAE = 2365; STONE_OF_UNKNOWN_RUNIC_ORIGINS1 = 2366; STONE_OF_UNKNOWN_RUNIC_ORIGINS2 = 2367; STONE_OF_UNKNOWN_RUNIC_ORIGINS3 = 2368; SECRETS_OF_RUNIC_ENHANCEMENT = 2369; RUNIC_KINEGRAVER = 2370; VIAL_OF_VIVID_RAINBOW_EXTRACT = 2371; INSIDIOS_EXTINGUISHED_LANTERN = 2372; VESSEL_OF_SUMMONING = 2373; SILVER_LUOPAN = 2374; LHAISO_NEFTEREHS_BELL = 2375; MIDRASS_EXPLOSIVE_SAMPLE = 2376; REPORT_ON_MIDRASS_EXPLOSIVE = 2377; TRAY_OF_ADOULINIAN_DELICACIES = 2378; SMALL_BAG_OF_ADOULINIAN_DELICACIES = 2379; WAYPOINT_RECALIBRATION_KIT = 2380; TWELVE_ORDERS_DOSSIER = 2381; RAVINE_WATER_TESTING_KIT = 2382; FISTFUL_OF_NUMBING_SOIL = 2383; HUNK_OF_BEDROCK = 2384; YORCIAS_TEAR = 2385; BLIGHTBERRY = 2386; LARGE_STRIP_OF_VELKK_HIDE = 2387; CLIMBING = 2388; BOX_OF_ADOULINIAN_TOMATOES = 2389; KALEIDOSCOPIC_CLAM = 2390; GLASS_PENDULUM = 2391; IVORY_WING_TALISMAN = 2393; BRONZE_MATTOCK_CORDON = 2394; BRONZE_SHOVEL_CORDON = 2395; TARUTARU_SAUCE_INVOICE = 2396; TARUTARU_SAUCE_RECEIPT = 2397; GPS_CRYSTAL = 2398; PAIR_OF_VELKK_GLOVES = 2399; LOST_ARTICLE1 = 2400; LOST_ARTICLE2 = 2401; GEOMANCER_CLAIM_TICKET = 2402; MAR_FB_OP_MATERIALS_CONTAINER = 2403; YOR_FB_OP_MATERIALS_CONTAINER = 2404; MAR_FS_BUILDING_MAT_CONTAINER = 2405; YOR_FS_BUILDING_MAT_CONTAINER = 2406; PROOF_OF_ORDER_RUNIC_HEADGEAR1 = 2407; PROOF_OF_ORDER_RUNIC_HANDGEAR2 = 2408; PROOF_OF_ORDER_RUNIC_FOOTGEAR4 = 2409; ROSULATIAS_POME = 2410; CELENNIA_MEMORIAL_LIBRARY_CARD = 2411; SOWYOURSEED = 2412; MY_FIRST_FURROW = 2413; FIELDS_AND_FERTILIZING = 2414; DESIGNER_FARMING = 2415; HOMESTEADERS_COMPENDIUM = 2416; MHMU_TREATISE_ON_AGRONOMY = 2417; GIVE_MY_REGARDS_TO_REODOAN = 2419; ADOULINS_TOPIARY_TREASURES = 2420; GRANDILOQUENT_GROVES = 2421; ARBOREAL_ABRACADABRA = 2422; VERDANT_AND_VERDONTS = 2423; MHMU_TREATISE_ON_FORESTRY = 2424; MYTHRIL_MARATHON_QUARTERLY = 2426; TAKE_A_LODE_OFF = 2427; VARICOSE_MINERAL_VEINS = 2428; TALES_FROM_THE_TUNNEL = 2429; THE_GUSGEN_MINES_TRAGEDY = 2430; MHMU_TREATISE_ON_MINERALOGY = 2431; A_FAREWELL_TO_FRESHWATER = 2433; WATER_WATER_EVERYWHERE = 2434; DREDGINGS_NO_DRUDGERY = 2435; ALL_THE_WAYS_TO_SKIN_A_CARP = 2436; ANATOMY_OF_AN_ANGLER = 2437; MHMU_TREATISE_ON_FISH_I = 2438; THE_OLD_MEN_OF_THE_SEA = 2440; BLACK_FISH_OF_THE_FAMILY = 2442; TWENTY_THOUSAND_YALMS_UNDER_THE_SEA = 2443; ENCYCLOPEDIA_ICTHYONNICA = 2444; MHMU_TREATISE_ON_FISH_II = 2445; MAR_FS_RESOURCE_CONTAINER = 2447; YOR_FS_RESOURCE_CONTAINER = 2448; NOTE_DETAILING_SEDITIOUS_PLANS = 2449; WATERWAY_FACILITY_CRANK = 2450; VIAL_OF_TRANSLURRY = 2451; GIL_REPOSITORY = 2452; CRAB_CALLER = 2453; PIECE_OF_A_STONE_WALL = 2454; VIAL_OF_UNTAINTED_HOLY_WATER = 2455; ETERNAL_FLAME = 2456; WEATHER_VANE_WINGS = 2457; AUREATE_BALL_OF_FUR = 2458; INVENTORS_COALITION_PICKAXE = 2459; TINTINNABULUM = 2460; FRAGMENTING = 2461; PAIR_OF_FUZZY_EARMUFFS = 2462; KAM_FB_OP_MATERIALS_CONTAINER = 2463; KAM_FS_BUILDING_MAT_CONTAINER = 2464; KAM_FS_RESOURCE_CONTAINER = 2465; MEMORANDOLL = 2466; SHADOW_LORD_PHANTOM_GEM = 2468; CELESTIAL_NEXUS_PHANTOM_GEM = 2469; STELLAR_FULCRUM_PHANTOM_GEM = 2470; PHANTOM_GEM_OF_APATHY = 2471; PHANTOM_GEM_OF_ARROGANCE = 2472; PHANTOM_GEM_OF_ENVY = 2473; PHANTOM_GEM_OF_COWARDICE = 2474; PHANTOM_GEM_OF_RAGE = 2475; P_PERPETRATOR_PHANTOM_GEM = 2476; COPPER_AMAN_VOUCHER = 2477; MATRIARCH_NAAKUAL_PARAGON = 2482; RIPTIDE_NAAKUAL_PARAGON = 2483; FIREBRAND_NAAKUAL_PARAGON = 2484; LIGNEOUS_NAAKUAL_PARAGON = 2485; BOOMING_NAAKUAL_PARAGON = 2486; FLASHFROST_NAAKUAL_PARAGON = 2487; MOG_KUPON_I_AF109 = 2489; MOG_KUPON_W_EWS = 2490; MOG_KUPON_AW_WK = 2491; MOG_KUPON_I_S3 = 2492; MOG_KUPON_A_PK109 = 2493; MOG_KUPON_I_S1 = 2494; MOG_KUPON_I_SKILL = 2495; GREEN_INSTITUTE_CARD = 2496; WINDURST_TRUST_PERMIT = 2497; BLUE_INSTITUTE_CARD = 2498; BASTOK_TRUST_PERMIT = 2499; RED_INSTITUTE_CARD = 2500; SAN_DORIA_TRUST_PERMIT = 2501; MOG_KUPON_I_RME = 2502; PULVERIZING = 2503; LERENES_PATEN = 2504; AMCHUCHUS_MISSIVE = 2505; TEMPLE_KNIGHT_KEY = 2506; UNBLEMISHED_PIONEERS_BADGE = 2507; SILVERY_PLATE = 2508; SOUL_SIPHON = 2509; TAPESTRY_OF_BAGUA_POETRY = 2511; FUTHARKIC_CONCEPTS_IN_FLUX = 2512; CRYSTALLIZED_LIFESTREAM_ESSENCE = 2513; STRAND_OF_RAKAZNAR_FILAMENT = 2514; ORDER_SLIP_LIFESTREAM_HEADGEAR = 2515; ORDER_SLIP_LIFESTREAM_BODYGEAR = 2516; ORDER_SLIP_LIFESTREAM_HANDGEAR = 2517; ORDER_SLIP_LIFESTREAM_LEGGEAR = 2518; ORDER_SLIP_LIFESTREAM_FOOTGEAR = 2519; ORDER_SLIP_LOGOMORPH_HEADGEAR = 2520; ORDER_SLIP_LOGOMORPH_BODYGEAR = 2521; ORDER_SLIP_LOGOMORPH_HANDGEAR = 2522; ORDER_SLIP_LOGOMORPH_LEGGEAR = 2523; ORDER_SLIP_LOGOMORPH_FOOTGEAR = 2524; PRISTINE_HAIR_RIBBON = 2525; VIAL_OF_TRANSMELANGE = 2526; LOST_ARTICLE = 2527; BREATH_OF_DAWN = 2528; PHLOX_YANTRIC_PLANCHETTE = 2529; RUSSET_YANTRIC_PLANCHETTE = 2530; ASTER_YANTRIC_PLANCHETTE = 2531; SPARKING_TAIL_FEATHER = 2532; PIECE_OF_INVIOLABLE_BARK = 2533; FROSTED_INCISOR = 2534; IMPURE_PHLOX_YGGZI = 2535; SEMI_PURE_PHLOX_YGGZI = 2536; IMPURE_RUSSET_YGGZI = 2537; SEMI_PURE_RUSSET_YGGZI = 2538; IMPURE_ASTER_YGGZI = 2539; SEMI_PURE_ASTER_YGGZI = 2540; BREATH_OF_DAWN1 = 2541; BREATH_OF_DAWN2 = 2542; BREATH_OF_DAWN3 = 2543; JOB_BREAKER = 2544;
gpl-3.0
amenophis1er/prosody-modules
mod_statistics/top.lua
32
6810
module("prosodytop", package.seeall); local array = require "util.array"; local it = require "util.iterators"; local curses = require "curses"; local stats = require "stats".stats; local time = require "socket".gettime; local sessions_idle_after = 60; local stanza_names = {"message", "presence", "iq"}; local top = {}; top.__index = top; local status_lines = { "Prosody $version - $time up $up_since, $total_users users, $cpu busy"; "Connections: $total_c2s c2s, $total_s2sout s2sout, $total_s2sin s2sin, $total_component component"; "Memory: $memory_lua lua, $memory_allocated process ($memory_used in use)"; "Stanzas in: $message_in_per_second message/s, $presence_in_per_second presence/s, $iq_in_per_second iq/s"; "Stanzas out: $message_out_per_second message/s, $presence_out_per_second presence/s, $iq_out_per_second iq/s"; }; function top:draw() self:draw_status(); self:draw_column_titles(); self:draw_conn_list(); self.statuswin:refresh(); self.listwin:refresh(); --self.infowin:refresh() self.stdscr:move(#status_lines,0) end -- Width specified as cols or % of unused space, defaults to -- title width if not specified local conn_list_columns = { { title = "ID", key = "id", width = "8" }; { title = "JID", key = "jid", width = "100%" }; { title = "STANZAS IN>", key = "total_stanzas_in", align = "right" }; { title = "MSG", key = "message_in", align = "right", width = "4" }; { title = "PRES", key = "presence_in", align = "right", width = "4" }; { title = "IQ", key = "iq_in", align = "right", width = "4" }; { title = "STANZAS OUT>", key = "total_stanzas_out", align = "right" }; { title = "MSG", key = "message_out", align = "right", width = "4" }; { title = "PRES", key = "presence_out", align = "right", width = "4" }; { title = "IQ", key = "iq_out", align = "right", width = "4" }; { title = "BYTES IN", key = "bytes_in", align = "right" }; { title = "BYTES OUT", key = "bytes_out", align = "right" }; }; function top:draw_status() for row, line in ipairs(status_lines) do self.statuswin:mvaddstr(row-1, 0, (line:gsub("%$([%w_]+)", self.data))); self.statuswin:clrtoeol(); end -- Clear stanza counts for _, stanza_type in ipairs(stanza_names) do self.prosody[stanza_type.."_in_per_second"] = 0; self.prosody[stanza_type.."_out_per_second"] = 0; end end local function padright(s, width) return s..string.rep(" ", width-#s); end local function padleft(s, width) return string.rep(" ", width-#s)..s; end function top:resized() self:recalc_column_widths(); --self.stdscr:clear(); self:draw(); end function top:recalc_column_widths() local widths = {}; self.column_widths = widths; local total_width = curses.cols()-4; local free_width = total_width; for i = 1, #conn_list_columns do local width = conn_list_columns[i].width or "0"; if not(type(width) == "string" and width:sub(-1) == "%") then width = math.max(tonumber(width), #conn_list_columns[i].title+1); widths[i] = width; free_width = free_width - width; end end for i = 1, #conn_list_columns do if not widths[i] then local pc_width = tonumber((conn_list_columns[i].width:gsub("%%$", ""))); widths[i] = math.floor(free_width*(pc_width/100)); end end return widths; end function top:draw_column_titles() local widths = self.column_widths; self.listwin:attron(curses.A_REVERSE); self.listwin:mvaddstr(0, 0, " "); for i, column in ipairs(conn_list_columns) do self.listwin:addstr(padright(column.title, widths[i])); end self.listwin:addstr(" "); self.listwin:attroff(curses.A_REVERSE); end local function session_compare(session1, session2) local stats1, stats2 = session1.stats, session2.stats; return (stats1.total_stanzas_in + stats1.total_stanzas_out) > (stats2.total_stanzas_in + stats2.total_stanzas_out); end function top:draw_conn_list() local rows = curses.lines()-(#status_lines+2)-5; local cutoff_time = time() - sessions_idle_after; local widths = self.column_widths; local top_sessions = array.collect(it.values(self.active_sessions)):sort(session_compare); for index = 1, rows do session = top_sessions[index]; if session then if session.last_update < cutoff_time then self.active_sessions[session.id] = nil; else local row = {}; for i, column in ipairs(conn_list_columns) do local width = widths[i]; local v = tostring(session[column.key] or ""):sub(1, width); if #v < width then if column.align == "right" then v = padleft(v, width-1).." "; else v = padright(v, width); end end table.insert(row, v); end if session.updated then self.listwin:attron(curses.A_BOLD); end self.listwin:mvaddstr(index, 0, " "..table.concat(row)); if session.updated then session.updated = false; self.listwin:attroff(curses.A_BOLD); end end else -- FIXME: How to clear a line? It's 5am and I don't feel like reading docs. self.listwin:move(index, 0); self.listwin:clrtoeol(); end end end function top:update_stat(name, value) self.prosody[name] = value; end function top:update_session(id, jid, stats) self.active_sessions[id] = stats; stats.id, stats.jid, stats.stats = id, jid, stats; stats.total_bytes = stats.bytes_in + stats.bytes_out; for _, stanza_type in ipairs(stanza_names) do self.prosody[stanza_type.."_in_per_second"] = (self.prosody[stanza_type.."_in_per_second"] or 0) + stats[stanza_type.."_in"]; self.prosody[stanza_type.."_out_per_second"] = (self.prosody[stanza_type.."_out_per_second"] or 0) + stats[stanza_type.."_out"]; end stats.total_stanzas_in = stats.message_in + stats.presence_in + stats.iq_in; stats.total_stanzas_out = stats.message_out + stats.presence_out + stats.iq_out; stats.last_update = time(); stats.updated = true; end function new(base) setmetatable(base, top); base.data = setmetatable({}, { __index = function (t, k) local stat = stats[k]; if stat and stat.tostring then if type(stat.tostring) == "function" then return stat.tostring(base.prosody[k]); elseif type(stat.tostring) == "string" then local v = base.prosody[k]; if v == nil then return "?"; end return (stat.tostring):format(v); end end return base.prosody[k]; end; }); base.active_sessions = {}; base.statuswin = curses.newwin(#status_lines, 0, 0, 0); base.promptwin = curses.newwin(1, 0, #status_lines, 0); base.promptwin:addstr(""); base.promptwin:refresh(); base.listwin = curses.newwin(curses.lines()-(#status_lines+2)-5, 0, #status_lines+1, 0); base.listwin:syncok(); base.infowin = curses.newwin(5, 0, curses.lines()-5, 0); base.infowin:mvaddstr(1, 1, "Hello world"); base.infowin:border(0,0,0,0); base.infowin:syncok(); base.infowin:refresh(); base:resized(); return base; end return _M;
mit
awhitesong/rspamd
test/lua/unit/redis_stat.lua
3
1570
context("Redis statistics unit tests", function() local task = require("rspamd_task") local ffi = require("ffi") ffi.cdef[[ struct rspamd_statfile_config { const char *symbol; const char *label; void *opts; int is_spam; const char *backend; void *data; }; unsigned long rspamd_redis_expand_object(const char *pattern, struct rspamd_statfile_config *stcf, struct rspamd_task *task, char **target); struct rspamd_task * rspamd_task_new(struct rspamd_worker *worker); int rspamd_task_add_recipient (struct rspamd_task *task, const char *rcpt); int rspamd_task_add_sender (struct rspamd_task *task, const char *sender); ]] test("Substitute redis values", function() local cases = { {"%s%l", "symbollabel"}, {"%s%%", "symbol%"}, {"%s%u", "symbol"}, {"%s%W", "symbolW"}, {"%r%l", "test@example.comlabel"}, {"%f-from", "test@example.com-from"} } local stcf = ffi.new("struct rspamd_statfile_config", {symbol="symbol",label="label"}) local t = ffi.C.rspamd_task_new(nil) assert_equal(ffi.C.rspamd_task_add_recipient(t, "Test <test@example.com>"), 1) assert_equal(ffi.C.rspamd_task_add_recipient(t, "Test1 <test1@example.com>"), 1) assert_equal(ffi.C.rspamd_task_add_sender(t, "Test <test@example.com>"), 1) for _,c in ipairs(cases) do local pbuf = ffi.new 'char *[1]' local sz = ffi.C.rspamd_redis_expand_object(c[1], stcf, t, pbuf) local s = ffi.string(pbuf[0]) assert_equal(s, c[2]) end end) end)
bsd-2-clause
zhaozg/lit
commands/get-luvi.lua
4
1403
return function () local core = require('core')() local uv = require('uv') local log = require('log').log local query = require('pkg').query local fs = require('coro-fs') -- Try to look up local metadata in case we're inside a luvi app. local meta = query(fs, ".") local opts = meta and meta.luvi or {} -- Allow command-line overrides local i = 2 while i < #args do local arg = args[i] if arg == "-o" then opts.output = assert(args[i + 1], "missing output value") i = i + 2 elseif arg == "-f" then opts.flavor = assert(args[i + 1], "missing flavor value") i = i + 2 elseif arg == "-u" then opts.url = assert(args[i + 1], "missing url value") i = i + 2 elseif arg == "-v" then opts.version = assert(args[i + 1], "missing version value") i = i + 2 else error("Unknown option: " .. arg) end end -- Ensure we have the right luvi. local path = core.getLuvi(opts) if opts.output then -- Copy to the output file if requested local fd2 = assert(uv.fs_open(opts.output, "w", 493)) -- 0755 local fd = assert(uv.fs_open(path, "r", 420)) -- 0644 local size = assert(uv.fs_fstat(fd)).size uv.fs_sendfile(fd2, fd, 0, size) uv.fs_close(fd) uv.fs_close(fd2) log("luvi extracted", opts.output) else -- Otherwise just emit path log("luvi cached", path) end end
apache-2.0
Lsty/ygopro-scripts
c55608151.lua
3
1070
--グリフォンの翼 function c55608151.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_DISABLE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_CHAINING) e1:SetCondition(c55608151.condition) e1:SetTarget(c55608151.target) e1:SetOperation(c55608151.activate) c:RegisterEffect(e1) end function c55608151.condition(e,tp,eg,ep,ev,re,r,rp) return rp~=tp and re:IsHasType(EFFECT_TYPE_ACTIVATE) and re:GetHandler():IsCode(18144506) and Duel.IsChainDisablable(ev) end function c55608151.filter(c) return c:IsType(TYPE_SPELL+TYPE_TRAP) and c:IsDestructable() end function c55608151.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_DISABLE,eg,1,0,0) local g=Duel.GetMatchingGroup(c55608151.filter,tp,0,LOCATION_ONFIELD,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) end function c55608151.activate(e,tp,eg,ep,ev,re,r,rp) Duel.NegateEffect(ev) local g=Duel.GetMatchingGroup(c55608151.filter,tp,0,LOCATION_ONFIELD,nil) Duel.Destroy(g,REASON_EFFECT) end
gpl-2.0
brimworks/luvi
samples/test.app/utils.lua
10
9094
local uv = require('uv') local env = require('env') local prettyPrint, dump, strip, color, colorize, loadColors local theme = {} local useColors = false local defaultTheme local stdout, stdin, stderr, width local quote, quote2, dquote, dquote2, obracket, cbracket, obrace, cbrace, comma, equals, controls local themes = { -- nice color theme using 16 ansi colors [16] = { property = "0;37", -- white sep = "1;30", -- bright-black braces = "1;30", -- bright-black ["nil"] = "1;30", -- bright-black boolean = "0;33", -- yellow number = "1;33", -- bright-yellow string = "0;32", -- green quotes = "1;32", -- bright-green escape = "1;32", -- bright-green ["function"] = "0;35", -- purple thread = "1;35", -- bright-purple table = "1;34", -- bright blue userdata = "1;36", -- bright cyan cdata = "0;36", -- cyan err = "1;31", -- bright red success = "1;33;42", -- bright-yellow on green failure = "1;33;41", -- bright-yellow on red highlight = "1;36;44", -- bright-cyan on blue }, -- nice color theme using ansi 256-mode colors [256] = { property = "38;5;253", braces = "38;5;247", sep = "38;5;240", ["nil"] = "38;5;244", boolean = "38;5;220", -- yellow-orange number = "38;5;202", -- orange string = "38;5;34", -- darker green quotes = "38;5;40", -- green escape = "38;5;46", -- bright green ["function"] = "38;5;129", -- purple thread = "38;5;199", -- pink table = "38;5;27", -- blue userdata = "38;5;39", -- blue2 cdata = "38;5;69", -- teal err = "38;5;196", -- bright red success = "38;5;120;48;5;22", -- bright green on dark green failure = "38;5;215;48;5;52", -- bright red on dark red highlight = "38;5;45;48;5;236", -- bright teal on dark grey }, } local special = { [7] = 'a', [8] = 'b', [9] = 't', [10] = 'n', [11] = 'v', [12] = 'f', [13] = 'r' } function loadColors(index) if index == nil then index = defaultTheme end -- Remove the old theme for key in pairs(theme) do theme[key] = nil end if index then local new = themes[index] if not new then error("Invalid theme index: " .. tostring(index)) end -- Add the new theme for key in pairs(new) do theme[key] = new[key] end useColors = true else useColors = false end quote = colorize('quotes', "'", 'string') quote2 = colorize('quotes', "'") dquote = colorize('quotes', '"', 'string') dquote2 = colorize('quotes', '"') obrace = colorize('braces', '{ ') cbrace = colorize('braces', '}') obracket = colorize('property', '[') cbracket = colorize('property', ']') comma = colorize('sep', ', ') equals = colorize('sep', ' = ') controls = {} for i = 0, 31 do local c = special[i] if not c then if i < 10 then c = "00" .. tostring(i) else c = "0" .. tostring(i) end end controls[i] = colorize('escape', '\\' .. c, 'string') end controls[92] = colorize('escape', '\\\\', 'string') controls[34] = colorize('escape', '\\"', 'string') controls[39] = colorize('escape', "\\'", 'string') end function color(colorName) return '\27[' .. (theme[colorName] or '0') .. 'm' end function colorize(colorName, string, resetName) return useColors and (color(colorName) .. tostring(string) .. color(resetName)) or tostring(string) end local function stringEscape(c) return controls[string.byte(c, 1)] end function dump(value) local seen = {} local output = {} local offset = 0 local stack = {} local function recalcOffset(index) for i = index + 1, #output do local m = string.match(output[i], "\n([^\n]*)$") if m then offset = #(strip(m)) else offset = offset + #(strip(output[i])) end end end local function write(text, length) if not length then length = #(strip(text)) end -- Create room for data by opening parent blocks -- Start at the root and go down. local i = 1 while offset + length > width and stack[i] do local entry = stack[i] if not entry.opened then entry.opened = true table.insert(output, entry.index + 1, "\n" .. string.rep(" ", i)) -- Recalculate the offset recalcOffset(entry.index) -- Bump the index of all deeper entries for j = i + 1, #stack do stack[j].index = stack[j].index + 1 end end i = i + 1 end output[#output + 1] = text offset = offset + length if offset > width then dump(stack) end end local function indent() stack[#stack + 1] = { index = #output, opened = false, } end local function unindent() stack[#stack] = nil end local function process(value) local typ = type(value) if typ == 'string' then if string.match(value, "'") and not string.match(value, '"') then write(dquote .. string.gsub(value, '[%c\\]', stringEscape) .. dquote2) else write(quote .. string.gsub(value, "[%c\\']", stringEscape) .. quote2) end elseif typ == 'table' and not seen[value] then seen[value] = true write(obrace) local i = 1 -- Count the number of keys so we know when to stop adding commas local total = 0 for _ in pairs(value) do total = total + 1 end for k, v in pairs(value) do indent() if k == i then -- if the key matches the index, don't show it. -- This is how lists print without keys process(v) else if type(k) == "string" and string.find(k,"^[%a_][%a%d_]*$") then write(colorize("property", k) .. equals) else write(obracket) process(k) write(cbracket .. equals) end if type(v) == "table" then process(v) else indent() process(v) unindent() end end if i < total then write(comma) else write(" ") end i = i + 1 unindent() end write(cbrace) else write(colorize(typ, tostring(value))) end end process(value) return table.concat(output, "") end -- Print replacement that goes through libuv. This is useful on windows -- to use libuv's code to translate ansi escape codes to windows API calls. function print(...) local n = select('#', ...) local arguments = {...} for i = 1, n do arguments[i] = tostring(arguments[i]) end uv.write(stdout, table.concat(arguments, "\t") .. "\n") end function prettyPrint(...) local n = select('#', ...) local arguments = { ... } for i = 1, n do arguments[i] = dump(arguments[i]) end print(table.concat(arguments, "\t")) end function strip(str) return string.gsub(str, '\027%[[^m]*m', '') end if uv.guess_handle(0) == 'tty' then stdin = assert(uv.new_tty(0, true)) else stdin = uv.new_pipe(false) uv.pipe_open(stdin, 0) end if uv.guess_handle(1) == 'tty' then stdout = assert(uv.new_tty(1, false)) width = uv.tty_get_winsize(stdout) -- auto-detect when 16 color mode should be used local term = env.get("TERM") if term == 'xterm' or term == 'xterm-256color' then defaultTheme = 256 else defaultTheme = 16 end else stdout = uv.new_pipe(false) uv.pipe_open(stdout, 1) width = 80 end loadColors() if uv.guess_handle(2) == 'tty' then stderr = assert(uv.new_tty(2, false)) else stderr = uv.new_pipe(false) uv.pipe_open(stderr, 2) end local function bind(fn, ...) local args = {...} if #args == 0 then return fn end return function () return fn(unpack(args)) end end local function noop(err) if err then print("Unhandled callback error", err) end end local function adapt(c, fn, ...) local nargs = select('#', ...) local args = {...} -- No continuation defaults to noop callback if not c then c = noop end local t = type(c) if t == 'function' then args[nargs + 1] = c return fn(unpack(args)) elseif t ~= 'thread' then error("Illegal continuation type " .. t) end local err, data, waiting args[nargs + 1] = function (err, ...) if waiting then if err then assert(coroutine.resume(c, nil, err)) else assert(coroutine.resume(c, ...)) end else error, data = err, {...} c = nil end end fn(unpack(args)) if c then waiting = true return coroutine.yield(c) elseif err then return nil, err else return unpack(data) end end return { bind = bind, loadColors = loadColors, theme = theme, print = print, prettyPrint = prettyPrint, dump = dump, strip = strip, color = color, colorize = colorize, stdin = stdin, stdout = stdout, stderr = stderr, noop = noop, adapt = adapt, }
apache-2.0
Lsty/ygopro-scripts
c38492752.lua
7
1324
--ラヴァル・キャノン function c38492752.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(38492752,0)) e1:SetCategory(CATEGORY_SPECIAL_SUMMON) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetTarget(c38492752.sptg) e1:SetOperation(c38492752.spop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetCode(EVENT_FLIP_SUMMON_SUCCESS) c:RegisterEffect(e2) end function c38492752.filter(c,e,tp) return c:IsSetCard(0x39) and c:IsFaceup() and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c38492752.sptg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_REMOVED) and chkc:IsControler(tp) and c38492752.filter(chkc,e,tp) end if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.IsExistingTarget(c38492752.filter,tp,LOCATION_REMOVED,0,1,nil,e,tp) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectTarget(tp,c38492752.filter,tp,LOCATION_REMOVED,0,1,1,nil,e,tp) Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,g,1,0,0) end function c38492752.spop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.SpecialSummon(tc,0,tp,tp,false,false,POS_FACEUP) end end
gpl-2.0
MalRD/darkstar
scripts/zones/Rabao/npcs/Leodarion.lua
9
3252
----------------------------------- -- Area: Rabao -- NPC: Leodarion -- Involved in Quest: 20 in Pirate Years, I'll Take the Big Box, True Will -- !pos -50 8 40 247 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); local ID = require("scripts/zones/Rabao/IDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.I_LL_TAKE_THE_BIG_BOX) == QUEST_ACCEPTED and player:getCharVar("illTakeTheBigBoxCS") == 2) then if (trade:hasItemQty(17098,1) and trade:getItemCount() == 1) then -- Trade Oak Pole player:startEvent(92); end end end; function onTrigger(player,npc) if (player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.I_LL_TAKE_THE_BIG_BOX) == QUEST_ACCEPTED) then illTakeTheBigBoxCS = player:getCharVar("illTakeTheBigBoxCS"); if (illTakeTheBigBoxCS == 1) then player:startEvent(90); elseif (illTakeTheBigBoxCS == 2) then player:startEvent(91); elseif (illTakeTheBigBoxCS == 3 and VanadielDayOfTheYear() == player:getCharVar("illTakeTheBigBox_Timer")) then player:startEvent(93); elseif (illTakeTheBigBoxCS == 3) then player:startEvent(94); elseif (illTakeTheBigBoxCS == 4) then player:startEvent(95); end elseif (player:getQuestStatus(OUTLANDS,dsp.quest.id.outlands.TRUE_WILL) == QUEST_ACCEPTED) then trueWillCS = player:getCharVar("trueWillCS"); if (trueWillCS == 1) then player:startEvent(97); elseif (trueWillCS == 2 and player:hasKeyItem(dsp.ki.LARGE_TRICK_BOX) == false) then player:startEvent(98); elseif (player:hasKeyItem(dsp.ki.LARGE_TRICK_BOX)) then player:startEvent(99); end else player:startEvent(89); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 90) then player:setCharVar("illTakeTheBigBoxCS",2); elseif (csid == 92) then player:tradeComplete(); player:setCharVar("illTakeTheBigBox_Timer",VanadielDayOfTheYear()); player:setCharVar("illTakeTheBigBoxCS",3); elseif (csid == 94) then player:setCharVar("illTakeTheBigBox_Timer",0); player:setCharVar("illTakeTheBigBoxCS",4); player:addKeyItem(dsp.ki.SEANCE_STAFF); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.SEANCE_STAFF); elseif (csid == 97) then player:delKeyItem(dsp.ki.OLD_TRICK_BOX); player:setCharVar("trueWillCS",2); elseif (csid == 99) then if (player:getFreeSlotsCount() < 1) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,13782); else player:delKeyItem(dsp.ki.LARGE_TRICK_BOX); player:addItem(13782); player:messageSpecial(ID.text.ITEM_OBTAINED,13782); -- Ninja Chainmail player:setCharVar("trueWillCS",0); player:addFame(NORG,30); player:completeQuest(OUTLANDS,dsp.quest.id.outlands.TRUE_WILL); end end end;
gpl-3.0
maxrio/luci981213
modules/luci-base/luasrc/sys/zoneinfo/tzoffset.lua
14
4023
-- Licensed to the public under the Apache License 2.0. module "luci.sys.zoneinfo.tzoffset" OFFSET = { gmt = 0, -- GMT eat = 10800, -- EAT cet = 3600, -- CET wat = 3600, -- WAT cat = 7200, -- CAT eet = 7200, -- EET wet = 0, -- WET sast = 7200, -- SAST hst = -36000, -- HST hdt = -32400, -- HDT akst = -32400, -- AKST akdt = -28800, -- AKDT ast = -14400, -- AST brt = -10800, -- BRT art = -10800, -- ART pyt = -14400, -- PYT pyst = -10800, -- PYST est = -18000, -- EST cst = -21600, -- CST cdt = -18000, -- CDT amt = -14400, -- AMT cot = -18000, -- COT mst = -25200, -- MST mdt = -21600, -- MDT vet = -16200, -- VET gft = -10800, -- GFT pst = -28800, -- PST pdt = -25200, -- PDT act = -18000, -- ACT wgt = -10800, -- WGT wgst = -7200, -- WGST ect = -18000, -- ECT gyt = -14400, -- GYT bot = -14400, -- BOT pet = -18000, -- PET pmst = -10800, -- PMST pmdt = -7200, -- PMDT uyt = -10800, -- UYT fnt = -7200, -- FNT srt = -10800, -- SRT clt = -10800, -- CLT egt = -3600, -- EGT egst = 0, -- EGST nst = -12600, -- NST ndt = -9000, -- NDT awst = 28800, -- AWST davt = 25200, -- DAVT ddut = 36000, -- DDUT mist = 39600, -- MIST mawt = 18000, -- MAWT nzst = 43200, -- NZST nzdt = 46800, -- NZDT rott = -10800, -- ROTT syot = 10800, -- SYOT utc = 0, -- UTC vost = 21600, -- VOST almt = 21600, -- ALMT anat = 43200, -- ANAT aqtt = 18000, -- AQTT tmt = 18000, -- TMT azt = 14400, -- AZT azst = 18000, -- AZST ict = 25200, -- ICT kgt = 21600, -- KGT bnt = 28800, -- BNT irkt = 28800, -- IRKT chot = 28800, -- CHOT chost = 32400, -- CHOST ist = 19800, -- IST bdt = 21600, -- BDT tlt = 32400, -- TLT gst = 14400, -- GST tjt = 18000, -- TJT hkt = 28800, -- HKT hovt = 25200, -- HOVT hovst = 28800, -- HOVST wib = 25200, -- WIB wit = 32400, -- WIT aft = 16200, -- AFT pett = 43200, -- PETT pkt = 18000, -- PKT npt = 20700, -- NPT yakt = 32400, -- YAKT krat = 25200, -- KRAT myt = 28800, -- MYT magt = 36000, -- MAGT wita = 28800, -- WITA pht = 28800, -- PHT novt = 21600, -- NOVT omst = 21600, -- OMST orat = 18000, -- ORAT kst = 30600, -- KST qyzt = 21600, -- QYZT mmt = 23400, -- MMT sakt = 36000, -- SAKT uzt = 18000, -- UZT sgt = 28800, -- SGT sret = 39600, -- SRET get = 14400, -- GET btt = 21600, -- BTT jst = 32400, -- JST ulat = 28800, -- ULAT ulast = 32400, -- ULAST xjt = 21600, -- XJT vlat = 36000, -- VLAT yekt = 18000, -- YEKT azot = -3600, -- AZOT azost = 0, -- AZOST cvt = -3600, -- CVT fkst = -10800, -- FKST acst = 34200, -- ACST acdt = 37800, -- ACDT aest = 36000, -- AEST acwst = 31500, -- ACWST lhst = 37800, -- LHST lhdt = 39600, -- LHDT msk = 10800, -- MSK samt = 14400, -- SAMT iot = 21600, -- IOT cxt = 25200, -- CXT cct = 23400, -- CCT tft = 18000, -- TFT sct = 14400, -- SCT mvt = 18000, -- MVT mut = 14400, -- MUT ret = 14400, -- RET wsst = 46800, -- WSST wsdt = 50400, -- WSDT bst = 39600, -- BST chast = 45900, -- CHAST chadt = 49500, -- CHADT chut = 36000, -- CHUT east = -18000, -- EAST vut = 39600, -- VUT phot = 46800, -- PHOT tkt = 46800, -- TKT fjt = 43200, -- FJT fjst = 46800, -- FJST tvt = 43200, -- TVT galt = -21600, -- GALT gamt = -32400, -- GAMT sbt = 39600, -- SBT lint = 50400, -- LINT kost = 39600, -- KOST mht = 43200, -- MHT mart = -34200, -- MART sst = -39600, -- SST nrt = 43200, -- NRT nut = -39600, -- NUT nft = 39600, -- NFT nct = 39600, -- NCT pwt = 32400, -- PWT pont = 39600, -- PONT pgt = 36000, -- PGT ckt = -36000, -- CKT taht = -36000, -- TAHT gilt = 43200, -- GILT tot = 46800, -- TOT wakt = 43200, -- WAKT wft = 43200, -- WFT }
apache-2.0
sagarwaghmare69/nn
SpatialConvolutionMap.lua
22
4220
local SpatialConvolutionMap, parent = torch.class('nn.SpatialConvolutionMap', 'nn.Module') nn.tables = nn.tables or {} function nn.tables.full(nin, nout) local ft = torch.Tensor(nin*nout,2) local p = 1 for j=1,nout do for i=1,nin do ft[p][1] = i ft[p][2] = j p = p + 1 end end return ft end function nn.tables.oneToOne(nfeat) local ft = torch.Tensor(nfeat,2) for i=1,nfeat do ft[i][1] = i ft[i][2] = i end return ft end function nn.tables.random(nin, nout, nto) local nker = nto * nout local tbl = torch.Tensor(nker, 2) local fi = torch.randperm(nin) local frcntr = 1 local nfi = math.floor(nin/nto) -- number of distinct nto chunks local totbl = tbl:select(2,2) local frtbl = tbl:select(2,1) local fitbl = fi:narrow(1, 1, (nfi * nto)) -- part of fi that covers distinct chunks local ufrtbl= frtbl:unfold(1, nto, nto) local utotbl= totbl:unfold(1, nto, nto) local ufitbl= fitbl:unfold(1, nto, nto) -- start filling frtbl for i=1,nout do -- fro each unit in target map ufrtbl:select(1,i):copy(ufitbl:select(1,frcntr)) frcntr = frcntr + 1 if frcntr-1 == nfi then -- reset fi fi:copy(torch.randperm(nin)) frcntr = 1 end end for tocntr=1,utotbl:size(1) do utotbl:select(1,tocntr):fill(tocntr) end return tbl end function SpatialConvolutionMap:__init(conMatrix, kW, kH, dW, dH) parent.__init(self) dW = dW or 1 dH = dH or 1 self.kW = kW self.kH = kH self.dW = dW self.dH = dH self.connTable = conMatrix self.nInputPlane = self.connTable:select(2,1):max() self.nOutputPlane = self.connTable:select(2,2):max() self.weight = torch.Tensor(self.connTable:size(1), kH, kW) self.bias = torch.Tensor(self.nOutputPlane) self.gradWeight = torch.Tensor(self.connTable:size(1), kH, kW) self.gradBias = torch.Tensor(self.nOutputPlane) self:reset() end function SpatialConvolutionMap:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) 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 else local ninp = torch.Tensor(self.nOutputPlane):zero() for i=1,self.connTable:size(1) do ninp[self.connTable[i][2]] = ninp[self.connTable[i][2]]+1 end for k=1,self.connTable:size(1) do stdv = 1/math.sqrt(self.kW*self.kH*ninp[self.connTable[k][2]]) if nn.oldSeed then self.weight:select(1,k):apply(function() return torch.uniform(-stdv,stdv) end) else self.weight:select(1,k):uniform(-stdv,stdv) end end for k=1,self.bias:size(1) do stdv = 1/math.sqrt(self.kW*self.kH*ninp[k]) self.bias[k] = torch.uniform(-stdv,stdv) end end end function SpatialConvolutionMap:updateOutput(input) input.THNN.SpatialConvolutionMap_updateOutput( input:cdata(), self.output:cdata(), self.weight:cdata(), self.bias:cdata(), self.connTable:cdata(), self.nInputPlane, self.nOutputPlane, self.dW, self.dH ) return self.output end function SpatialConvolutionMap:updateGradInput(input, gradOutput) input.THNN.SpatialConvolutionMap_updateGradInput( input:cdata(), gradOutput:cdata(), self.gradInput:cdata(), self.weight:cdata(), self.bias:cdata(), self.connTable:cdata(), self.nInputPlane, self.nOutputPlane, self.dW, self.dH ) return self.gradInput end function SpatialConvolutionMap:accGradParameters(input, gradOutput, scale) input.THNN.SpatialConvolutionMap_accGradParameters( input:cdata(), gradOutput:cdata(), self.gradWeight:cdata(), self.gradBias:cdata(), self.connTable:cdata(), self.nInputPlane, self.nOutputPlane, self.dW, self.dH, scale or 1 ) end function SpatialConvolutionMap:decayParameters(decay) self.weight:add(-decay, self.weight) self.bias:add(-decay, self.bias) end
bsd-3-clause
Death15/Test
plugins/Groups.lua
1
1555
do -- Checks if bot was disabled on specific chat local function is_channel_disabled(receiver) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end local function enable_channel(receiver) if not _config.disabled_channels then _config.disabled_channels = {} end if _config.disabled_channels[receiver] == nil then return 'Group is not disabled' end _config.disabled_channels[receiver] = false save_config() return 'Group re-enabled' end local function pre_process(msg) -- If sender is a moderator then re-enable the channel if is_mod(msg.from.id, msg.to.id) then if msg.text == 'group +' then enable_channel(get_receiver(msg)) end end if is_channel_disabled(get_receiver(msg)) then msg.text = '' end return msg end local function run(msg, matches) -- Enable a group if matches[1] == '+' then return enable_channel(get_receiver(msg)) end -- Disable a group if matches[1] == '-' then if not _config.disabled_channels then _config.disabled_channels = {} end _config.disabled_channels[get_receiver(msg)] = true save_config() return 'Group Has Been Disabled!' end end return { description = 'Plugin .', usage = { }, patterns = { "^[!/](group) (+)$", "^[!/](group) (-)$" }, run = run, moderated = true, pre_process = pre_process } end
gpl-2.0
MalRD/darkstar
scripts/globals/items/black_ghost.lua
11
1050
----------------------------------------- -- ID: 5138 -- Item: Black Ghost -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 4 -- Mind -6 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if (target:getRace() ~= dsp.race.MITHRA) then result = dsp.msg.basic.CANNOT_EAT end if (target:getMod(dsp.mod.EAT_RAW_FISH) == 1) then result = 0 end if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,300,5138) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, 4) target:addMod(dsp.mod.MND, -6) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 4) target:delMod(dsp.mod.MND, -6) end
gpl-3.0
MalRD/darkstar
scripts/zones/The_Garden_of_RuHmet/bcnms/when_angels_fall.lua
9
1414
----------------------------------- -- Area: The_Garden_of_RuHmet -- Name: When Angels Fall ----------------------------------- require("scripts/globals/battlefield") require("scripts/globals/missions") ----------------------------------- function onBattlefieldTick(battlefield, tick) dsp.battlefield.onBattlefieldTick(battlefield, tick) end function onBattlefieldRegister(player, battlefield) end function onBattlefieldEnter(player, battlefield) end function onBattlefieldLeave(player, battlefield, leavecode) if leavecode == dsp.battlefield.leaveCode.WON then local name, clearTime, partySize = battlefield:getRecord() local arg8 = (player:getCurrentMission(COP) ~= dsp.mission.id.cop.WHEN_ANGELS_FALL or player:getCharVar("PromathiaStatus") ~= 4) and 1 or 0 player:startEvent(32001, battlefield:getArea(), clearTime, partySize, battlefield:getTimeInside(), 0, battlefield:getLocalVar("[cs]bit"), arg8) elseif leavecode == dsp.battlefield.leaveCode.LOST then player:startEvent(32002) end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) if csid== 32001 then if player:getCurrentMission(COP) == dsp.mission.id.cop.WHEN_ANGELS_FALL and player:getCharVar("PromathiaStatus") == 4 then player:setCharVar("PromathiaStatus", 5) end player:setPos(420, 0, 445, 192) end end
gpl-3.0
robertbrook/Penlight
tests/test-lapp.lua
5
4622
local test = require 'pl.test' local lapp = require 'pl.lapp' local utils = require 'pl.utils' local tablex = require 'pl.tablex' local k = 1 function check (spec,args,match) local args = lapp(spec,args) for k,v in pairs(args) do if type(v) == 'userdata' then args[k]:close(); args[k] = '<file>' end end test.asserteq(args,match,nil,1) end -- force Lapp to throw an error, rather than just calling os.exit() lapp.show_usage_error = 'throw' function check_error(spec,args,msg) arg = args local ok,err = pcall(lapp,spec) test.assertmatch(err,msg) end local parmtest = [[ Testing 'array' parameter handling -o,--output... (string) -v... ]] check (parmtest,{'-o','one'},{output={'one'},v={false}}) check (parmtest,{'-o','one','-v'},{output={'one'},v={true}}) check (parmtest,{'-o','one','-vv'},{output={'one'},v={true,true}}) check (parmtest,{'-o','one','-o','two'},{output={'one','two'},v={false}}) local simple = [[ Various flags and option types -p A simple optional flag, defaults to false -q,--quiet A simple flag with long name -o (string) A required option with argument <input> (default stdin) Optional input file parameter... ]] check(simple, {'-o','in'}, {quiet=false,p=false,o='in',input='<file>'}) check(simple, {'-o','help','-q','test-lapp.lua'}, {quiet=true,p=false,o='help',input='<file>',input_name='test-lapp.lua'}) local longs = [[ --open (string) ]] check(longs,{'--open','folder'},{open='folder'}) local extras1 = [[ <files...> (string) A bunch of files ]] check(extras1,{'one','two'},{files={'one','two'}}) -- any extra parameters go into the array part of the result local extras2 = [[ <file> (string) A file ]] check(extras2,{'one','two'},{file='one','two'}) local extended = [[ --foo (string default 1) -s,--speed (slow|medium|fast default medium) -n (1..10 default 1) -p print -v verbose ]] check(extended,{},{foo='1',speed='medium',n=1,p=false,v=false}) check(extended,{'-pv'},{foo='1',speed='medium',n=1,p=true,v=true}) check(extended,{'--foo','2','-s','fast'},{foo='2',speed='fast',n=1,p=false,v=false}) check(extended,{'--foo=2','-s=fast','-n2'},{foo='2',speed='fast',n=2,p=false,v=false}) check_error(extended,{'--speed','massive'},"value 'massive' not in slow|medium|fast") check_error(extended,{'-n','x'},"unable to convert to number: x") check_error(extended,{'-n','12'},"n out of range") local with_dashes = [[ --first-dash dash --second-dash dash also ]] check(with_dashes,{'--first-dash'},{first_dash=true,second_dash=false}) -- optional parameters don't have to be set local optional = [[ -p (optional string) ]] check(optional,{'-p', 'test'},{p='test'}) check(optional,{},{}) -- boolean flags may have a true default... local false_flag = [[ -g group results -f (default true) force result ]] check (false_flag,{},{f=true,g=false}) check (false_flag,{'-g','-f'},{f=false,g=true}) local addtype = [[ -l (intlist) List of items ]] -- defining a custom type lapp.add_type('intlist', function(x) return tablex.imap(tonumber, utils.split(x, '%s*,%s*')) end, function(x) for _,v in ipairs(x) do lapp.assert(math.ceil(v) == v,'not an integer!') end end) check(addtype,{'-l', '1,2,3'},{l={1,2,3}}) check_error(addtype,{'-l', '1.5,2,3'},"not an integer!") -- short flags may be immediately followed by their value -- (previously only true for numerical values) local short_args = [[ -n (default 10) -I,--include (string) ]] check(short_args,{'-Ifrodo','-n5'},{include='frodo',n=5}) check(short_args,{'-I/usr/local/lua/5.1'},{include='/usr/local/lua/5.1',n=10}) -- ok, introducing _slack_ mode ;) -- 'short' flags may have multiple characters! (this is otherwise an error) -- Note that in _any case_ flags may contain hyphens, but these are turned -- into underscores for convenience. lapp.slack = true local spec = [[ Does some calculations -vs,--video-set (string) Use the German road sign dataset -w,--width (default 256) Width of the video -h,--height (default 144) Height of the video -t,--time (default 10) Seconds of video to process -sk,--seek (default 0) Seek number of seconds -dbg Debug! ]] test.asserteq(lapp(spec,{'-vs',200,'-sk',1}),{ video_set = 200, time = 10, height = 144, seek = 1, dbg = false, width = 256 })
mit
MalRD/darkstar
scripts/zones/Windurst_Waters/npcs/Ohbiru-Dohbiru.lua
9
10499
----------------------------------- -- Area: Windurst Waters -- NPC: Ohbiru-Dohbiru -- Involved in quest: Food For Thought, Say It with Flowers -- Starts and finishes quest: Toraimarai Turmoil ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/titles"); require("scripts/globals/common"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); local ID = require("scripts/zones/Windurst_Waters/IDs"); function onTrade(player,npc,trade) local turmoil = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.TORAIMARAI_TURMOIL); local count = trade:getItemCount(); if (player:getQuestStatus(WINDURST,dsp.quest.id.windurst.WATER_WAY_TO_GO) == QUEST_ACCEPTED) then if (trade:hasItemQty(4351,1) and count == 1) then player:startEvent(355,900); end elseif (player:getQuestStatus(WINDURST,dsp.quest.id.windurst.FOOD_FOR_THOUGHT) == QUEST_ACCEPTED) then local OhbiruFood = player:getCharVar("Ohbiru_Food_var"); if (trade:hasItemQty(4493,1) == true and trade:hasItemQty(4408,1) == true and trade:hasItemQty(624,1) == true and count == 3) then if (OhbiruFood < 2) then -- Traded all 3 items & Didn't ask for order if (math.random(1,2) == 1) then player:startEvent(325,440); else player:startEvent(326); end elseif (OhbiruFood == 2) then -- Traded all 3 items after receiving order player:startEvent(322,440); end end elseif (turmoil == QUEST_ACCEPTED) then if (count == 3 and trade:getGil() == 0 and trade:hasItemQty(906,3) == true) then --Check that all 3 items have been traded player:startEvent(791); else player:startEvent(786,4500,267,906); -- Reminder of needed items end elseif (turmoil == QUEST_COMPLETED) then if (count == 3 and trade:getGil() == 0 and trade:hasItemQty(906,3) == true) then --Check that all 3 items have been traded player:startEvent(791); else player:startEvent(795,4500,0,906); -- Reminder of needed items for repeated quest end end end; function onTrigger(player,npc) -- Check for Missions first (priority?) -- If the player has started the mission or not local pfame = player:getFameLevel(WINDURST); local turmoil = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.TORAIMARAI_TURMOIL); local FoodForThought = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.FOOD_FOR_THOUGHT); local needToZone = player:needToZone(); local OhbiruFood = player:getCharVar("Ohbiru_Food_var"); -- Variable to track progress of Ohbiru-Dohbiru in Food for Thought local waterWayToGo = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.WATER_WAY_TO_GO); local overnightDelivery = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.OVERNIGHT_DELIVERY); local SayFlowers = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.SAY_IT_WITH_FLOWERS); local FlowerProgress = player:getCharVar("FLOWER_PROGRESS"); local blueRibbonBlues = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.BLUE_RIBBON_BLUES) if (player:getCurrentMission(COP) == dsp.mission.id.cop.THE_ROAD_FORKS and player:getCharVar("MEMORIES_OF_A_MAIDEN_Status")==2) then player:startEvent(872); elseif (player:getCurrentMission(WINDURST) == dsp.mission.id.windurst.THE_PRICE_OF_PEACE) then if (player:getCharVar("ohbiru_dohbiru_talk") == 1) then player:startEvent(143); else player:startEvent(144); end elseif ((SayFlowers == QUEST_ACCEPTED or SayFlowers == QUEST_COMPLETED) and FlowerProgress == 1) then if (needToZone) then player:startEvent(518); elseif (player:getCharVar("FLOWER_PROGRESS") == 2) then player:startEvent(517,0,0,0,0,950); else player:startEvent(516,0,0,0,0,950); end elseif (waterWayToGo == QUEST_COMPLETED and needToZone) then player:startEvent(356,0,4351); elseif (waterWayToGo == QUEST_ACCEPTED) then if (player:hasItem(504) == false and player:hasItem(4351) == false) then player:startEvent(354); else player:startEvent(353); end elseif (waterWayToGo == QUEST_AVAILABLE and overnightDelivery == QUEST_COMPLETED and pfame >= 3) then player:startEvent(352,0,4351); elseif (FoodForThought == QUEST_AVAILABLE and OhbiruFood == 0) then player:startEvent(308); -- Hungry; mentions the experiment. First step in quest for this NPC. player:setCharVar("Ohbiru_Food_var",1); elseif (FoodForThought == QUEST_AVAILABLE and OhbiruFood == 1) then player:startEvent(309); -- Hungry. The NPC complains of being hungry before the quest is active. elseif (FoodForThought == QUEST_ACCEPTED and OhbiruFood < 2) then player:startEvent(316,0,4493,624,4408); -- Gives Order player:setCharVar("Ohbiru_Food_var",2); elseif (FoodForThought == QUEST_ACCEPTED and OhbiruFood == 2) then player:startEvent(317,0,4493,624,4408); -- Repeats Order elseif (FoodForThought == QUEST_ACCEPTED and OhbiruFood == 3) then player:startEvent(324); -- Reminds player to check on friends if he has been given his food. elseif (FoodForThought == QUEST_COMPLETED and needToZone == true) then player:startEvent(344); -- Post Food for Thought Dialogue elseif (overnightDelivery == QUEST_COMPLETED and pfame < 6) then player:startEvent(351); -- Post Overnight Delivery Dialogue -- -- Begin Toraimarai Turmoil Section -- elseif blueRibbonBlues == QUEST_COMPLETED and turmoil == QUEST_AVAILABLE and pfame >= 6 and needToZone == false then player:startEvent(785,4500,267,906); elseif (turmoil == QUEST_ACCEPTED) then player:startEvent(786,4500,267,906); -- Reminder of needed items elseif (turmoil == QUEST_COMPLETED) then player:startEvent(795,4500,0,906); -- Allows player to initiate repeat of Toraimarai Turmoil else player:startEvent(344); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) local tabre = { [0] = { itemid = 948, gil = 300 }, -- Carnation [1] = { itemid = 941, gil = 200 }, -- Red Rose [2] = { itemid = 949, gil = 250 }, -- Rain Lily [3] = { itemid = 956, gil = 150 }, -- Lilac [4] = { itemid = 957, gil = 200 }, -- Amaryllis [5] = { itemid = 958, gil = 100 } -- Marguerite } -- Check Missions first (priority?) local turmoil = player:getQuestStatus(WINDURST,dsp.quest.id.windurst.TORAIMARAI_TURMOIL); if (csid == 143) then player:setCharVar("ohbiru_dohbiru_talk",2); elseif (csid == 322 or csid == 325 or csid == 326) then player:tradeComplete(); player:addGil(GIL_RATE*440); if (player:getCharVar("Kerutoto_Food_var") == 2 and player:getCharVar("Kenapa_Food_var") == 4) then -- If this is the last NPC to be fed player:completeQuest(WINDURST,dsp.quest.id.windurst.FOOD_FOR_THOUGHT); player:addFame(WINDURST,100); player:addTitle(dsp.title.FAST_FOOD_DELIVERER); player:needToZone(true); player:setCharVar("Kerutoto_Food_var",0); -- ------------------------------------------ player:setCharVar("Kenapa_Food_var",0); -- Erase all the variables used in this quest player:setCharVar("Ohbiru_Food_var",0); -- ------------------------------------------ else -- If this is NOT the last NPC given food, flag this NPC as completed. player:setCharVar("Ohbiru_Food_var",3); end elseif (csid == 785 and option == 1) then -- Adds Toraimarai turmoil player:addQuest(WINDURST,dsp.quest.id.windurst.TORAIMARAI_TURMOIL); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.RHINOSTERY_CERTIFICATE); player:addKeyItem(dsp.ki.RHINOSTERY_CERTIFICATE); -- Rhinostery Certificate elseif (csid == 791 and turmoil == QUEST_ACCEPTED) then -- Completes Toraimarai turmoil - first time player:addGil(GIL_RATE*4500); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*4500); player:completeQuest(WINDURST,dsp.quest.id.windurst.TORAIMARAI_TURMOIL); player:addFame(WINDURST,100); player:addTitle(dsp.title.CERTIFIED_RHINOSTERY_VENTURER); player:tradeComplete(); elseif (csid == 791 and turmoil == 2) then -- Completes Toraimarai turmoil - repeats player:addGil(GIL_RATE*4500); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*4500); player:addFame(WINDURST,50); player:tradeComplete(); elseif (csid == 352 and option == 0 or csid == 354) then if (player:getFreeSlotsCount() >= 1) then if (player:getQuestStatus(WINDURST,dsp.quest.id.windurst.WATER_WAY_TO_GO) == QUEST_AVAILABLE) then player:addQuest(WINDURST,dsp.quest.id.windurst.WATER_WAY_TO_GO); end player:addItem(504); player:messageSpecial(ID.text.ITEM_OBTAINED,504); else player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,504); end elseif (csid == 355) then player:addGil(GIL_RATE*900); player:completeQuest(WINDURST,dsp.quest.id.windurst.WATER_WAY_TO_GO); player:addFame(WINDURST,40); player:tradeComplete(); player:needToZone(true); elseif (csid == 872) then player:setCharVar("MEMORIES_OF_A_MAIDEN_Status",3); elseif (csid == 516) then if (option < 7) then local choice = tabre[option]; if (choice and player:getGil() >= choice.gil) then if (player:getFreeSlotsCount() > 0) then player:addItem(choice.itemid) player:messageSpecial(ID.text.ITEM_OBTAINED,choice.itemid); player:delGil(choice.gil); player:needToZone(true); else player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,choice.itemid); end else player:messageSpecial(ID.text.NOT_HAVE_ENOUGH_GIL); end elseif (option == 7) then player:setCharVar("FLOWER_PROGRESS",2); end end end;
gpl-3.0
MalRD/darkstar
scripts/globals/items/green_curry_bun_+1.lua
11
1556
----------------------------------------- -- ID: 5762 -- Item: green_curry_bun_+1 -- Food Effect: 60 min, All Races ----------------------------------------- -- TODO: Group effects -- VIT +3 -- AGI +4 -- Ranged Accuracy +10% (cap 25) -- DEF +13% (cap 180) -- Resist Sleep +5 -- hHP +6 -- hMP +3 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,3600,5762) end function onEffectGain(target,effect) target:addMod(dsp.mod.VIT, 3) target:addMod(dsp.mod.AGI, 4) target:addMod(dsp.mod.FOOD_RACCP, 10) target:addMod(dsp.mod.FOOD_RACC_CAP, 25) target:addMod(dsp.mod.FOOD_DEFP, 13) target:addMod(dsp.mod.FOOD_DEF_CAP, 180) target:addMod(dsp.mod.SLEEPRES, 5) target:addMod(dsp.mod.HPHEAL, 6) target:addMod(dsp.mod.MPHEAL, 3) end function onEffectLose(target, effect) target:delMod(dsp.mod.VIT, 3) target:delMod(dsp.mod.AGI, 4) target:delMod(dsp.mod.FOOD_RACCP, 10) target:delMod(dsp.mod.FOOD_RACC_CAP, 25) target:delMod(dsp.mod.FOOD_DEFP, 13) target:delMod(dsp.mod.FOOD_DEF_CAP, 180) target:delMod(dsp.mod.SLEEPRES, 5) target:delMod(dsp.mod.HPHEAL, 6) target:delMod(dsp.mod.MPHEAL, 3) end
gpl-3.0
MalRD/darkstar
scripts/globals/spells/quick_etude.lua
12
1841
----------------------------------------- -- Spell: Quick Etude -- Static AGI Boost, BRD 28 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/magic") require("scripts/globals/msg") ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0 end function onSpellCast(caster,target,spell) local sLvl = caster:getSkillLevel(dsp.skill.SINGING) -- Gets skill level of Singing local iLvl = caster:getWeaponSkillLevel(dsp.slot.RANGED) local power = 0 if (sLvl+iLvl <= 181) then power = 3 elseif ((sLvl+iLvl >= 182) and (sLvl+iLvl <= 235)) then power = 4 elseif ((sLvl+iLvl >= 236) and (sLvl+iLvl <= 288)) then power = 5 elseif ((sLvl+iLvl >= 289) and (sLvl+iLvl <= 342)) then power = 6 elseif ((sLvl+iLvl >= 343) and (sLvl+iLvl <= 396)) then power = 7 elseif ((sLvl+iLvl >= 397) and (sLvl+iLvl <= 449)) then power = 8 elseif (sLvl+iLvl >= 450) then power = 9 end local iBoost = caster:getMod(dsp.mod.ETUDE_EFFECT) + caster:getMod(dsp.mod.ALL_SONGS_EFFECT) power = power + iBoost if (caster:hasStatusEffect(dsp.effect.SOUL_VOICE)) then power = power * 2 elseif (caster:hasStatusEffect(dsp.effect.MARCATO)) then power = power * 1.5 end caster:delStatusEffect(dsp.effect.MARCATO) local duration = 120 duration = duration * ((iBoost * 0.1) + (caster:getMod(dsp.mod.SONG_DURATION_BONUS)/100) + 1) if (caster:hasStatusEffect(dsp.effect.TROUBADOUR)) then duration = duration * 2 end if not (target:addBardSong(caster,dsp.effect.ETUDE,power,0,duration,caster:getID(), dsp.mod.AGI, 1)) then spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end return dsp.effect.ETUDE end
gpl-3.0
nmabhi/Webface
demos/vis-outputs.lua
11
2580
#!/usr/bin/env th -- -- Copyright 2015-2016 Carnegie Mellon University -- -- Licensed under the Apache License, Version 2.0 (the "License"); -- you may not use this file except in compliance with the License. -- You may obtain a copy of the License at -- -- http://www.apache.org/licenses/LICENSE-2.0 -- -- Unless required by applicable law or agreed to in writing, software -- distributed under the License is distributed on an "AS IS" BASIS, -- WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. -- See the License for the specific language governing permissions and -- limitations under the License. require 'torch' require 'nn' require 'dpnn' require 'image' require 'paths' torch.setdefaulttensortype('torch.FloatTensor') local cmd = torch.CmdLine() cmd:text() cmd:text('Visualize OpenFace outputs.') cmd:text() cmd:text('Options:') cmd:option('-imgPath', 'images/examples-aligned/lennon-1.png', 'Path to aligned image.') cmd:option('-filterOutput', 'images/examples-aligned/lennon-1', 'Output directory.') cmd:option('-model', './models/openface/nn4.small2.v1.t7', 'Path to model.') cmd:option('-imgDim', 96, 'Image dimension. nn1=224, nn4=96') cmd:option('-numPreview', 39, 'Number of images to preview') cmd:text() opt = cmd:parse(arg or {}) -- print(opt) os.execute('mkdir -p ' .. opt.filterOutput) if not paths.filep(opt.imgPath) then print("Unable to find: " .. opt.imgPath) os.exit(-1) end net = torch.load(opt.model) net:evaluate() print(net) local img = torch.Tensor(1, 3, opt.imgDim, opt.imgDim) local img_orig = image.load(opt.imgPath, 3) img[1] = image.scale(img_orig, opt.imgDim, opt.imgDim) net:forward(img) local fName = opt.filterOutput .. '/preview.html' print("Outputting filter preview to '" .. fName .. "'") f, err = io.open(fName, 'w') if err then print("Error: Unable to open preview.html"); os.exit(-1) end torch.IntTensor({3, 7, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21}):apply(function (i) os.execute(string.format('mkdir -p %s/%s', opt.filterOutput, i)) out = net.modules[i].output[1] f:write(string.format("<h1>Layer %s</h1>\n", i)) for j = 1,out:size(1) do imgName = string.format('%s/%d/%d.png', opt.filterOutput, i, j) image.save(imgName, out[j]) if j <= opt.numPreview then f:write(string.format("<img src='%d/%d.png' width='96px'></img>\n", i, j)) end end end)
apache-2.0
Lsty/ygopro-scripts
c24221808.lua
3
2743
--メンタルオーバー・デーモン function c24221808.initial_effect(c) --synchro summon aux.AddSynchroProcedure(c,aux.FilterBoolFunction(Card.IsRace,RACE_PSYCHO),aux.NonTuner(Card.IsRace,RACE_PSYCHO),2) c:EnableReviveLimit() --remove local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(24221808,0)) e1:SetCategory(CATEGORY_REMOVE) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetTarget(c24221808.rmtg) e1:SetOperation(c24221808.rmop) c:RegisterEffect(e1) local sg=Group.CreateGroup() sg:KeepAlive() e1:SetLabelObject(sg) --spsummon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(24221808,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_TO_GRAVE) e2:SetCondition(c24221808.spcon) e2:SetTarget(c24221808.sptg) e2:SetOperation(c24221808.spop) e2:SetLabelObject(sg) c:RegisterEffect(e2) end function c24221808.rmfilter(c) return c:IsRace(RACE_PSYCHO) and c:IsAbleToRemove() end function c24221808.rmtg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_GRAVE) and chkc:IsControler(tp) and c24221808.rmfilter(chkc) end if chk==0 then return Duel.IsExistingTarget(c24221808.rmfilter,tp,LOCATION_GRAVE,0,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectTarget(tp,c24221808.rmfilter,tp,LOCATION_GRAVE,0,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0) end function c24221808.rmop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then Duel.Remove(tc,POS_FACEUP,REASON_EFFECT) if c:IsRelateToEffect(e) then local sg=e:GetLabelObject() if c:GetFlagEffect(24221808)==0 then sg:Clear() c:RegisterFlagEffect(24221808,RESET_EVENT+0x1680000,0,1) end sg:AddCard(tc) tc:CreateRelation(c,RESET_EVENT+0x1fe0000) end end end function c24221808.spcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():IsPreviousLocation(LOCATION_ONFIELD) and e:GetHandler():GetFlagEffect(24221808)~=0 end function c24221808.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_REMOVED) end function c24221808.spfilter(c,rc,e,tp) return c:IsRelateToCard(rc) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) end function c24221808.spop(e,tp,eg,ep,ev,re,r,rp) local g=e:GetLabelObject() local ft=Duel.GetLocationCount(tp,LOCATION_MZONE) if ft<=0 then return end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local sg=g:FilterSelect(tp,c24221808.spfilter,ft,ft,nil,e:GetHandler(),e,tp) Duel.SpecialSummon(sg,0,tp,tp,false,false,POS_FACEUP) end
gpl-2.0
kevinlowrie/wrk
deps/luajit/src/jit/bcsave.lua
87
18141
---------------------------------------------------------------------------- -- LuaJIT module to save/list bytecode. -- -- Copyright (C) 2005-2015 Mike Pall. All rights reserved. -- Released under the MIT license. See Copyright Notice in luajit.h ---------------------------------------------------------------------------- -- -- This module saves or lists the bytecode for an input file. -- It's run by the -b command line option. -- ------------------------------------------------------------------------------ local jit = require("jit") assert(jit.version_num == 20004, "LuaJIT core/library version mismatch") local bit = require("bit") -- Symbol name prefix for LuaJIT bytecode. local LJBC_PREFIX = "luaJIT_BC_" ------------------------------------------------------------------------------ local function usage() io.stderr:write[[ Save LuaJIT bytecode: luajit -b[options] input output -l Only list bytecode. -s Strip debug info (default). -g Keep debug info. -n name Set module name (default: auto-detect from input name). -t type Set output file type (default: auto-detect from output name). -a arch Override architecture for object files (default: native). -o os Override OS for object files (default: native). -e chunk Use chunk string as input. -- Stop handling options. - Use stdin as input and/or stdout as output. File types: c h obj o raw (default) ]] os.exit(1) end local function check(ok, ...) if ok then return ok, ... end io.stderr:write("luajit: ", ...) io.stderr:write("\n") os.exit(1) end local function readfile(input) if type(input) == "function" then return input end if input == "-" then input = nil end return check(loadfile(input)) end local function savefile(name, mode) if name == "-" then return io.stdout end return check(io.open(name, mode)) end ------------------------------------------------------------------------------ local map_type = { raw = "raw", c = "c", h = "h", o = "obj", obj = "obj", } local map_arch = { x86 = true, x64 = true, arm = true, ppc = true, ppcspe = true, mips = true, mipsel = true, } local map_os = { linux = true, windows = true, osx = true, freebsd = true, netbsd = true, openbsd = true, dragonfly = true, solaris = true, } local function checkarg(str, map, err) str = string.lower(str) local s = check(map[str], "unknown ", err) return s == true and str or s end local function detecttype(str) local ext = string.match(string.lower(str), "%.(%a+)$") return map_type[ext] or "raw" end local function checkmodname(str) check(string.match(str, "^[%w_.%-]+$"), "bad module name") return string.gsub(str, "[%.%-]", "_") end local function detectmodname(str) if type(str) == "string" then local tail = string.match(str, "[^/\\]+$") if tail then str = tail end local head = string.match(str, "^(.*)%.[^.]*$") if head then str = head end str = string.match(str, "^[%w_.%-]+") else str = nil end check(str, "cannot derive module name, use -n name") return string.gsub(str, "[%.%-]", "_") end ------------------------------------------------------------------------------ local function bcsave_tail(fp, output, s) local ok, err = fp:write(s) if ok and output ~= "-" then ok, err = fp:close() end check(ok, "cannot write ", output, ": ", err) end local function bcsave_raw(output, s) local fp = savefile(output, "wb") bcsave_tail(fp, output, s) end local function bcsave_c(ctx, output, s) local fp = savefile(output, "w") if ctx.type == "c" then fp:write(string.format([[ #ifdef _cplusplus extern "C" #endif #ifdef _WIN32 __declspec(dllexport) #endif const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname)) else fp:write(string.format([[ #define %s%s_SIZE %d static const char %s%s[] = { ]], LJBC_PREFIX, ctx.modname, #s, LJBC_PREFIX, ctx.modname)) end local t, n, m = {}, 0, 0 for i=1,#s do local b = tostring(string.byte(s, i)) m = m + #b + 1 if m > 78 then fp:write(table.concat(t, ",", 1, n), ",\n") n, m = 0, #b + 1 end n = n + 1 t[n] = b end bcsave_tail(fp, output, table.concat(t, ",", 1, n).."\n};\n") end local function bcsave_elfobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint32_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF32header; typedef struct { uint8_t emagic[4], eclass, eendian, eversion, eosabi, eabiversion, epad[7]; uint16_t type, machine; uint32_t version; uint64_t entry, phofs, shofs; uint32_t flags; uint16_t ehsize, phentsize, phnum, shentsize, shnum, shstridx; } ELF64header; typedef struct { uint32_t name, type, flags, addr, ofs, size, link, info, align, entsize; } ELF32sectheader; typedef struct { uint32_t name, type; uint64_t flags, addr, ofs, size; uint32_t link, info; uint64_t align, entsize; } ELF64sectheader; typedef struct { uint32_t name, value, size; uint8_t info, other; uint16_t sectidx; } ELF32symbol; typedef struct { uint32_t name; uint8_t info, other; uint16_t sectidx; uint64_t value, size; } ELF64symbol; typedef struct { ELF32header hdr; ELF32sectheader sect[6]; ELF32symbol sym[2]; uint8_t space[4096]; } ELF32obj; typedef struct { ELF64header hdr; ELF64sectheader sect[6]; ELF64symbol sym[2]; uint8_t space[4096]; } ELF64obj; ]] local symname = LJBC_PREFIX..ctx.modname local is64, isbe = false, false if ctx.arch == "x64" then is64 = true elseif ctx.arch == "ppc" or ctx.arch == "ppcspe" or ctx.arch == "mips" then isbe = true end -- Handle different host/target endianess. local function f32(x) return x end local f16, fofs = f32, f32 if ffi.abi("be") ~= isbe then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end if is64 then local two32 = ffi.cast("int64_t", 2^32) function fofs(x) return bit.bswap(x)*two32 end else fofs = f32 end end -- Create ELF object and fill in header. local o = ffi.new(is64 and "ELF64obj" or "ELF32obj") local hdr = o.hdr if ctx.os == "bsd" or ctx.os == "other" then -- Determine native hdr.eosabi. local bf = assert(io.open("/bin/ls", "rb")) local bs = bf:read(9) bf:close() ffi.copy(o, bs, 9) check(hdr.emagic[0] == 127, "no support for writing native object files") else hdr.emagic = "\127ELF" hdr.eosabi = ({ freebsd=9, netbsd=2, openbsd=12, solaris=6 })[ctx.os] or 0 end hdr.eclass = is64 and 2 or 1 hdr.eendian = isbe and 2 or 1 hdr.eversion = 1 hdr.type = f16(1) hdr.machine = f16(({ x86=3, x64=62, arm=40, ppc=20, ppcspe=20, mips=8, mipsel=8 })[ctx.arch]) if ctx.arch == "mips" or ctx.arch == "mipsel" then hdr.flags = 0x50001006 end hdr.version = f32(1) hdr.shofs = fofs(ffi.offsetof(o, "sect")) hdr.ehsize = f16(ffi.sizeof(hdr)) hdr.shentsize = f16(ffi.sizeof(o.sect[0])) hdr.shnum = f16(6) hdr.shstridx = f16(2) -- Fill in sections and symbols. local sofs, ofs = ffi.offsetof(o, "space"), 1 for i,name in ipairs{ ".symtab", ".shstrtab", ".strtab", ".rodata", ".note.GNU-stack", } do local sect = o.sect[i] sect.align = fofs(1) sect.name = f32(ofs) ffi.copy(o.space+ofs, name) ofs = ofs + #name+1 end o.sect[1].type = f32(2) -- .symtab o.sect[1].link = f32(3) o.sect[1].info = f32(1) o.sect[1].align = fofs(8) o.sect[1].ofs = fofs(ffi.offsetof(o, "sym")) o.sect[1].entsize = fofs(ffi.sizeof(o.sym[0])) o.sect[1].size = fofs(ffi.sizeof(o.sym)) o.sym[1].name = f32(1) o.sym[1].sectidx = f16(4) o.sym[1].size = fofs(#s) o.sym[1].info = 17 o.sect[2].type = f32(3) -- .shstrtab o.sect[2].ofs = fofs(sofs) o.sect[2].size = fofs(ofs) o.sect[3].type = f32(3) -- .strtab o.sect[3].ofs = fofs(sofs + ofs) o.sect[3].size = fofs(#symname+1) ffi.copy(o.space+ofs+1, symname) ofs = ofs + #symname + 2 o.sect[4].type = f32(1) -- .rodata o.sect[4].flags = fofs(2) o.sect[4].ofs = fofs(sofs + ofs) o.sect[4].size = fofs(#s) o.sect[5].type = f32(1) -- .note.GNU-stack o.sect[5].ofs = fofs(sofs + ofs + #s) -- Write ELF object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_peobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint16_t arch, nsects; uint32_t time, symtabofs, nsyms; uint16_t opthdrsz, flags; } PEheader; typedef struct { char name[8]; uint32_t vsize, vaddr, size, ofs, relocofs, lineofs; uint16_t nreloc, nline; uint32_t flags; } PEsection; typedef struct __attribute((packed)) { union { char name[8]; uint32_t nameref[2]; }; uint32_t value; int16_t sect; uint16_t type; uint8_t scl, naux; } PEsym; typedef struct __attribute((packed)) { uint32_t size; uint16_t nreloc, nline; uint32_t cksum; uint16_t assoc; uint8_t comdatsel, unused[3]; } PEsymaux; typedef struct { PEheader hdr; PEsection sect[2]; // Must be an even number of symbol structs. PEsym sym0; PEsymaux sym0aux; PEsym sym1; PEsymaux sym1aux; PEsym sym2; PEsym sym3; uint32_t strtabsize; uint8_t space[4096]; } PEobj; ]] local symname = LJBC_PREFIX..ctx.modname local is64 = false if ctx.arch == "x86" then symname = "_"..symname elseif ctx.arch == "x64" then is64 = true end local symexport = " /EXPORT:"..symname..",DATA " -- The file format is always little-endian. Swap if the host is big-endian. local function f32(x) return x end local f16 = f32 if ffi.abi("be") then f32 = bit.bswap function f16(x) return bit.rshift(bit.bswap(x), 16) end end -- Create PE object and fill in header. local o = ffi.new("PEobj") local hdr = o.hdr hdr.arch = f16(({ x86=0x14c, x64=0x8664, arm=0x1c0, ppc=0x1f2, mips=0x366, mipsel=0x366 })[ctx.arch]) hdr.nsects = f16(2) hdr.symtabofs = f32(ffi.offsetof(o, "sym0")) hdr.nsyms = f32(6) -- Fill in sections and symbols. o.sect[0].name = ".drectve" o.sect[0].size = f32(#symexport) o.sect[0].flags = f32(0x00100a00) o.sym0.sect = f16(1) o.sym0.scl = 3 o.sym0.name = ".drectve" o.sym0.naux = 1 o.sym0aux.size = f32(#symexport) o.sect[1].name = ".rdata" o.sect[1].size = f32(#s) o.sect[1].flags = f32(0x40300040) o.sym1.sect = f16(2) o.sym1.scl = 3 o.sym1.name = ".rdata" o.sym1.naux = 1 o.sym1aux.size = f32(#s) o.sym2.sect = f16(2) o.sym2.scl = 2 o.sym2.nameref[1] = f32(4) o.sym3.sect = f16(-1) o.sym3.scl = 2 o.sym3.value = f32(1) o.sym3.name = "@feat.00" -- Mark as SafeSEH compliant. ffi.copy(o.space, symname) local ofs = #symname + 1 o.strtabsize = f32(ofs + 4) o.sect[0].ofs = f32(ffi.offsetof(o, "space") + ofs) ffi.copy(o.space + ofs, symexport) ofs = ofs + #symexport o.sect[1].ofs = f32(ffi.offsetof(o, "space") + ofs) -- Write PE object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, ffi.sizeof(o)-4096+ofs)) bcsave_tail(fp, output, s) end local function bcsave_machobj(ctx, output, s, ffi) ffi.cdef[[ typedef struct { uint32_t magic, cputype, cpusubtype, filetype, ncmds, sizeofcmds, flags; } mach_header; typedef struct { mach_header; uint32_t reserved; } mach_header_64; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint32_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command; typedef struct { uint32_t cmd, cmdsize; char segname[16]; uint64_t vmaddr, vmsize, fileoff, filesize; uint32_t maxprot, initprot, nsects, flags; } mach_segment_command_64; typedef struct { char sectname[16], segname[16]; uint32_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2; } mach_section; typedef struct { char sectname[16], segname[16]; uint64_t addr, size; uint32_t offset, align, reloff, nreloc, flags; uint32_t reserved1, reserved2, reserved3; } mach_section_64; typedef struct { uint32_t cmd, cmdsize, symoff, nsyms, stroff, strsize; } mach_symtab_command; typedef struct { int32_t strx; uint8_t type, sect; int16_t desc; uint32_t value; } mach_nlist; typedef struct { uint32_t strx; uint8_t type, sect; uint16_t desc; uint64_t value; } mach_nlist_64; typedef struct { uint32_t magic, nfat_arch; } mach_fat_header; typedef struct { uint32_t cputype, cpusubtype, offset, size, align; } mach_fat_arch; typedef struct { struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[1]; mach_nlist sym_entry; uint8_t space[4096]; } mach_obj; typedef struct { struct { mach_header_64 hdr; mach_segment_command_64 seg; mach_section_64 sec; mach_symtab_command sym; } arch[1]; mach_nlist_64 sym_entry; uint8_t space[4096]; } mach_obj_64; typedef struct { mach_fat_header fat; mach_fat_arch fat_arch[4]; struct { mach_header hdr; mach_segment_command seg; mach_section sec; mach_symtab_command sym; } arch[4]; mach_nlist sym_entry; uint8_t space[4096]; } mach_fat_obj; ]] local symname = '_'..LJBC_PREFIX..ctx.modname local isfat, is64, align, mobj = false, false, 4, "mach_obj" if ctx.arch == "x64" then is64, align, mobj = true, 8, "mach_obj_64" elseif ctx.arch == "arm" then isfat, mobj = true, "mach_fat_obj" else check(ctx.arch == "x86", "unsupported architecture for OSX") end local function aligned(v, a) return bit.band(v+a-1, -a) end local be32 = bit.bswap -- Mach-O FAT is BE, supported archs are LE. -- Create Mach-O object and fill in header. local o = ffi.new(mobj) local mach_size = aligned(ffi.offsetof(o, "space")+#symname+2, align) local cputype = ({ x86={7}, x64={0x01000007}, arm={7,12,12,12} })[ctx.arch] local cpusubtype = ({ x86={3}, x64={3}, arm={3,6,9,11} })[ctx.arch] if isfat then o.fat.magic = be32(0xcafebabe) o.fat.nfat_arch = be32(#cpusubtype) end -- Fill in sections and symbols. for i=0,#cpusubtype-1 do local ofs = 0 if isfat then local a = o.fat_arch[i] a.cputype = be32(cputype[i+1]) a.cpusubtype = be32(cpusubtype[i+1]) -- Subsequent slices overlap each other to share data. ofs = ffi.offsetof(o, "arch") + i*ffi.sizeof(o.arch[0]) a.offset = be32(ofs) a.size = be32(mach_size-ofs+#s) end local a = o.arch[i] a.hdr.magic = is64 and 0xfeedfacf or 0xfeedface a.hdr.cputype = cputype[i+1] a.hdr.cpusubtype = cpusubtype[i+1] a.hdr.filetype = 1 a.hdr.ncmds = 2 a.hdr.sizeofcmds = ffi.sizeof(a.seg)+ffi.sizeof(a.sec)+ffi.sizeof(a.sym) a.seg.cmd = is64 and 0x19 or 0x1 a.seg.cmdsize = ffi.sizeof(a.seg)+ffi.sizeof(a.sec) a.seg.vmsize = #s a.seg.fileoff = mach_size-ofs a.seg.filesize = #s a.seg.maxprot = 1 a.seg.initprot = 1 a.seg.nsects = 1 ffi.copy(a.sec.sectname, "__data") ffi.copy(a.sec.segname, "__DATA") a.sec.size = #s a.sec.offset = mach_size-ofs a.sym.cmd = 2 a.sym.cmdsize = ffi.sizeof(a.sym) a.sym.symoff = ffi.offsetof(o, "sym_entry")-ofs a.sym.nsyms = 1 a.sym.stroff = ffi.offsetof(o, "sym_entry")+ffi.sizeof(o.sym_entry)-ofs a.sym.strsize = aligned(#symname+2, align) end o.sym_entry.type = 0xf o.sym_entry.sect = 1 o.sym_entry.strx = 1 ffi.copy(o.space+1, symname) -- Write Macho-O object file. local fp = savefile(output, "wb") fp:write(ffi.string(o, mach_size)) bcsave_tail(fp, output, s) end local function bcsave_obj(ctx, output, s) local ok, ffi = pcall(require, "ffi") check(ok, "FFI library required to write this file type") if ctx.os == "windows" then return bcsave_peobj(ctx, output, s, ffi) elseif ctx.os == "osx" then return bcsave_machobj(ctx, output, s, ffi) else return bcsave_elfobj(ctx, output, s, ffi) end end ------------------------------------------------------------------------------ local function bclist(input, output) local f = readfile(input) require("jit.bc").dump(f, savefile(output, "w"), true) end local function bcsave(ctx, input, output) local f = readfile(input) local s = string.dump(f, ctx.strip) local t = ctx.type if not t then t = detecttype(output) ctx.type = t end if t == "raw" then bcsave_raw(output, s) else if not ctx.modname then ctx.modname = detectmodname(input) end if t == "obj" then bcsave_obj(ctx, output, s) else bcsave_c(ctx, output, s) end end end local function docmd(...) local arg = {...} local n = 1 local list = false local ctx = { strip = true, arch = jit.arch, os = string.lower(jit.os), type = false, modname = false, } while n <= #arg do local a = arg[n] if type(a) == "string" and string.sub(a, 1, 1) == "-" and a ~= "-" then table.remove(arg, n) if a == "--" then break end for m=2,#a do local opt = string.sub(a, m, m) if opt == "l" then list = true elseif opt == "s" then ctx.strip = true elseif opt == "g" then ctx.strip = false else if arg[n] == nil or m ~= #a then usage() end if opt == "e" then if n ~= 1 then usage() end arg[1] = check(loadstring(arg[1])) elseif opt == "n" then ctx.modname = checkmodname(table.remove(arg, n)) elseif opt == "t" then ctx.type = checkarg(table.remove(arg, n), map_type, "file type") elseif opt == "a" then ctx.arch = checkarg(table.remove(arg, n), map_arch, "architecture") elseif opt == "o" then ctx.os = checkarg(table.remove(arg, n), map_os, "OS name") else usage() end end end else n = n + 1 end end if list then if #arg == 0 or #arg > 2 then usage() end bclist(arg[1], arg[2] or "-") else if #arg ~= 2 then usage() end bcsave(ctx, arg[1], arg[2]) end end ------------------------------------------------------------------------------ -- Public module functions. module(...) start = docmd -- Process -b command line option.
apache-2.0
T-L-N/Dev_TLN
libs/fakeredis.lua
650
40405
local unpack = table.unpack or unpack --- Bit operations local ok,bit if _VERSION == "Lua 5.3" then bit = (load [[ return { band = function(x, y) return x & y end, bor = function(x, y) return x | y end, bxor = function(x, y) return x ~ y end, bnot = function(x) return ~x end, rshift = function(x, n) return x >> n end, lshift = function(x, n) return x << n end, } ]])() else ok,bit = pcall(require,"bit") if not ok then bit = bit32 end end assert(type(bit) == "table", "module for bitops not found") --- default sleep local default_sleep do local ok, mod = pcall(require, "socket") if ok and type(mod) == "table" then default_sleep = mod.sleep else default_sleep = function(n) local t0 = os.clock() while true do local delta = os.clock() - t0 if (delta < 0) or (delta > n) then break end end end end end --- Helpers local xdefv = function(ktype) if ktype == "list" then return {head = 0, tail = 0} elseif ktype == "zset" then return { list = {}, set = {}, } else return {} end end local xgetr = function(self, k, ktype) if self.data[k] then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) assert(self.data[k].value) return self.data[k].value else return xdefv(ktype) end end local xgetw = function(self, k, ktype) if self.data[k] and self.data[k].value then assert( (self.data[k].ktype == ktype), "ERR Operation against a key holding the wrong kind of value" ) else self.data[k] = {ktype = ktype, value = xdefv(ktype)} end return self.data[k].value end local empty = function(self, k) local v, t = self.data[k].value, self.data[k].ktype if t == nil then return true elseif t == "string" then return not v[1] elseif (t == "hash") or (t == "set") then for _,_ in pairs(v) do return false end return true elseif t == "list" then return v.head == v.tail elseif t == "zset" then if #v.list == 0 then for _,_ in pairs(v.set) do error("incoherent") end return true else for _,_ in pairs(v.set) do return(false) end error("incoherent") end else error("unsupported") end end local cleanup = function(self, k) if empty(self, k) then self.data[k] = nil end end local is_integer = function(x) return (type(x) == "number") and (math.floor(x) == x) end local overflows = function(n) return (n > 2^53-1) or (n < -2^53+1) end local is_bounded_integer = function(x) return (is_integer(x) and (not overflows(x))) end local is_finite_number = function(x) return (type(x) == "number") and (x > -math.huge) and (x < math.huge) end local toint = function(x) if type(x) == "string" then x = tonumber(x) end return is_bounded_integer(x) and x or nil end local tofloat = function(x) if type(x) == "number" then return x end if type(x) ~= "string" then return nil end local r = tonumber(x) if r then return r end if x == "inf" or x == "+inf" then return math.huge elseif x == "-inf" then return -math.huge else return nil end end local tostr = function(x) if is_bounded_integer(x) then return string.format("%d", x) else return tostring(x) end end local char_bitcount = function(x) assert( (type(x) == "number") and (math.floor(x) == x) and (x >= 0) and (x < 256) ) local n = 0 while x ~= 0 do x = bit.band(x, x-1) n = n+1 end return n end local chkarg = function(x) if type(x) == "number" then x = tostr(x) end assert(type(x) == "string") return x end local chkargs = function(n, ...) local arg = {...} assert(#arg == n) for i=1,n do arg[i] = chkarg(arg[i]) end return unpack(arg) end local getargs = function(...) local arg = {...} local n = #arg; assert(n > 0) for i=1,n do arg[i] = chkarg(arg[i]) end return arg end local getargs_as_map = function(...) local arg, r = getargs(...), {} assert(#arg%2 == 0) for i=1,#arg,2 do r[arg[i]] = arg[i+1] end return r end local chkargs_wrap = function(f, n) assert( (type(f) == "function") and (type(n) == "number") ) return function(self, ...) return f(self, chkargs(n, ...)) end end local lset_to_list = function(s) local r = {} for v,_ in pairs(s) do r[#r+1] = v end return r end local nkeys = function(x) local r = 0 for _,_ in pairs(x) do r = r + 1 end return r end --- Commands -- keys local del = function(self, ...) local arg = getargs(...) local r = 0 for i=1,#arg do if self.data[arg[i]] then r = r + 1 end self.data[arg[i]] = nil end return r end local exists = function(self, k) return not not self.data[k] end local keys = function(self, pattern) assert(type(pattern) == "string") -- We want to convert the Redis pattern to a Lua pattern. -- Start by escaping dashes *outside* character classes. -- We also need to escape percents here. local t, p, n = {}, 1, #pattern local p1, p2 while true do p1, p2 = pattern:find("%[.+%]", p) if p1 then if p1 > p then t[#t+1] = {true, pattern:sub(p, p1-1)} end t[#t+1] = {false, pattern:sub(p1, p2)} p = p2+1 if p > n then break end else t[#t+1] = {true, pattern:sub(p, n)} break end end for i=1,#t do if t[i][1] then t[i] = t[i][2]:gsub("[%%%-]", "%%%0") else t[i] = t[i][2]:gsub("%%", "%%%%") end end -- Remaining Lua magic chars are: '^$().[]*+?' ; escape them except '*?[]' -- Then convert '\' to '%', '*' to '.*' and '?' to '.'. Leave '[]' as is. -- Wrap in '^$' to enforce bounds. local lp = "^" .. table.concat(t):gsub("[%^%$%(%)%.%+]", "%%%0") :gsub("\\", "%%"):gsub("%*", ".*"):gsub("%?", ".") .. "$" local r = {} for k,_ in pairs(self.data) do if k:match(lp) then r[#r+1] = k end end return r end local _type = function(self, k) return self.data[k] and self.data[k].ktype or "none" end local randomkey = function(self) local ks = lset_to_list(self.data) local n = #ks if n > 0 then return ks[math.random(1, n)] else return nil end end local rename = function(self, k, k2) assert((k ~= k2) and self.data[k]) self.data[k2] = self.data[k] self.data[k] = nil return true end local renamenx = function(self, k, k2) if self.data[k2] then return false else return rename(self, k, k2) end end -- strings local getrange, incrby, set local append = function(self, k, v) local x = xgetw(self, k, "string") x[1] = (x[1] or "") .. v return #x[1] end local bitcount = function(self, k, i1, i2) k = chkarg(k) local s if i1 or i2 then assert(i1 and i2, "ERR syntax error") s = getrange(self, k, i1, i2) else s = xgetr(self, k, "string")[1] or "" end local r, bytes = 0,{s:byte(1, -1)} for i=1,#bytes do r = r + char_bitcount(bytes[i]) end return r end local bitop = function(self, op, k, ...) assert(type(op) == "string") op = op:lower() assert( (op == "and") or (op == "or") or (op == "xor") or (op == "not"), "ERR syntax error" ) k = chkarg(k) local arg = {...} local good_arity = (op == "not") and (#arg == 1) or (#arg > 0) assert(good_arity, "ERR wrong number of arguments for 'bitop' command") local l, vals = 0, {} local s for i=1,#arg do s = xgetr(self, arg[i], "string")[1] or "" if #s > l then l = #s end vals[i] = s end if l == 0 then del(self, k) return 0 end local vector_mt = {__index=function() return 0 end} for i=1,#vals do vals[i] = setmetatable({vals[i]:byte(1, -1)}, vector_mt) end local r = {} if op == "not" then assert(#vals[1] == l) for i=1,l do r[i] = bit.band(bit.bnot(vals[1][i]), 0xff) end else local _op = bit["b" .. op] for i=1,l do local t = {} for j=1,#vals do t[j] = vals[j][i] end r[i] = _op(unpack(t)) end end set(self, k, string.char(unpack(r))) return l end local decr = function(self, k) return incrby(self, k, -1) end local decrby = function(self, k, n) n = toint(n) assert(n, "ERR value is not an integer or out of range") return incrby(self, k, -n) end local get = function(self, k) local x = xgetr(self, k, "string") return x[1] end local getbit = function(self, k, offset) k = chkarg(k) offset = toint(offset) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" if bytepos >= #s then return 0 end local char = s:sub(bytepos+1, bytepos+1):byte() return bit.band(bit.rshift(char, 7-bitpos), 1) end getrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetr(self, k, "string") x = x[1] or "" if i1 >= 0 then i1 = i1 + 1 end if i2 >= 0 then i2 = i2 + 1 end return x:sub(i1, i2) end local getset = function(self, k, v) local r = get(self, k) set(self, k, v) return r end local incr = function(self, k) return incrby(self, k, 1) end incrby = function(self, k, n) k, n = chkarg(k), toint(n) assert(n, "ERR value is not an integer or out of range") local x = xgetw(self, k, "string") local i = toint(x[1] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[1] = tostr(i) return i end local incrbyfloat = function(self, k, n) k, n = chkarg(k), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "string") local i = tofloat(x[1] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[1] = tostr(i) return i end local mget = function(self, ...) local arg, r = getargs(...), {} for i=1,#arg do r[i] = get(self, arg[i]) end return r end local mset = function(self, ...) local argmap = getargs_as_map(...) for k,v in pairs(argmap) do set(self, k, v) end return true end local msetnx = function(self, ...) local argmap = getargs_as_map(...) for k,_ in pairs(argmap) do if self.data[k] then return false end end for k,v in pairs(argmap) do set(self, k, v) end return true end set = function(self, k, v) self.data[k] = {ktype = "string", value = {v}} return true end local setbit = function(self, k, offset, b) k = chkarg(k) offset, b = toint(offset), toint(b) assert( (offset >= 0), "ERR bit offset is not an integer or out of range" ) assert( (b == 0) or (b == 1), "ERR bit is not an integer or out of range" ) local bitpos = offset % 8 -- starts at 0 local bytepos = (offset - bitpos) / 8 -- starts at 0 local s = xgetr(self, k, "string")[1] or "" local pad = {s} for i=2,bytepos+2-#s do pad[i] = "\0" end s = table.concat(pad) assert(#s >= bytepos+1) local before = s:sub(1, bytepos) local char = s:sub(bytepos+1, bytepos+1):byte() local after = s:sub(bytepos+2, -1) local old = bit.band(bit.rshift(char, 7-bitpos), 1) if b == 1 then char = bit.bor(bit.lshift(1, 7-bitpos), char) else char = bit.band(bit.bnot(bit.lshift(1, 7-bitpos)), char) end local r = before .. string.char(char) .. after set(self, k, r) return old end local setnx = function(self, k, v) if self.data[k] then return false else return set(self, k, v) end end local setrange = function(self, k, i, s) local k, s = chkargs(2, k, s) i = toint(i) assert(i and (i >= 0)) local x = xgetw(self, k, "string") local y = x[1] or "" local ly, ls = #y, #s if i > ly then -- zero padding local t = {} for i=1, i-ly do t[i] = "\0" end y = y .. table.concat(t) .. s else y = y:sub(1, i) .. s .. y:sub(i+ls+1, ly) end x[1] = y return #y end local strlen = function(self, k) local x = xgetr(self, k, "string") return x[1] and #x[1] or 0 end -- hashes local hdel = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local r = 0 local x = xgetw(self, k, "hash") for i=1,#arg do if x[arg[i]] then r = r + 1 end x[arg[i]] = nil end cleanup(self, k) return r end local hget local hexists = function(self, k, k2) return not not hget(self, k, k2) end hget = function(self, k, k2) local x = xgetr(self, k, "hash") return x[k2] end local hgetall = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,v in pairs(x) do r[_k] = v end return r end local hincrby = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), toint(n) assert(n, "ERR value is not an integer or out of range") assert(type(n) == "number") local x = xgetw(self, k, "hash") local i = toint(x[k2] or 0) assert(i, "ERR value is not an integer or out of range") i = i+n assert( (not overflows(i)), "ERR increment or decrement would overflow" ) x[k2] = tostr(i) return i end local hincrbyfloat = function(self, k, k2, n) k, k2, n = chkarg(k), chkarg(k2), tofloat(n) assert(n, "ERR value is not a valid float") local x = xgetw(self, k, "hash") local i = tofloat(x[k2] or 0) assert(i, "ERR value is not a valid float") i = i+n assert( is_finite_number(i), "ERR increment would produce NaN or Infinity" ) x[k2] = tostr(i) return i end local hkeys = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _k,_ in pairs(x) do r[#r+1] = _k end return r end local hlen = function(self, k) local x = xgetr(self, k, "hash") return nkeys(x) end local hmget = function(self, k, k2s) k = chkarg(k) assert((type(k2s) == "table")) local r = {} local x = xgetr(self, k, "hash") for i=1,#k2s do r[i] = x[chkarg(k2s[i])] end return r end local hmset = function(self, k, ...) k = chkarg(k) local arg = {...} if type(arg[1]) == "table" then assert(#arg == 1) local x = xgetw(self, k, "hash") for _k,v in pairs(arg[1]) do x[chkarg(_k)] = chkarg(v) end else assert(#arg % 2 == 0) local x = xgetw(self, k, "hash") local t = getargs(...) for i=1,#t,2 do x[t[i]] = t[i+1] end end return true end local hset = function(self, k, k2, v) local x = xgetw(self, k, "hash") local r = not x[k2] x[k2] = v return r end local hsetnx = function(self, k, k2, v) local x = xgetw(self, k, "hash") if x[k2] == nil then x[k2] = v return true else return false end end local hvals = function(self, k) local x = xgetr(self, k, "hash") local r = {} for _,v in pairs(x) do r[#r+1] = v end return r end -- lists (head = left, tail = right) local _l_real_i = function(x, i) if i < 0 then return x.tail+i+1 else return x.head+i+1 end end local _l_len = function(x) return x.tail - x.head end local _block_for = function(self, timeout) if timeout > 0 then local sleep = self.sleep or default_sleep if type(sleep) == "function" then sleep(timeout) else error("sleep function unavailable", 0) end else error("operation would block", 0) end end local rpoplpush local blpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpop = function(self, ...) local arg = {...} local timeout = toint(arg[#arg]) arg[#arg] = nil local vs = getargs(...) local x, l, k, v for i=1,#vs do k = vs[i] x = xgetw(self, k, "list") l = _l_len(x) if l > 0 then v = x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return {k, v} else self.data[k] = nil end end _block_for(self, timeout) end local brpoplpush = function(self, k1, k2, timeout) k1, k2 = chkargs(2, k1, k2) timeout = toint(timeout) if not self.data[k1] then _block_for(self, timeout) end return rpoplpush(self, k1, k2) end local lindex = function(self, k, i) k = chkarg(k) i = assert(toint(i)) local x = xgetr(self, k, "list") return x[_l_real_i(x, i)] end local linsert = function(self, k, mode, pivot, v) mode = mode:lower() assert((mode == "before") or (mode == "after")) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local p = nil for i=x.head+1, x.tail do if x[i] == pivot then p = i break end end if not p then return -1 end if mode == "after" then for i=x.head+1, p do x[i-1] = x[i] end x.head = x.head - 1 else for i=x.tail, p, -1 do x[i+1] = x[i] end x.tail = x.tail + 1 end x[p] = v return _l_len(x) end local llen = function(self, k) local x = xgetr(self, k, "list") return _l_len(x) end local lpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.head+1] if l > 1 then x.head = x.head + 1 x[x.head] = nil else self.data[k] = nil end return r end local lpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x[x.head] = vs[i] x.head = x.head - 1 end return _l_len(x) end local lpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x[x.head] = v x.head = x.head - 1 return _l_len(x) end local lrange = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x, r = xgetr(self, k, "list"), {} i1 = math.max(_l_real_i(x, i1), x.head+1) i2 = math.min(_l_real_i(x, i2), x.tail) for i=i1,i2 do r[#r+1] = x[i] end return r end local _lrem_i = function(x, p) for i=p,x.tail do x[i] = x[i+1] end x.tail = x.tail - 1 end local _lrem_l = function(x, v, s) assert(v) if not s then s = x.head+1 end for i=s,x.tail do if x[i] == v then _lrem_i(x, i) return i end end return false end local _lrem_r = function(x, v, s) assert(v) if not s then s = x.tail end for i=s,x.head+1,-1 do if x[i] == v then _lrem_i(x, i) return i end end return false end local lrem = function(self, k, count, v) k, v = chkarg(k), chkarg(v) count = assert(toint(count)) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") local n, last = 0, nil local op = (count < 0) and _lrem_r or _lrem_l local limited = (count ~= 0) count = math.abs(count) while true do last = op(x, v, last) if last then n = n+1 if limited then count = count - 1 if count == 0 then break end end else break end end return n end local lset = function(self, k, i, v) k, v = chkarg(k), chkarg(v) i = assert(toint(i)) if not self.data[k] then error("ERR no such key") end local x = xgetw(self, k, "list") local l = _l_len(x) if i >= l or i < -l then error("ERR index out of range") end x[_l_real_i(x, i)] = v return true end local ltrim = function(self, k, i1, i2) k = chkarg(k) i1, i2 = toint(i1), toint(i2) assert(i1 and i2) local x = xgetw(self, k, "list") i1, i2 = _l_real_i(x, i1), _l_real_i(x, i2) for i=x.head+1,i1-1 do x[i] = nil end for i=i2+1,x.tail do x[i] = nil end x.head = math.max(i1-1, x.head) x.tail = math.min(i2, x.tail) assert( (x[x.head] == nil) and (x[x.tail+1] == nil) ) cleanup(self, k) return true end local rpop = function(self, k) local x = xgetw(self, k, "list") local l, r = _l_len(x), x[x.tail] if l > 1 then x[x.tail] = nil x.tail = x.tail - 1 else self.data[k] = nil end return r end rpoplpush = function(self, k1, k2) local v = rpop(self, k1) if not v then return nil end lpush(self, k2, v) return v end local rpush = function(self, k, ...) local vs = getargs(...) local x = xgetw(self, k, "list") for i=1,#vs do x.tail = x.tail + 1 x[x.tail] = vs[i] end return _l_len(x) end local rpushx = function(self, k, v) if not self.data[k] then return 0 end local x = xgetw(self, k, "list") x.tail = x.tail + 1 x[x.tail] = v return _l_len(x) end -- sets local sadd = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if not x[arg[i]] then x[arg[i]] = true r = r + 1 end end return r end local scard = function(self, k) local x = xgetr(self, k, "set") return nkeys(x) end local _sdiff = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} for v,_ in pairs(x) do r[v] = true end for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = nil end end return r end local sdiff = function(self, k, ...) return lset_to_list(_sdiff(self, k, ...)) end local sdiffstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sdiff(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local _sinter = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x = xgetr(self, k, "set") local r = {} local y for v,_ in pairs(x) do r[v] = true for i=1,#arg do y = xgetr(self, arg[i], "set") if not y[v] then r[v] = nil; break end end end return r end local sinter = function(self, k, ...) return lset_to_list(_sinter(self, k, ...)) end local sinterstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sinter(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end local sismember = function(self, k, v) local x = xgetr(self, k, "set") return not not x[v] end local smembers = function(self, k) local x = xgetr(self, k, "set") return lset_to_list(x) end local smove = function(self, k, k2, v) local x = xgetr(self, k, "set") if x[v] then local y = xgetw(self, k2, "set") x[v] = nil y[v] = true return true else return false end end local spop = function(self, k) local x, r = xgetw(self, k, "set"), nil local l = lset_to_list(x) local n = #l if n > 0 then r = l[math.random(1, n)] x[r] = nil end cleanup(self, k) return r end local srandmember = function(self, k, count) k = chkarg(k) local x = xgetr(self, k, "set") local l = lset_to_list(x) local n = #l if not count then if n > 0 then return l[math.random(1, n)] else return nil end end count = toint(count) if (count == 0) or (n == 0) then return {} end if count >= n then return l end local r = {} if count > 0 then -- distinct elements for i=0,count-1 do r[#r+1] = table.remove(l, math.random(1, n-i)) end else -- allow repetition for i=1,-count do r[#r+1] = l[math.random(1, n)] end end return r end local srem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "set"), 0 for i=1,#arg do if x[arg[i]] then x[arg[i]] = nil r = r + 1 end end cleanup(self, k) return r end local _sunion = function(self, ...) local arg = getargs(...) local r = {} local x for i=1,#arg do x = xgetr(self, arg[i], "set") for v,_ in pairs(x) do r[v] = true end end return r end local sunion = function(self, k, ...) return lset_to_list(_sunion(self, k, ...)) end local sunionstore = function(self, k2, k, ...) k2 = chkarg(k2) local x = _sunion(self, k, ...) self.data[k2] = {ktype = "set", value = x} return nkeys(x) end -- zsets local _z_p_mt = { __eq = function(a, b) if a.v == b.v then assert(a.s == b.s) return true else return false end end, __lt = function(a, b) if a.s == b.s then return (a.v < b.v) else return (a.s < b.s) end end, } local _z_pair = function(s, v) assert( (type(s) == "number") and (type(v) == "string") ) local r = {s = s, v = v} return setmetatable(r, _z_p_mt) end local _z_pairs = function(...) local arg = {...} assert((#arg > 0) and (#arg % 2 == 0)) local ps = {} for i=1,#arg,2 do ps[#ps+1] = _z_pair( assert(tofloat(arg[i])), chkarg(arg[i+1]) ) end return ps end local _z_insert = function(x, ix, p) assert( (type(x) == "table") and (type(ix) == "number") and (type(p) == "table") ) local l = x.list table.insert(l, ix, p) for i=ix+1,#l do x.set[l[i].v] = x.set[l[i].v] + 1 end x.set[p.v] = ix end local _z_remove = function(x, v) if not x.set[v] then return false end local l, ix = x.list, x.set[v] assert(l[ix].v == v) table.remove(l, ix) for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - 1 end x.set[v] = nil return true end local _z_remove_range = function(x, i1, i2) local l = x.list i2 = i2 or i1 assert( (i1 > 0) and (i2 >= i1) and (i2 <= #l) ) local ix, n = i1, i2-i1+1 for i=1,n do x.set[l[ix].v] = nil table.remove(l, ix) end for i=ix,#l do x.set[l[i].v] = x.set[l[i].v] - n end return n end local _z_update = function(x, p) local l = x.list local found = _z_remove(x, p.v) local ix = nil for i=1,#l do if l[i] > p then ix = i; break end end if not ix then ix = #l+1 end _z_insert(x, ix, p) return found end local _z_coherence = function(x) local l, s = x.list, x.set local found, n = {}, 0 for val,pos in pairs(s) do if found[pos] then return false end found[pos] = true n = n + 1 if not (l[pos] and (l[pos].v == val)) then return false end end if #l ~= n then return false end for i=1, n-1 do if l[i].s > l[i+1].s then return false end end return true end local _z_normrange = function(l, i1, i2) i1, i2 = assert(toint(i1)), assert(toint(i2)) if i1 < 0 then i1 = #l+i1 end if i2 < 0 then i2 = #l+i2 end i1, i2 = math.max(i1+1, 1), i2+1 if (i2 < i1) or (i1 > #l) then return nil end i2 = math.min(i2, #l) return i1, i2 end local _zrbs_opts = function(...) local arg = {...} if #arg == 0 then return {} end local ix, opts = 1, {} while type(arg[ix]) == "string" do if arg[ix] == "withscores" then opts.withscores = true ix = ix + 1 elseif arg[ix] == "limit" then opts.limit = { offset = assert(toint(arg[ix+1])), count = assert(toint(arg[ix+2])), } ix = ix + 3 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.withscores = opts.withscores or _o.withscores if _o.limit then opts.limit = { offset = assert(toint(_o.limit.offset or _o.limit[1])), count = assert(toint(_o.limit.count or _o.limit[2])), } end ix = ix + 1 end assert(arg[ix] == nil) if opts.limit then assert( (opts.limit.count >= 0) and (opts.limit.offset >= 0) ) end return opts end local _z_store_params = function(dest, numkeys, ...) dest = chkarg(dest) numkeys = assert(toint(numkeys)) assert(numkeys > 0) local arg = {...} assert(#arg >= numkeys) local ks = {} for i=1, numkeys do ks[i] = chkarg(arg[i]) end local ix, opts = numkeys+1,{} while type(arg[ix]) == "string" do if arg[ix] == "weights" then opts.weights = {} ix = ix + 1 for i=1, numkeys do opts.weights[i] = assert(toint(arg[ix])) ix = ix + 1 end elseif arg[ix] == "aggregate" then opts.aggregate = assert(chkarg(arg[ix+1])) ix = ix + 2 else error("input") end end if type(arg[ix]) == "table" then local _o = arg[ix] opts.weights = opts.weights or _o.weights opts.aggregate = opts.aggregate or _o.aggregate ix = ix + 1 end assert(arg[ix] == nil) if opts.aggregate then assert( (opts.aggregate == "sum") or (opts.aggregate == "min") or (opts.aggregate == "max") ) else opts.aggregate = "sum" end if opts.weights then assert(#opts.weights == numkeys) for i=1,#opts.weights do assert(type(opts.weights[i]) == "number") end else opts.weights = {} for i=1, numkeys do opts.weights[i] = 1 end end opts.keys = ks opts.dest = dest return opts end local _zrbs_limits = function(x, s1, s2, descending) local s1_incl, s2_incl = true, true if s1:sub(1, 1) == "(" then s1, s1_incl = s1:sub(2, -1), false end s1 = assert(tofloat(s1)) if s2:sub(1, 1) == "(" then s2, s2_incl = s2:sub(2, -1), false end s2 = assert(tofloat(s2)) if descending then s1, s2 = s2, s1 s1_incl, s2_incl = s2_incl, s1_incl end if s2 < s1 then return nil end local l = x.list local i1, i2 local fst, lst = l[1].s, l[#l].s if (fst > s2) or ((not s2_incl) and (fst == s2)) then return nil end if (lst < s1) or ((not s1_incl) and (lst == s1)) then return nil end if (fst > s1) or (s1_incl and (fst == s1)) then i1 = 1 end if (lst < s2) or (s2_incl and (lst == s2)) then i2 = #l end for i=1,#l do if (i1 and i2) then break end if (not i1) then if l[i].s > s1 then i1 = i end if s1_incl and l[i].s == s1 then i1 = i end end if (not i2) then if l[i].s > s2 then i2 = i-1 end if (not s2_incl) and l[i].s == s2 then i2 = i-1 end end end assert(i1 and i2) if descending then return #l-i2, #l-i1 else return i1-1, i2-1 end end local dbg_zcoherence = function(self, k) local x = xgetr(self, k, "zset") return _z_coherence(x) end local zadd = function(self, k, ...) k = chkarg(k) local ps = _z_pairs(...) local x = xgetw(self, k, "zset") local n = 0 for i=1,#ps do if not _z_update(x, ps[i]) then n = n+1 end end return n end local zcard = function(self, k) local x = xgetr(self, k, "zset") return #x.list end local zcount = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return i2 - i1 + 1 end local zincrby = function(self, k, n, v) k,v = chkargs(2, k, v) n = assert(tofloat(n)) local x = xgetw(self, k, "zset") local p = x.list[x.set[v]] local s = p and (p.s + n) or n _z_update(x, _z_pair(s, v)) return s end local zinterstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local aggregate if params.aggregate == "sum" then aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then aggregate = math.min elseif params.aggregate == "max" then aggregate = math.max else error() end local y = xgetr(self, params.keys[1], "zset") local p1, p2 for j=1,#y.list do p1 = _z_pair(y.list[j].s, y.list[j].v) _z_update(x, p1) end for i=2,#params.keys do y = xgetr(self, params.keys[i], "zset") local to_remove, to_update = {}, {} for j=1,#x.list do p1 = x.list[j] if y.set[p1.v] then p2 = _z_pair( aggregate( p1.s, params.weights[i] * y.list[y.set[p1.v]].s ), p1.v ) to_update[#to_update+1] = p2 else to_remove[#to_remove+1] = p1.v end end for j=1,#to_remove do _z_remove(x, to_remove[j]) end for j=1,#to_update do _z_update(x, to_update[j]) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end local _zranger = function(descending) return function(self, k, i1, i2, opts) k = chkarg(k) local withscores = false if type(opts) == "table" then withscores = opts.withscores elseif type(opts) == "string" then assert(opts:lower() == "withscores") withscores = true else assert(opts == nil) end local x = xgetr(self, k, "zset") local l = x.list i1, i2 = _z_normrange(l, i1, i2) if not i1 then return {} end local inc = 1 if descending then i1 = #l - i1 + 1 i2 = #l - i2 + 1 inc = -1 end local r = {} if withscores then for i=i1, i2, inc do r[#r+1] = {l[i].v, l[i].s} end else for i=i1, i2, inc do r[#r+1] = l[i].v end end return r end end local zrange = _zranger(false) local zrevrange = _zranger(true) local _zrangerbyscore = function(descending) return function(self, k, s1, s2, ...) k, s1, s2 = chkargs(3, k, s1, s2) local opts = _zrbs_opts(...) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, descending) if not (i1 and i2) then return {} end if opts.limit then if opts.limit.count == 0 then return {} end i1 = i1 + opts.limit.offset if i1 > i2 then return {} end i2 = math.min(i2, i1+opts.limit.count-1) end if descending then return zrevrange(self, k, i1, i2, opts) else return zrange(self, k, i1, i2, opts) end end end local zrangebyscore = _zrangerbyscore(false) local zrevrangebyscore = _zrangerbyscore(true) local zrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return r-1 else return nil end end local zrem = function(self, k, ...) k = chkarg(k) local arg = getargs(...) local x, r = xgetw(self, k, "zset"), 0 for i=1,#arg do if _z_remove(x, arg[i]) then r = r + 1 end end cleanup(self, k) return r end local zremrangebyrank = function(self, k, i1, i2) k = chkarg(k) local x = xgetw(self, k, "zset") i1, i2 = _z_normrange(x.list, i1, i2) if not i1 then cleanup(self, k) return 0 end local n = _z_remove_range(x, i1, i2) cleanup(self, k) return n end local zremrangebyscore = function(self, k, s1, s2) local x = xgetr(self, k, "zset") local i1, i2 = _zrbs_limits(x, s1, s2, false) if not (i1 and i2) then return 0 end assert(i2 >= i1) return zremrangebyrank(self, k, i1, i2) end local zrevrank = function(self, k, v) local x = xgetr(self, k, "zset") local r = x.set[v] if r then return #x.list-r else return nil end end local zscore = function(self, k, v) local x = xgetr(self, k, "zset") local p = x.list[x.set[v]] if p then return p.s else return nil end end local zunionstore = function(self, ...) local params = _z_store_params(...) local x = xdefv("zset") local default_score, aggregate if params.aggregate == "sum" then default_score = 0 aggregate = function(x, y) return x+y end elseif params.aggregate == "min" then default_score = math.huge aggregate = math.min elseif params.aggregate == "max" then default_score = -math.huge aggregate = math.max else error() end local y, p1, p2 for i=1,#params.keys do y = xgetr(self, params.keys[i], "zset") for j=1,#y.list do p1 = y.list[j] p2 = _z_pair( aggregate( params.weights[i] * p1.s, x.set[p1.v] and x.list[x.set[p1.v]].s or default_score ), p1.v ) _z_update(x, p2) end end local r = #x.list if r > 0 then self.data[params.dest] = {ktype = "zset", value = x} end return r end -- connection local echo = function(self, v) return v end local ping = function(self) return true end -- server local flushdb = function(self) self.data = {} return true end --- Class local methods = { -- keys del = del, -- (...) -> #removed exists = chkargs_wrap(exists, 1), -- (k) -> exists? keys = keys, -- (pattern) -> list of keys ["type"] = chkargs_wrap(_type, 1), -- (k) -> [string|list|set|zset|hash|none] randomkey = randomkey, -- () -> [k|nil] rename = chkargs_wrap(rename, 2), -- (k,k2) -> true renamenx = chkargs_wrap(renamenx, 2), -- (k,k2) -> ! existed? k2 -- strings append = chkargs_wrap(append, 2), -- (k,v) -> #new bitcount = bitcount, -- (k,[start,end]) -> n bitop = bitop, -- ([and|or|xor|not],k,...) decr = chkargs_wrap(decr, 1), -- (k) -> new decrby = decrby, -- (k,n) -> new get = chkargs_wrap(get, 1), -- (k) -> [v|nil] getbit = getbit, -- (k,offset) -> b getrange = getrange, -- (k,start,end) -> string getset = chkargs_wrap(getset, 2), -- (k,v) -> [oldv|nil] incr = chkargs_wrap(incr, 1), -- (k) -> new incrby = incrby, -- (k,n) -> new incrbyfloat = incrbyfloat, -- (k,n) -> new mget = mget, -- (k1,...) -> {v1,...} mset = mset, -- (k1,v1,...) -> true msetnx = msetnx, -- (k1,v1,...) -> worked? (i.e. !existed? any k) set = chkargs_wrap(set, 2), -- (k,v) -> true setbit = setbit, -- (k,offset,b) -> old setnx = chkargs_wrap(setnx, 2), -- (k,v) -> worked? (i.e. !existed?) setrange = setrange, -- (k,offset,val) -> #new strlen = chkargs_wrap(strlen, 1), -- (k) -> [#v|0] -- hashes hdel = hdel, -- (k,sk1,...) -> #removed hexists = chkargs_wrap(hexists, 2), -- (k,sk) -> exists? hget = chkargs_wrap(hget,2), -- (k,sk) -> v hgetall = chkargs_wrap(hgetall, 1), -- (k) -> map hincrby = hincrby, -- (k,sk,n) -> new hincrbyfloat = hincrbyfloat, -- (k,sk,n) -> new hkeys = chkargs_wrap(hkeys, 1), -- (k) -> keys hlen = chkargs_wrap(hlen, 1), -- (k) -> [#sk|0] hmget = hmget, -- (k,{sk1,...}) -> {v1,...} hmset = hmset, -- (k,{sk1=v1,...}) -> true hset = chkargs_wrap(hset, 3), -- (k,sk1,v1) -> !existed? hsetnx = chkargs_wrap(hsetnx, 3), -- (k,sk1,v1) -> worked? (i.e. !existed?) hvals = chkargs_wrap(hvals, 1), -- (k) -> values -- lists blpop = blpop, -- (k1,...) -> k,v brpop = brpop, -- (k1,...) -> k,v brpoplpush = brpoplpush, -- (k1,k2,timeout) -> v lindex = lindex, -- (k,i) -> v linsert = chkargs_wrap(linsert, 4), -- (k,mode,pivot,v) -> #list (after) llen = chkargs_wrap(llen, 1), -- (k) -> #list lpop = chkargs_wrap(lpop, 1), -- (k) -> v lpush = lpush, -- (k,v1,...) -> #list (after) lpushx = chkargs_wrap(lpushx, 2), -- (k,v) -> #list (after) lrange = lrange, -- (k,start,stop) -> list lrem = lrem, -- (k,count,v) -> #removed lset = lset, -- (k,i,v) -> true ltrim = ltrim, -- (k,start,stop) -> true rpop = chkargs_wrap(rpop, 1), -- (k) -> v rpoplpush = chkargs_wrap(rpoplpush, 2), -- (k1,k2) -> v rpush = rpush, -- (k,v1,...) -> #list (after) rpushx = chkargs_wrap(rpushx, 2), -- (k,v) -> #list (after) -- sets sadd = sadd, -- (k,v1,...) -> #added scard = chkargs_wrap(scard, 1), -- (k) -> [n|0] sdiff = sdiff, -- (k1,...) -> set (of elements in k1 & not in any of ...) sdiffstore = sdiffstore, -- (k0,k1,...) -> #set at k0 sinter = sinter, -- (k1,...) -> set sinterstore = sinterstore, -- (k0,k1,...) -> #set at k0 sismember = chkargs_wrap(sismember, 2), -- (k,v) -> member? smembers = chkargs_wrap(smembers, 1), -- (k) -> set smove = chkargs_wrap(smove, 3), -- (k1,k2,v) -> moved? (i.e. !member? k1) spop = chkargs_wrap(spop, 1), -- (k) -> [v|nil] srandmember = srandmember, -- (k,[count]) -> v|[v1,v2,...] srem = srem, -- (k,v1,...) -> #removed sunion = sunion, -- (k1,...) -> set sunionstore = sunionstore, -- (k0,k1,...) -> #set at k0 -- zsets zadd = zadd, -- (k,score,member,[score,member,...]) zcard = chkargs_wrap(zcard, 1), -- (k) -> n zcount = chkargs_wrap(zcount, 3), -- (k,min,max) -> count zincrby = zincrby, -- (k,score,v) -> score zinterstore = zinterstore, -- (k,numkeys,k1,...,[opts]) -> card zrange = zrange, -- (k,start,stop,[opts]) -> depends on opts zrangebyscore = zrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrank = chkargs_wrap(zrank, 2), -- (k,v) -> rank zrem = zrem, -- (k,v1,...) -> #removed zremrangebyrank = zremrangebyrank, -- (k,start,stop) -> #removed zremrangebyscore = chkargs_wrap(zremrangebyscore, 3), -- (k,min,max) -> #removed zrevrange = zrevrange, -- (k,start,stop,[opts]) -> depends on opts zrevrangebyscore = zrevrangebyscore, -- (k,min,max,[opts]) -> depends on opts zrevrank = chkargs_wrap(zrevrank, 2), -- (k,v) -> rank zscore = chkargs_wrap(zscore, 2), -- (k,v) -> score zunionstore = zunionstore, -- (k,numkeys,k1,...,[opts]) -> card -- connection echo = chkargs_wrap(echo, 1), -- (v) -> v ping = ping, -- () -> true -- server flushall = flushdb, -- () -> true flushdb = flushdb, -- () -> true -- debug dbg_zcoherence = dbg_zcoherence, } local new = function() local r = {data = {}} return setmetatable(r,{__index = methods}) end return { new = new, }
gpl-2.0
sagarwaghmare69/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
Lsty/ygopro-scripts
c6799227.lua
5
1158
--ハーフ・カウンター function c6799227.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE) e1:SetCondition(c6799227.condition) e1:SetTarget(c6799227.target) e1:SetOperation(c6799227.activate) c:RegisterEffect(e1) end function c6799227.condition(e,tp,eg,ep,ev,re,r,rp) local t=Duel.GetAttackTarget() return t and t:IsControler(tp) end function c6799227.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) local tg=Duel.GetAttackTarget() if chkc then return chkc==tg end if chk==0 then return Duel.GetAttacker():IsOnField() and tg:IsCanBeEffectTarget(e) end Duel.SetTargetCard(tg) end function c6799227.activate(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() then local atk=Duel.GetAttacker():GetBaseAttack() local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_UPDATE_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e1:SetValue(atk/2) tc:RegisterEffect(e1) end end
gpl-2.0
Lsty/ygopro-scripts
c25955164.lua
3
1130
--雷魔神-サンガ function c25955164.initial_effect(c) --atkdown local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(25955164,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_QUICK_O) e1:SetRange(LOCATION_MZONE) e1:SetCode(EVENT_PRE_DAMAGE_CALCULATE) e1:SetProperty(EFFECT_FLAG_NO_TURN_RESET) e1:SetCountLimit(1) e1:SetCondition(c25955164.condition) e1:SetTarget(c25955164.target) e1:SetOperation(c25955164.operation) c:RegisterEffect(e1) end function c25955164.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()~=tp and Duel.GetAttackTarget()==e:GetHandler() end function c25955164.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetAttacker():IsCanBeEffectTarget(e) end Duel.SetTargetCard(Duel.GetAttacker()) end function c25955164.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK_FINAL) e1:SetReset(RESET_PHASE+RESET_DAMAGE_CAL) e1:SetValue(0) tc:RegisterEffect(e1) end end
gpl-2.0
MalRD/darkstar
scripts/zones/Ifrits_Cauldron/Zone.lua
8
1268
----------------------------------- -- -- Zone: Ifrits_Cauldron (205) -- ----------------------------------- local ID = require("scripts/zones/Ifrits_Cauldron/IDs") require("scripts/globals/conquest") require("scripts/globals/treasure") require("scripts/globals/helm") ----------------------------------- function onInitialize(zone) UpdateNMSpawnPoint(ID.mob.ASH_DRAGON) GetMobByID(ID.mob.ASH_DRAGON):setRespawnTime(math.random(900, 10800)) dsp.treasure.initZone(zone) dsp.helm.initZone(zone, dsp.helm.type.MINING) end function onConquestUpdate(zone, updatetype) dsp.conq.onConquestUpdate(zone, updatetype) end function onZoneIn(player, prevZone) local cs = -1 if player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0 then player:setPos(-60.296, 48.884, 105.967, 69) end return cs end function onRegionEnter(player, region) end function onGameHour(zone) -- Opens flame spouts every 3 hours Vana'diel time. Doors are offset from spouts by 5. if VanadielHour() % 3 == 0 then for i = 5, 8 do GetNPCByID(ID.npc.FLAME_SPOUT_OFFSET + i):openDoor(90) end end end function onEventUpdate(player, csid, option) end function onEventFinish(player, csid, option) end
gpl-3.0
Lsty/ygopro-scripts
c78266168.lua
3
1692
--ジャイアントマミー function c78266168.initial_effect(c) --turn set local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(78266168,0)) e1:SetCategory(CATEGORY_POSITION) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetTarget(c78266168.target) e1:SetOperation(c78266168.operation) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(78266168,1)) e2:SetCategory(CATEGORY_DESTROY) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_DAMAGE_STEP_END) e2:SetCondition(c78266168.descon) e2:SetTarget(c78266168.destg) e2:SetOperation(c78266168.desop) c:RegisterEffect(e2) end function c78266168.target(e,tp,eg,ep,ev,re,r,rp,chk) local c=e:GetHandler() if chk==0 then return c:IsCanTurnSet() and c:GetFlagEffect(78266168)==0 end c:RegisterFlagEffect(78266168,RESET_EVENT+0x1fc0000+RESET_PHASE+PHASE_END,0,1) Duel.SetOperationInfo(0,CATEGORY_POSITION,c,1,0,0) end function c78266168.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then Duel.ChangePosition(c,POS_FACEDOWN_DEFENCE) end end function c78266168.descon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetAttackTarget()==e:GetHandler() and e:GetHandler():GetBattlePosition()==POS_FACEDOWN_DEFENCE and Duel.GetAttacker():GetAttack()<e:GetHandler():GetDefence() end function c78266168.destg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_DESTROY,Duel.GetAttacker(),1,0,0) end function c78266168.desop(e,tp,eg,ep,ev,re,r,rp) local a=Duel.GetAttacker() if not a:IsRelateToBattle() then return end Duel.Destroy(a,REASON_EFFECT) end
gpl-2.0
shahabsaf1/My-system
plugins/wiki.lua
735
4364
-- http://git.io/vUA4M local socket = require "socket" local JSON = require "cjson" local wikiusage = { "!wiki [text]: Read extract from default Wikipedia (EN)", "!wiki(lang) [text]: Read extract from 'lang' Wikipedia. Example: !wikies hola", "!wiki search [text]: Search articles on default Wikipedia (EN)", "!wiki(lang) search [text]: Search articles on 'lang' Wikipedia. Example: !wikies search hola", } local Wikipedia = { -- http://meta.wikimedia.org/wiki/List_of_Wikipedias wiki_server = "https://%s.wikipedia.org", wiki_path = "/w/api.php", wiki_load_params = { action = "query", prop = "extracts", format = "json", exchars = 300, exsectionformat = "plain", explaintext = "", redirects = "" }, wiki_search_params = { action = "query", list = "search", srlimit = 20, format = "json", }, default_lang = "en", } function Wikipedia:getWikiServer(lang) return string.format(self.wiki_server, lang or self.default_lang) end --[[ -- return decoded JSON table from Wikipedia --]] function Wikipedia:loadPage(text, lang, intro, plain, is_search) local request, sink = {}, {} local query = "" local parsed if is_search then for k,v in pairs(self.wiki_search_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "srsearch=" .. URL.escape(text) else self.wiki_load_params.explaintext = plain and "" or nil for k,v in pairs(self.wiki_load_params) do query = query .. k .. '=' .. v .. '&' end parsed = URL.parse(self:getWikiServer(lang)) parsed.path = self.wiki_path parsed.query = query .. "titles=" .. URL.escape(text) end -- HTTP request request['url'] = URL.build(parsed) print(request['url']) request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) if not headers or not sink then return nil end local content = table.concat(sink) if content ~= "" then local ok, result = pcall(JSON.decode, content) if ok and result then return result else return nil end else return nil end end -- extract intro passage in wiki page function Wikipedia:wikintro(text, lang) local result = self:loadPage(text, lang, true, true) if result and result.query then local query = result.query if query and query.normalized then text = query.normalized[1].to or text end local page = query.pages[next(query.pages)] if page and page.extract then return text..": "..page.extract else local text = "Extract not found for "..text text = text..'\n'..table.concat(wikiusage, '\n') return text end else return "Sorry an error happened" end end -- search for term in wiki function Wikipedia:wikisearch(text, lang) local result = self:loadPage(text, lang, true, true, true) if result and result.query then local titles = "" for i,item in pairs(result.query.search) do titles = titles .. "\n" .. item["title"] end titles = titles ~= "" and titles or "No results found" return titles else return "Sorry, an error occurred" end end local function run(msg, matches) -- TODO: Remember language (i18 on future version) -- TODO: Support for non Wikipedias but Mediawikis local search, term, lang if matches[1] == "search" then search = true term = matches[2] lang = nil elseif matches[2] == "search" then search = true term = matches[3] lang = matches[1] else term = matches[2] lang = matches[1] end if not term then term = lang lang = nil end if term == "" then local text = "Usage:\n" text = text..table.concat(wikiusage, '\n') return text end local result if search then result = Wikipedia:wikisearch(term, lang) else -- TODO: Show the link result = Wikipedia:wikintro(term, lang) end return result end return { description = "Searches Wikipedia and send results", usage = wikiusage, patterns = { "^![Ww]iki(%w+) (search) (.+)$", "^![Ww]iki (search) ?(.*)$", "^![Ww]iki(%w+) (.+)$", "^![Ww]iki ?(.*)$" }, run = run }
gpl-2.0
MalRD/darkstar
scripts/globals/items/serving_of_herb_quus.lua
11
1090
----------------------------------------- -- ID: 4559 -- Item: serving_of_herb_quus -- Food Effect: 180Min, All Races ----------------------------------------- -- Dexterity 1 -- Mind -1 -- Ranged ACC % 7 -- Ranged ACC Cap 10 ----------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") ----------------------------------------- function onItemCheck(target) local result = 0 if target:hasStatusEffect(dsp.effect.FOOD) or target:hasStatusEffect(dsp.effect.FIELD_SUPPORT_FOOD) then result = dsp.msg.basic.IS_FULL end return result end function onItemUse(target) target:addStatusEffect(dsp.effect.FOOD,0,0,10800,4559) end function onEffectGain(target, effect) target:addMod(dsp.mod.DEX, 1) target:addMod(dsp.mod.MND, -1) target:addMod(dsp.mod.FOOD_RACCP, 7) target:addMod(dsp.mod.FOOD_RACC_CAP, 10) end function onEffectLose(target, effect) target:delMod(dsp.mod.DEX, 1) target:delMod(dsp.mod.MND, -1) target:delMod(dsp.mod.FOOD_RACCP, 7) target:delMod(dsp.mod.FOOD_RACC_CAP, 10) end
gpl-3.0
chu11/flux-core
t/job-manager/exec-service.lua
7
2713
#!/usr/bin/env lua ------------------------------------------------------------- -- Copyright 2019 Lawrence Livermore National Security, LLC -- (c.f. AUTHORS, NOTICE.LLNS, COPYING) -- -- This file is part of the Flux resource manager framework. -- For details, see https://github.com/flux-framework. -- -- SPDX-License-Identifier: LGPL-3.0 ------------------------------------------------------------- -- -- Simple test exec service in-a-script -- Run as "exec.lua servicename <job duration seconds>" -- local flux = require 'flux' local posix = require 'posix' local f = assert (flux.new()) local service = assert(arg[1], "Required service name argument") local timeout = arg[2] or 0. timeout = timeout * 1000. io.stdout:setvbuf("line") local function printf (...) io.stdout:write (string.format (...)) end local function die (...) io.stderr:write (string.format (...)) os.exit (1) end local jobs = {} local function job_complete (msg, id, rc) assert (msg:respond { id = id, type = "finish", data = {status = rc} }) assert (msg:respond { id = id, type = "release", data = {ranks = "all", final = true} }) jobs[id].timer:remove() jobs[id] = nil printf ("%s: finish: %d\n", service, id) end assert (f:msghandler { pattern = service .. ".start", msgtypes = { flux.MSGTYPE_REQUEST }, handler = function (f, msg, mh) local id = msg.data.id jobs[id] = { msg = msg } printf ("%s: start: %d\n", service, id) assert (msg:respond {id = id, type = "start", data = {}}) -- Launch job timer: jobs[id].timer = assert (f:timer { timeout = timeout, oneshot = true, handler = function () job_complete (msg, id, 0) end }) end }) assert (f:msghandler { pattern = "job-exception", msgtypes = { flux.MSGTYPE_EVENT }, handler = function (f, msg, mh) local id = msg.data.id printf ("%s: exeception for %d\n", service, id) if jobs[id] then job_complete (jobs[id].msg, id, 9) end end }) printf ("Adding service %s\n", service) local rc,err = f:rpc ("service.add", { service = service }) if not rc then die ("service.add: %s\n", err) end assert (f:subscribe ("job-exception")) local rc,err = f:rpc ("job-manager.exec-hello", { service = service }) if not rc then die ("job-manager.exec-hello: %s\n", err) end -- Synchronize with test driver by creating a ready key for this service -- in the kvs: os.execute ("flux kvs put test.exec-hello."..service.."=1") f:reactor () -- vi: ts=4 sw=4 expandtab
lgpl-3.0
Lsty/ygopro-scripts
c34230233.lua
3
2581
--暗黒界の龍神 グラファ function c34230233.initial_effect(c) --special summon local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD) e1:SetCode(EFFECT_SPSUMMON_PROC) e1:SetProperty(EFFECT_FLAG_UNCOPYABLE) e1:SetRange(LOCATION_GRAVE) e1:SetCondition(c34230233.spcon) e1:SetOperation(c34230233.spop) c:RegisterEffect(e1) --destroy local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(34230233,0)) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e2:SetProperty(EFFECT_FLAG_CARD_TARGET) e2:SetCode(EVENT_TO_GRAVE) e2:SetCondition(c34230233.descon) e2:SetTarget(c34230233.destg) e2:SetOperation(c34230233.desop) c:RegisterEffect(e2) end function c34230233.spfilter(c) return c:IsFaceup() and c:IsAbleToHandAsCost() and c:IsSetCard(0x6) and c:GetCode()~=34230233 end function c34230233.spcon(e,c) if c==nil then return true end return Duel.GetLocationCount(c:GetControler(),LOCATION_MZONE)>-1 and Duel.IsExistingMatchingCard(c34230233.spfilter,c:GetControler(),LOCATION_MZONE,0,1,nil) end function c34230233.spop(e,tp,eg,ep,ev,re,r,rp,c) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_RTOHAND) local g=Duel.SelectMatchingCard(tp,c34230233.spfilter,tp,LOCATION_MZONE,0,1,1,nil) Duel.SendtoHand(g,nil,REASON_COST) end function c34230233.descon(e,tp,eg,ep,ev,re,r,rp) e:SetLabel(e:GetHandler():GetPreviousControler()) return e:GetHandler():IsPreviousLocation(LOCATION_HAND) and bit.band(r,0x4040)==0x4040 end function c34230233.destg(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsOnField() and chkc:IsControler(1-tp) and chkc:IsDestructable() end if chk==0 then return true end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_DESTROY) local g=Duel.SelectTarget(tp,Card.IsDestructable,tp,0,LOCATION_ONFIELD,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_DESTROY,g,g:GetCount(),0,0) if rp==tp then e:SetCategory(CATEGORY_DESTROY) else e:SetCategory(CATEGORY_DESTROY+CATEGORY_SPECIAL_SUMMON) end end function c34230233.desop(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsRelateToEffect(e) and Duel.Destroy(tc,REASON_EFFECT)~=0 and rp~=tp and tp==e:GetLabel() then Duel.BreakEffect() local hg=Duel.GetFieldGroup(tp,0,LOCATION_HAND) if hg:GetCount()>0 then local cg=hg:RandomSelect(tp,1) local cc=cg:GetFirst() Duel.ConfirmCards(tp,cc) if Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and cc:IsCanBeSpecialSummoned(e,0,tp,false,false) and Duel.SelectYesNo(tp,aux.Stringid(34230233,1)) then Duel.SpecialSummon(cc,0,tp,tp,false,false,POS_FACEUP) else Duel.ShuffleHand(1-tp) end end end end
gpl-2.0
tarulas/luadch
luasocket/etc/forward.lua
61
2077
-- load our favourite library local dispatch = require("dispatch") local handler = dispatch.newhandler() -- make sure the user knows how to invoke us if table.getn(arg) < 1 then print("Usage") print(" lua forward.lua <iport:ohost:oport> ...") os.exit(1) end -- function to move data from one socket to the other local function move(foo, bar) local live while 1 do local data, error, partial = foo:receive(2048) live = data or error == "timeout" data = data or partial local result, error = bar:send(data) if not live or not result then foo:close() bar:close() break end end end -- for each tunnel, start a new server for i, v in ipairs(arg) do -- capture forwarding parameters local _, _, iport, ohost, oport = string.find(v, "([^:]+):([^:]+):([^:]+)") assert(iport, "invalid arguments") -- create our server socket local server = assert(handler.tcp()) assert(server:setoption("reuseaddr", true)) assert(server:bind("*", iport)) assert(server:listen(32)) -- handler for the server object loops accepting new connections handler:start(function() while 1 do local client = assert(server:accept()) assert(client:settimeout(0)) -- for each new connection, start a new client handler handler:start(function() -- handler tries to connect to peer local peer = assert(handler.tcp()) assert(peer:settimeout(0)) assert(peer:connect(ohost, oport)) -- if sucessful, starts a new handler to send data from -- client to peer handler:start(function() move(client, peer) end) -- afte starting new handler, enter in loop sending data from -- peer to client move(peer, client) end) end end) end -- simply loop stepping the server while 1 do handler:step() end
gpl-3.0
Lsty/ygopro-scripts
c29904964.lua
3
1971
--覚醒の暗黒騎士ガイア function c29904964.initial_effect(c) --summon with no tribute local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(29904964,0)) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetCode(EFFECT_SUMMON_PROC) e1:SetCondition(c29904964.ntcon) c:RegisterEffect(e1) --tohand local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(29904964,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e2:SetCode(EVENT_RELEASE) e2:SetProperty(EFFECT_FLAG_DAMAGE_STEP+EFFECT_FLAG_DELAY) e2:SetCountLimit(1,29904964) e2:SetTarget(c29904964.sptg) e2:SetOperation(c29904964.spop) c:RegisterEffect(e2) --ritual material local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_SINGLE) e3:SetCode(EFFECT_EXTRA_RITUAL_MATERIAL) e3:SetValue(c29904964.mtval) c:RegisterEffect(e3) end function c29904964.ntcon(e,c,minc) if c==nil then return true end local tp=c:GetControler() return minc==0 and c:GetLevel()>4 and Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)>Duel.GetFieldGroupCount(tp,LOCATION_MZONE,0) end function c29904964.spfilter(c,e,tp) return c:IsSetCard(0xcf) and c:IsCanBeSpecialSummoned(e,0,tp,false,false) and not c:IsHasEffect(EFFECT_NECRO_VALLEY) end function c29904964.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c29904964.spfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,1,nil,e,tp) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,nil,1,tp,LOCATION_HAND+LOCATION_GRAVE) end function c29904964.spop(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_SPSUMMON) local g=Duel.SelectMatchingCard(tp,c29904964.spfilter,tp,LOCATION_HAND+LOCATION_GRAVE,0,1,1,nil,e,tp) if g:GetCount()>0 then Duel.SpecialSummon(g,0,tp,tp,false,false,POS_FACEUP) end end function c29904964.mtval(e,c) return c:IsSetCard(0xcf) end
gpl-2.0
elant/cardpeek
dot_cardpeek_dir/scripts/calypso/c250n502.lua
17
4335
-- -- This file is part of Cardpeek, the smartcard reader utility. -- -- Copyright 2009 by 'L1L1' and 2013-2014 by 'kalon33' -- -- Cardpeek 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. -- -- Cardpeek 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 Cardpeek. If not, see <http://www.gnu.org/licenses/>. -- --------------------------------------------------------------------- -- Most of the data and coding ideas in this file -- was contributed by 'Pascal Terjan', based on location -- data from 'Nicolas Derive'. --------------------------------------------------------------------- require('lib.strict') require('etc.grenoble-tag_stops') require('etc.grenoble-tag_lines') SERVICE_PROVIDERS = { [3] = "TAG" } TRANSPORT_LIST = { [1] = "Tram" } TRANSITION_LIST = { [1] = "Entry", [2] = "Exit", [4] = "Inspection", [6] = "Interchange (entry)", [7] = "Interchange (exit)" } function navigo_process_events(ctx) local EVENTS local RECORD local REF local rec_index local code_value local code_transport local code_transition local code_transport_string local code_transition_string local code_string local service_provider_value local location_id_value local route_number_value local route_string local sector_id local station_id local location_string EVENTS = ui.tree_find_node(ctx,"Event logs, parsed"); if EVENTS==nil then log.print(log.WARNING,"No event found in card") return 0 end for rec_index=1,16 do RECORD = ui.tree_find_node(EVENTS,"record",rec_index) if RECORD==nil then break end REF = ui.tree_find_node(RECORD,"EventServiceProvider") service_provider_value = bytes.tonumber(ui.tree_get_value(REF)) ui.tree_set_alt_value(REF,SERVICE_PROVIDERS[service_provider_value]) REF = ui.tree_find_node(RECORD,"EventCode") code_value = bytes.tonumber(ui.tree_get_value(REF)) code_transport = bit.SHR(code_value,4) code_transport_string = TRANSPORT_LIST[code_transport] if code_transport_string==nil then code_transport_string = code_transport end code_transition = bit.AND(code_value,0xF) code_transition_string = TRANSITION_LIST[code_transition] if (code_transition_string==nil) then code_transition_string = code_transition end ui.tree_set_alt_value(REF,code_transport_string.." - "..code_transition_string) if service_provider_value == 3 and code_transport <=1 then REF = ui.tree_find_node(RECORD,"EventLocationId") location_id_value = bytes.tonumber(ui.tree_get_value(REF)) -- sector_id = bit.SHR(location_id_value,9) -- station_id = bit.AND(bit.SHR(location_id_value,4),0x1F) -- if STOPS_LIST[sector_id]~=nil then -- location_string = "secteur "..STOPS_LIST[sector_id]['name'].." - station " -- if STOPS_LIST[sector_id][station_id]==nil then -- location_string = location_string .. station_id -- else -- location_string = location_string .. STOPS_LIST[sector_id][station_id] -- end -- else -- location_string = "secteur "..sector_id.." - station "..station_id -- end -- end if STOPS_LIST[location_id_value]~=nil then location_string = STOPS_LIST[location_id_value] else location_string = location_id_value end ui.tree_set_alt_value(REF,location_string) REF = ui.tree_find_node(RECORD,"EventRouteNumber") route_number_value = bytes.tonumber(ui.tree_get_value(REF)) if LINES_LIST[route_number_value]["name"] then route_string = LINES_LIST[route_number_value]["name"] else -- route_string = route_number_value route_string = LINES_LIST[route_number_value]["name"] end ui.tree_set_alt_value(REF,route_string) end end end navigo_process_events(CARD)
gpl-3.0
intel2TM/intel
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
gallenmu/MoonGen
examples/timestamping-tests/timestamps-software.lua
5
2484
--- Software timestamping precision test. --- (Used for an evaluation for a paper) local mg = require "moongen" local ts = require "timestamping" local device = require "device" local hist = require "histogram" local memory = require "memory" local stats = require "stats" local timer = require "timer" local ffi = require "ffi" local PKT_SIZE = 60 local NUM_PKTS = 10^6 function master(txPort, rxPort, load) if not txPort or not rxPort or type(load) ~= "number" then errorf("usage: txPort rxPort load") end local txDev = device.config{port = txPort, rxQueues = 2, txQueues = 2} local rxDev = device.config{port = rxPort, rxQueues = 2, txQueues = 2} device.waitForLinks() txDev:getTxQueue(0):setRate(load) if load > 0 then mg.startTask("loadSlave", txDev:getTxQueue(0)) end mg.startTask("txTimestamper", txDev:getTxQueue(1)) mg.startTask("rxTimestamper", rxDev:getRxQueue(1)) mg.waitForTasks() end function loadSlave(queue) local mem = memory.createMemPool(function(buf) buf:getEthPacket():fill{ } end) local bufs = mem:bufArray() local ctr = stats:newDevTxCounter("Load Traffic", queue.dev, "plain") while mg.running() do bufs:alloc(PKT_SIZE) queue:send(bufs) ctr:update() end ctr:finalize() end function txTimestamper(queue) local mem = memory.createMemPool(function(buf) -- just to use the default filter here -- you can use whatever packet type you want buf:getUdpPtpPacket():fill{ } end) mg.sleepMillis(1000) -- ensure that the load task is running local bufs = mem:bufArray(1) local rateLimit = timer:new(0.0001) -- 10kpps timestamped packets local i = 0 while i < NUM_PKTS and mg.running() do bufs:alloc(PKT_SIZE) queue:sendWithTimestamp(bufs) rateLimit:wait() rateLimit:reset() i = i + 1 end mg.sleepMillis(500) mg.stop() end function rxTimestamper(queue) local tscFreq = mg.getCyclesFrequency() local bufs = memory.bufArray(64) -- use whatever filter appropriate for your packet type queue:filterUdpTimestamps() local results = {} local rxts = {} while mg.running() do local numPkts = queue:recvWithTimestamps(bufs) for i = 1, numPkts do local rxTs = bufs[i].udata64 local txTs = bufs[i]:getSoftwareTxTimestamp() results[#results + 1] = tonumber(rxTs - txTs) / tscFreq * 10^9 -- to nanoseconds rxts[#rxts + 1] = tonumber(rxTs) end bufs:free(numPkts) end local f = io.open("pings.txt", "w+") for i, v in ipairs(results) do f:write(v .. "\n") end f:close() end
mit
MalRD/darkstar
scripts/globals/mobskills/astral_flow_pet.lua
11
2217
--------------------------------------------- -- Astral Flow -- make existing pet use astral flow skill --------------------------------------------- require("scripts/globals/status") require("scripts/globals/msg") --------------------------------------------- local function petInactive(pet) return pet:hasStatusEffect(dsp.effect.LULLABY) or pet:hasStatusEffect(dsp.effect.STUN) or pet:hasStatusEffect(dsp.effect.PETRIFICATION) or pet:hasStatusEffect(dsp.effect.SLEEP_II) or pet:hasStatusEffect(dsp.effect.SLEEP_I) or pet:hasStatusEffect(dsp.effect.TERROR) end function onMobSkillCheck(target, mob, skill) -- must have pet if not mob:hasPet() then return 1 end local pet = mob:getPet() -- pet must be an avatar, and active if pet:getSystem() ~= 5 or petInactive(pet) then return 1 end return 0 end function onMobWeaponSkill(target, mob, skill) local typeEffect = dsp.effect.ASTRAL_FLOW local pet = mob:getPet() skill:setMsg(dsp.msg.basic.USES) -- no effect if pet is inactive if petInactive(pet) then return typeEffect end -- Find proper pet skill local petFamily = pet:getFamily() local skillId = 0 if petFamily == 34 or petFamily == 379 then skillId = 919 -- carbuncle searing light elseif petFamily == 36 or petFamily == 381 then skillId = 839 -- fenrir howling moon elseif petFamily == 37 or petFamily == 382 then skillId = 916 -- garuda aerial blast elseif petFamily == 38 or petFamily == 383 then skillId = 913 -- ifrit inferno elseif petFamily == 40 or petFamily == 384 then skillId = 915 -- leviathan tidal wave elseif petFamily == 43 or petFamily == 386 then skillId = 918 -- ramuh judgment bolt elseif petFamily == 44 or petFamily == 387 then skillId = 917 -- shiva diamond dust elseif petFamily == 45 or petFamily == 388 then skillId = 914 -- titan earthen fury else printf("[astral_flow_pet] received unexpected pet family %i. Defaulted skill to Searing Light.", petFamily) skillId = 919 -- searing light end pet:useMobAbility(skillId) return typeEffect end
gpl-3.0
MalRD/darkstar
scripts/globals/mobskills/triclip.lua
11
1043
--------------------------------------------- -- Triclip -- -- Description: Deals damage in a threefold attack. Additional effect: DEX Down -- Type: Physical -- Utsusemi/Blink absorb: 3 shadows -- Range: Melee -- Notes: --------------------------------------------- require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/monstertpmoves") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local numhits = 3 local accmod = 1 local dmgmod = 1.3 local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.PHYSICAL,dsp.damageType.SLASHING,info.hitslanded) local typeEffect = dsp.effect.DEX_DOWN MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 10, 3, 120) target:takeDamage(dmg, mob, dsp.attackType.PHYSICAL, dsp.damageType.SLASHING) return dmg end
gpl-3.0
Lsty/ygopro-scripts
c69058960.lua
3
3454
--No.13 ケインズ・デビル function c69058960.initial_effect(c) --xyz summon aux.AddXyzProcedure(c,nil,1,2) c:EnableReviveLimit() --pos local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(69058960,0)) e1:SetCategory(CATEGORY_POSITION) e1:SetType(EFFECT_TYPE_QUICK_O) e1:SetCode(EVENT_FREE_CHAIN) e1:SetCountLimit(1) e1:SetRange(LOCATION_MZONE) e1:SetCost(c69058960.cost) e1:SetTarget(c69058960.target) e1:SetOperation(c69058960.operation) c:RegisterEffect(e1) -- local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE) e2:SetProperty(EFFECT_FLAG_SINGLE_RANGE) e2:SetRange(LOCATION_MZONE) e2:SetCode(EFFECT_INDESTRUCTABLE_BATTLE) e2:SetCondition(c69058960.indcon) e2:SetValue(1) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) c:RegisterEffect(e3) --reflect local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_REFLECT_BATTLE_DAMAGE) e4:SetCondition(c69058960.refcon) e4:SetValue(1) c:RegisterEffect(e4) end c69058960.xyz_number=13 function c69058960.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():CheckRemoveOverlayCard(tp,1,REASON_COST) end e:GetHandler():RemoveOverlayCard(tp,1,1,REASON_COST) end function c69058960.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetFieldGroupCount(tp,0,LOCATION_MZONE)>0 end end function c69058960.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local g=Duel.GetFieldGroup(tp,0,LOCATION_MZONE) if g:GetCount()>0 then Duel.ChangePosition(g,POS_FACEUP_ATTACK) c:RegisterFlagEffect(69058960,RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END,0,1) local tc=g:GetFirst() while tc do local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_MUST_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_CANNOT_EP) e2:SetRange(LOCATION_MZONE) e2:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e2:SetTargetRange(1,0) e2:SetCondition(c69058960.becon) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD) e3:SetRange(LOCATION_MZONE) e3:SetTargetRange(0,LOCATION_MZONE) e3:SetProperty(EFFECT_FLAG_SET_AVAILABLE+EFFECT_FLAG_IGNORE_IMMUNE) e3:SetCode(EFFECT_CANNOT_BE_BATTLE_TARGET) e3:SetTarget(c69058960.bttg) e3:SetValue(c69058960.vala) e3:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e3) local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_CANNOT_DIRECT_ATTACK) e4:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) tc:RegisterEffect(e4) tc=g:GetNext() end end end function c69058960.filter(c) return c:IsFaceup() and c:IsCode(95442074) end function c69058960.indcon(e) return Duel.IsExistingMatchingCard(c69058960.filter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) and e:GetHandler():GetOverlayCount()~=0 end function c69058960.refcon(e) return Duel.IsExistingMatchingCard(c69058960.filter,e:GetHandlerPlayer(),LOCATION_MZONE,0,1,nil) and Duel.GetAttackTarget()==e:GetHandler() end function c69058960.becon(e) return e:GetHandler():IsAttackable() end function c69058960.bttg(e,c) return c:GetFlagEffect(69058960)==0 end function c69058960.vala(e,c) return c==e:GetHandler() end
gpl-2.0
Lsty/ygopro-scripts
c23558733.lua
3
3022
--フェニキシアン・クラスター・アマリリス function c23558733.initial_effect(c) --cannot special summon local e1=Effect.CreateEffect(c) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(aux.FALSE) c:RegisterEffect(e1) --damage local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetCode(EVENT_BATTLED) e2:SetOperation(c23558733.desop) c:RegisterEffect(e2) local e3=Effect.CreateEffect(c) e3:SetDescription(aux.Stringid(23558733,0)) e3:SetCategory(CATEGORY_DAMAGE) e3:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e3:SetProperty(EFFECT_FLAG_PLAYER_TARGET) e3:SetCode(EVENT_TO_GRAVE) e3:SetCondition(c23558733.damcon) e3:SetTarget(c23558733.damtg) e3:SetOperation(c23558733.damop) c:RegisterEffect(e3) --Special Summon local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(23558733,1)) e4:SetType(EFFECT_TYPE_TRIGGER_O+EFFECT_TYPE_FIELD) e4:SetCategory(CATEGORY_SPECIAL_SUMMON) e4:SetCode(EVENT_PHASE+PHASE_END) e4:SetRange(LOCATION_GRAVE) e4:SetCountLimit(1) e4:SetCondition(c23558733.spcon) e4:SetCost(c23558733.spcost) e4:SetTarget(c23558733.sptg) e4:SetOperation(c23558733.spop) c:RegisterEffect(e4) end function c23558733.desop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c==Duel.GetAttacker() and not c:IsStatus(STATUS_BATTLE_DESTROYED) then Duel.Destroy(c,REASON_EFFECT) end end function c23558733.damcon(e,tp,eg,ep,ev,re,r,rp) return e:GetHandler():GetPreviousControler()==tp and bit.band(r,REASON_DESTROY)~=0 and bit.band(e:GetHandler():GetPreviousLocation(),LOCATION_ONFIELD)>0 end function c23558733.damtg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetTargetPlayer(1-tp) Duel.SetTargetParam(800) Duel.SetOperationInfo(0,CATEGORY_DAMAGE,nil,0,1-tp,800) end function c23558733.damop(e,tp,eg,ep,ev,re,r,rp) local p,d=Duel.GetChainInfo(0,CHAININFO_TARGET_PLAYER,CHAININFO_TARGET_PARAM) Duel.Damage(p,d,REASON_EFFECT) end function c23558733.cfilter(c) return c:IsRace(RACE_PLANT) and c:IsAbleToRemoveAsCost() end function c23558733.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp end function c23558733.spcost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c23558733.cfilter,tp,LOCATION_GRAVE,0,1,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectMatchingCard(tp,c23558733.cfilter,tp,LOCATION_GRAVE,0,1,1,e:GetHandler()) Duel.Remove(g,POS_FACEUP,REASON_COST) end function c23558733.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.GetLocationCount(tp,LOCATION_MZONE)>0 and e:GetHandler():IsCanBeSpecialSummoned(e,0,tp,true,false) end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c23558733.spop(e,tp,eg,ep,ev,re,r,rp) if e:GetHandler():IsRelateToEffect(e) then Duel.SpecialSummon(e:GetHandler(),0,tp,tp,true,false,POS_FACEUP_DEFENCE) end end
gpl-2.0
shahabsaf1/My-system
plugins/groupmanager.lua
136
11323
-- 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 not is_admin(msg) then return "You're not admin!" end 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 local function set_description(msg, data) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = deskripsi save_data(_config.moderation.data, data) return 'Set group description to:\n'..deskripsi end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function set_rules(msg, data) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = string.gsub(msg.to.print_name, '_', ' ')..' rules:\n\n'..rules return rules end -- lock/unlock group name. bot automatically change group name when locked local function lock_group_name(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(msg.to.id)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['set_name'] = string.gsub(msg.to.print_name, '_', ' ') save_data(_config.moderation.data, data) return 'Group name has been locked' end end local function unlock_group_name(msg, data) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local group_name_lock = data[tostring(msg.to.id)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(msg.to.id)]['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) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(msg.to.id)]['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) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(msg.to.id)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(msg.to.id)]['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) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'yes' then return 'Group photo is already locked' else data[tostring(msg.to.id)]['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) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(msg.to.id)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(msg.to.id)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end -- show group settings local function show_group_settings(msg, data) if not is_momod(msg) then return "For moderators only!" end local settings = data[tostring(msg.to.id)]['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 function run(msg, matches) --vardump(msg) if matches[1] == 'creategroup' and matches[2] then group_name = matches[2] return create_group(msg) end if not is_chat_msg(msg) then return "This is not a group chat." end local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if msg.media and is_chat_msg(msg) and is_momod(msg) then if msg.media.type == 'photo' and data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' then load_photo(msg.id, set_group_photo, msg) end end end if data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'setabout' and matches[2] then deskripsi = matches[2] return set_description(msg, data) end if matches[1] == 'about' then return get_description(msg, data) end if matches[1] == 'setrules' then rules = matches[2] return set_rules(msg, data) end if matches[1] == 'rules' then return get_rules(msg, data) end if matches[1] == 'group' and matches[2] == 'lock' then --group lock * if matches[3] == 'name' then return lock_group_name(msg, data) end if matches[3] == 'member' then return lock_group_member(msg, data) end if matches[3] == 'photo' then return lock_group_photo(msg, data) end end if matches[1] == 'group' and matches[2] == 'unlock' then --group unlock * if matches[3] == 'name' then return unlock_group_name(msg, data) end if matches[3] == 'member' then return unlock_group_member(msg, data) end if matches[3] == 'photo' then return unlock_group_photo(msg, data) end end if matches[1] == 'group' and matches[2] == 'settings' then return show_group_settings(msg, data) end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then chat_set_photo (receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end end end return { description = "Plugin to manage group chat.", usage = { "!creategroup <group_name> : Create a new group (admin only)", "!setabout <description> : Set group description", "!about : Read group description", "!setrules <rules> : Set group rules", "!rules : Read group rules", "!setname <new_name> : Set group name", "!setphoto : Set group photo", "!group <lock|unlock> name : Lock/unlock group name", "!group <lock|unlock> photo : Lock/unlock group photo", "!group <lock|unlock> member : Lock/unlock group member", "!group settings : Show group settings" }, patterns = { "^!(creategroup) (.*)$", "^!(setabout) (.*)$", "^!(about)$", "^!(setrules) (.*)$", "^!(rules)$", "^!(setname) (.*)$", "^!(setphoto)$", "^!(group) (lock) (.*)$", "^!(group) (unlock) (.*)$", "^!(group) (settings)$", "^!!tgservice (.+)$", "%[(photo)%]", }, run = run, } end
gpl-2.0
Lsty/ygopro-scripts
c39751093.lua
3
2918
--竜宮之姫 function c39751093.initial_effect(c) --cannot special summon local e1=Effect.CreateEffect(c) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SPSUMMON_CONDITION) e1:SetValue(aux.FALSE) c:RegisterEffect(e1) --summon,flip local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e2:SetCode(EVENT_SUMMON_SUCCESS) e2:SetOperation(c39751093.retreg) c:RegisterEffect(e2) local e3=e2:Clone() e3:SetCode(EVENT_FLIP) c:RegisterEffect(e3) --pos local e4=Effect.CreateEffect(c) e4:SetDescription(aux.Stringid(39751093,1)) e4:SetCategory(CATEGORY_POSITION) e4:SetProperty(EFFECT_FLAG_CARD_TARGET+EFFECT_FLAG_DAMAGE_STEP) e4:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e4:SetCode(EVENT_SUMMON_SUCCESS) e4:SetTarget(c39751093.target) e4:SetOperation(c39751093.operation) c:RegisterEffect(e4) local e5=e4:Clone() e5:SetCode(EVENT_FLIP) c:RegisterEffect(e5) end function c39751093.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and chkc:IsFaceup() end if chk==0 then return Duel.IsExistingTarget(Card.IsFaceup,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_POSCHANGE) local g=Duel.SelectTarget(tp,Card.IsFaceup,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_POSITION,g,1,0,0) end function c39751093.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc and tc:IsFaceup() and tc:IsRelateToEffect(e) then Duel.ChangePosition(tc,POS_FACEUP_DEFENCE,0,POS_FACEUP_ATTACK,0) end end function c39751093.retreg(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() --to hand local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e1:SetDescription(aux.Stringid(39751093,0)) e1:SetCategory(CATEGORY_TOHAND) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetReset(RESET_EVENT+0x1ee0000+RESET_PHASE+PHASE_END) e1:SetCondition(c39751093.retcon) e1:SetTarget(c39751093.rettg) e1:SetOperation(c39751093.retop) c:RegisterEffect(e1) local e2=e1:Clone() e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_O) c:RegisterEffect(e2) end function c39751093.retcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsHasEffect(EFFECT_SPIRIT_DONOT_RETURN) then return false end if e:IsHasType(EFFECT_TYPE_TRIGGER_F) then return not c:IsHasEffect(EFFECT_SPIRIT_MAYNOT_RETURN) else return c:IsHasEffect(EFFECT_SPIRIT_MAYNOT_RETURN) end end function c39751093.rettg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_TOHAND,e:GetHandler(),1,0,0) end function c39751093.retop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if c:IsRelateToEffect(e) and c:IsFaceup() then Duel.SendtoHand(c,nil,REASON_EFFECT) end end
gpl-2.0
neverlose1/sickmind
libs/redis.lua
566
1214
local Redis = require 'redis' local FakeRedis = require 'fakeredis' local params = { host = os.getenv('REDIS_HOST') or '127.0.0.1', port = tonumber(os.getenv('REDIS_PORT') or 6379) } local database = os.getenv('REDIS_DB') local password = os.getenv('REDIS_PASSWORD') -- Overwrite HGETALL Redis.commands.hgetall = Redis.command('hgetall', { response = function(reply, command, ...) local new_reply = { } for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end return new_reply end }) local redis = nil -- Won't launch an error if fails local ok = pcall(function() redis = Redis.connect(params) end) if not ok then local fake_func = function() print('\27[31mCan\'t connect with Redis, install/configure it!\27[39m') end fake_func() fake = FakeRedis.new() print('\27[31mRedis addr: '..params.host..'\27[39m') print('\27[31mRedis port: '..params.port..'\27[39m') redis = setmetatable({fakeredis=true}, { __index = function(a, b) if b ~= 'data' and fake[b] then fake_func(b) end return fake[b] or fake_func end }) else if password then redis:auth(password) end if database then redis:select(database) end end return redis
gpl-2.0
MalRD/darkstar
scripts/globals/spells/distract.lua
12
1695
----------------------------------------- -- Spell: Distract ----------------------------------------- require("scripts/globals/magic") require("scripts/globals/msg") require("scripts/globals/status") require("scripts/globals/utils") ----------------------------------------- function onMagicCastingCheck(caster, target, spell) return 0 end function onSpellCast(caster, target, spell) -- Pull base stats. local dMND = caster:getStat(dsp.mod.MND) - target:getStat(dsp.mod.MND) -- Base evasion reduction is determend by enfeebling skill -- Caps at -25 evasion at 125 skill local basePotency = utils.clamp(math.floor(caster:getSkillLevel(dsp.skill.ENFEEBLING_MAGIC) / 5), 0, 25) -- dMND is tacked on after -- Min cap: 0 at 0 dMND -- Max cap: 10 at 50 dMND basePotency = basePotency + utils.clamp(math.floor(dMND / 5), 0, 10) local power = calculatePotency(basePotency, spell:getSkillType(), caster, target) -- Duration, including resistance. Unconfirmed. local duration = calculateDuration(120, spell:getSkillType(), spell:getSpellGroup(), caster, target) local params = {} params.diff = dMND params.skillType = dsp.skill.ENFEEBLING_MAGIC params.bonus = 0 params.effect = dsp.effect.EVASION_DOWN local resist = applyResistanceEffect(caster, target, spell, params) if resist >= 0.5 then -- Do it! if target:addStatusEffect(params.effect, power, 0, duration * resist) then spell:setMsg(dsp.msg.basic.MAGIC_ENFEEB_IS) else spell:setMsg(dsp.msg.basic.MAGIC_NO_EFFECT) end else spell:setMsg(dsp.msg.basic.MAGIC_RESIST) end return params.effect end
gpl-3.0
Lsty/ygopro-scripts
c55696885.lua
3
1195
--疫病狼 function c55696885.initial_effect(c) --atkup local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(55696885,0)) e1:SetCategory(CATEGORY_ATKCHANGE) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCountLimit(1) e1:SetOperation(c55696885.atkop) c:RegisterEffect(e1) end function c55696885.atkop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_SET_ATTACK_FINAL) e1:SetValue(c:GetBaseAttack()*2) e1:SetReset(RESET_EVENT+0x1ff0000) c:RegisterEffect(e1) local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(55696885,1)) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetCode(EVENT_PHASE+PHASE_END) e2:SetRange(LOCATION_MZONE) e2:SetCountLimit(1) e2:SetTarget(c55696885.destg) e2:SetOperation(c55696885.desop) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) c:RegisterEffect(e2) end function c55696885.destg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_DESTROY,e:GetHandler(),1,0,0) end function c55696885.desop(e,tp,eg,ep,ev,re,r,rp) Duel.Destroy(e:GetHandler(),REASON_EFFECT) end
gpl-2.0
Lsty/ygopro-scripts
c75105429.lua
3
1198
--シンクロ・イジェクション function c75105429.initial_effect(c) --remove local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_REMOVE+CATEGORY_DRAW) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c75105429.target) e1:SetOperation(c75105429.operation) c:RegisterEffect(e1) end function c75105429.filter(c) return c:IsFaceup() and c:IsType(TYPE_SYNCHRO) and c:IsAbleToRemove() end function c75105429.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsControler(1-tp) and chkc:IsLocation(LOCATION_MZONE) and c75105429.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c75105429.filter,tp,0,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_REMOVE) local g=Duel.SelectTarget(tp,c75105429.filter,tp,0,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_REMOVE,g,1,0,0) Duel.SetOperationInfo(0,CATEGORY_DRAW,nil,0,1-tp,1) end function c75105429.operation(e,tp,eg,ep,ev,re,r,rp) local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) and tc:IsFaceup() and Duel.Remove(tc,0,REASON_EFFECT)~=0 then Duel.BreakEffect() Duel.Draw(1-tp,1,REASON_EFFECT) end end
gpl-2.0
Lsty/ygopro-scripts
c61258740.lua
5
1406
--水神の護符 function c61258740.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetTarget(c61258740.target) c:RegisterEffect(e1) --indes local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_INDESTRUCTABLE_EFFECT) e2:SetRange(LOCATION_SZONE) e2:SetTargetRange(LOCATION_MZONE,0) e2:SetTarget(aux.TargetBoolFunction(Card.IsAttribute,ATTRIBUTE_WATER)) e2:SetValue(c61258740.indval) c:RegisterEffect(e2) end function c61258740.indval(e,re,tp) return e:GetHandlerPlayer()==1-tp end function c61258740.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end e:GetHandler():SetTurnCounter(0) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EVENT_PHASE+PHASE_END) e1:SetCountLimit(1) e1:SetRange(LOCATION_SZONE) e1:SetCondition(c61258740.tgcon) e1:SetOperation(c61258740.tgop) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END+RESET_OPPO_TURN,3) e:GetHandler():RegisterEffect(e1) end function c61258740.tgcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()~=tp end function c61258740.tgop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local ct=c:GetTurnCounter() ct=ct+1 c:SetTurnCounter(ct) if ct==3 then Duel.SendtoGrave(c,REASON_RULE) end end
gpl-2.0
MalRD/darkstar
scripts/zones/Bibiki_Bay/IDs.lua
9
3809
----------------------------------- -- Area: Bibiki_Bay ----------------------------------- require("scripts/globals/zone") ----------------------------------- zones = zones or {} zones[dsp.zone.BIBIKI_BAY] = { text = { ITEM_CANNOT_BE_OBTAINED = 6382, -- You cannot obtain the <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6388, -- Obtained: <item>. GIL_OBTAINED = 6389, -- Obtained <number> gil. KEYITEM_OBTAINED = 6391, -- Obtained key item: <keyitem>. YOU_OBTAIN = 6397, -- You obtain <number> <item>! NOTHING_OUT_OF_ORDINARY = 6402, -- There is nothing out of the ordinary here. CONQUEST_BASE = 7049, -- Tallying conquest results... POHKA_SHOP_DIALOG = 7220, -- Hey buddy, need a rod? I've got loads of state-of-the-art, top-of-the-line, high quality rods right here waitin' fer ya! Whaddya say? MEP_NHAPOPOLUKO_DIALOG = 7222, -- Welcome! Fishermen's Guild representative, at your service! WHOA_HOLD_ON_NOW = 7238, -- Whoa, hold on now. Ain't look like you got 'nuff room in that spiffy bag o' yours to carrrry all these darn clams. Why don't you trrry thrrrowin' some o' that old junk away before ya come back here 'gain? YOU_GIT_YER_BAG_READY = 7239, -- You git yer bag ready, pardner? Well alrighty then. Here'rrre yer clams. YOU_RETURN_THE = 7246, -- You return the <item>. AREA_IS_LITTERED = 7247, -- The area is littered with pieces of broken seashells. YOU_FIND_ITEM = 7249, -- You find <item> and toss it into your bucket. THE_WEIGHT_IS_TOO_MUCH = 7250, -- You find <item> and toss it into your bucket... But the weight is too much for the bucket and its bottom breaks! All your shellfish are washed back into the sea... YOU_CANNOT_COLLECT = 7251, -- You cannot collect any clams with a broken bucket! IT_LOOKS_LIKE_SOMEONE = 7252, -- It looks like someone has been digging here. YOUR_CLAMMING_CAPACITY = 7260, -- Your clamming capacity has increased to <number> ponzes! Now you may be able to dig up a... SOMETHING_JUMPS_INTO = 7263, -- Something jumps into your bucket and breaks through the bottom! All your shellfish are washed back into the sea... FISHING_MESSAGE_OFFSET = 7264, -- You can't fish here. DIG_THROW_AWAY = 7277, -- You dig up <item>, but your inventory is full. You regretfully throw the <item> away. FIND_NOTHING = 7279, -- You dig and you dig, but find nothing. NO_BILLET = 7481, -- You were refused passage for failing to present <item>! HAVE_BILLET = 7486, -- You cannot buy morrre than one <item>. Use the one you have now to ride the next ship. LEFT_BILLET = 7491, -- You use your <item>. (<number> trip[/s] remaining) END_BILLET = 7492, -- You use up your <item>. COMMON_SENSE_SURVIVAL = 8637, -- It appears that you have arrived at a new survival guide provided by the Adventurers' Mutual Aid Network. Common sense dictates that you should now be able to teleport here from similar tomes throughout the world. NEWS_BILLET = 8660, -- <item> has been [added to your list of favorites/removed from your list of favorites]. }, mob = { SERRA_PH = { [16793645] = 16793646, -- -348 0.001 -904 }, INTULO_PH = { [16793741] = 16793742, -- 480 -3 743 }, SPLACKNUCK_PH = { [16793775] = 16793776, }, DALHAM = 16793858, SHEN = 16793859, }, npc = { }, } return zones[dsp.zone.BIBIKI_BAY]
gpl-3.0