repo_name
stringlengths
6
78
path
stringlengths
4
206
copies
stringclasses
281 values
size
stringlengths
4
7
content
stringlengths
625
1.05M
license
stringclasses
15 values
okwinza/PartyAbilityBarsLegion
libs/Spells/spell_lib_hunter.lua
2
7595
local name, SPELLDB = ... SPELLDB.HUNTER = {} SPELLDB.HUNTER.BEASTMASTERY = {} SPELLDB.HUNTER.MARKSMANSHIP = {} SPELLDB.HUNTER.SURVIVAL = {} SPELLDB.HUNTER.BEASTMASTERY.spells = { 208683, 186257 --[[Aspect of the Cheetah--]], 186265 --[[Aspect of the Turtle--]], 193530 --[[Aspect of the Wild--]], 19574 --[[Bestial Wrath--]], 193455 --[[Cobra Shot--]], 5116 --[[Concussive Shot--]], 147362 --[[Counter Shot--]], 120679 --[[Dire Beast--]], 6197 --[[Eagle Eye--]], 109304 --[[Exhilaration--]], 5384 --[[Feign Death--]], 1543 --[[Flare--]], 34026 --[[Kill Command--]], 34477 --[[Misdirection--]], 2643 --[[Multi-Shot--]], 115939 --[[Beast Cleave--]], 56315 --[[Kindred Spirits--]], 76657 --[[Mastery: Master of Beasts--]], 185789 --[[Wild Call--]], }; SPELLDB.HUNTER.MARKSMANSHIP.spells = { 19434 --[[Aimed Shot--]], 185358 --[[Arcane Shot--]], 186257 --[[Aspect of the Cheetah--]], 186265 --[[Aspect of the Turtle--]], 186387 --[[Bursting Shot--]], 5116 --[[Concussive Shot--]], 147362 --[[Counter Shot--]], 6197 --[[Eagle Eye--]], 109304 --[[Exhilaration--]], 5384 --[[Feign Death--]], 1543 --[[Flare--]], 185901 --[[Marked Shot--]], 34477 --[[Misdirection--]], 2643 --[[Multi-Shot--]], 193526 --[[Trueshot--]], 35110 --[[Bombardment--]], 185987 --[[Hunter's Mark--]], 212658 --[[Hunting Party--]], 231554 --[[Marksman's Focus--]], 193468 --[[Mastery: Sniper Training--]], }; SPELLDB.HUNTER.SURVIVAL.spells = { 186257 --[[Aspect of the Cheetah--]], 186289 --[[Aspect of the Eagle--]], 186265 --[[Aspect of the Turtle--]], 187708 --[[Carve--]], 6197 --[[Eagle Eye--]], 109304 --[[Exhilaration--]], 5384 --[[Feign Death--]], 202800 --[[Flanking Strike--]], 1543 --[[Flare--]], 190925 --[[Harpoon--]], 193265 --[[Hatchet Toss--]], 185855 --[[Lacerate--]], 190928 --[[Mongoose Bite--]], 187707 --[[Muzzle--]], 186270 --[[Raptor Strike--]], 195645 --[[Wing Clip--]], 191334 --[[Mastery: Hunting Companion--]], 164856 --[[Survivalist--]], 234955 --[[Waylay--]], 187650 --[[Freezing Trap]], }; SPELLDB.HUNTER.BEASTMASTERY.talents = { 204308 --[[Big Game Hunter--]], 194397 --[[Way of the Cobra--]], 193532 --[[Dire Stable--]], 199530 --[[Stomp--]], 217200 --[[Dire Frenzy--]], 53209 --[[Chimaera Shot--]], 109215 --[[Posthaste--]], 199523 --[[Farstrider--]], 199921 --[[Trailblazer--]], 199528 --[[One with the Pack--]], 194306 --[[Bestial Fury--]], 130392 --[[Blink Strikes--]], 109248 --[[Binding Shot--]], 19386 --[[Wyvern Sting--]], 19577 --[[Intimidation--]], 131894 --[[A Murder of Crows--]], 120360 --[[Barrage--]], 194386 --[[Volley--]], 201430 --[[Stampede--]], 199532 --[[Killer Cobra--]], 191384 --[[Aspect of the Beast--]], }; SPELLDB.HUNTER.MARKSMANSHIP.talents = { 155228 --[[Lone Wolf--]], 193533 --[[Steady Focus--]], 53238 --[[Careful Aim--]], 194595 --[[Lock and Load--]], 194599 --[[Black Arrow--]], 199527 --[[True Aim--]], 109215 --[[Posthaste--]], 199523 --[[Farstrider--]], 199921 --[[Trailblazer--]], 212431 --[[Explosive Shot--]], 206817 --[[Sentinel--]], 234588 --[[Patient Sniper--]], 109248 --[[Binding Shot--]], 19386 --[[Wyvern Sting--]], 199483 --[[Camouflage--]], 131894 --[[A Murder of Crows--]], 120360 --[[Barrage--]], 194386 --[[Volley--]], 214579 --[[Sidewinders--]], 198670 --[[Piercing Shot--]], 199522 --[[Trick Shot--]], }; SPELLDB.HUNTER.SURVIVAL.talents = { 204315 --[[Animal Instincts--]], 200163 --[[Throwing Axes--]], 201082 --[[Way of the Mok'Nathal--]], 206505 --[[A Murder of Crows--]], 201075 --[[Mortal Wounds--]], 201078 --[[Snake Hunter--]], 109215 --[[Posthaste--]], 781 --[[Disengage--]], 199921 --[[Trailblazer--]], 194277 --[[Caltrops--]], 236698 --[[Guerrilla Tactics--]], 162488 --[[Steel Trap--]], 191241 --[[Sticky Bomb--]], 200108 --[[Ranger's Net--]], 199483 --[[Camouflage--]], 212436 --[[Butchery--]], 194855 --[[Dragonsfire Grenade--]], 87935 --[[Serpent Sting--]], 194407 --[[Spitting Cobra--]], 199543 --[[Expert Trapper--]], 191384 --[[Aspect of the Beast--]], }; SPELLDB.HUNTER.BEASTMASTERY.pvpTalents = { 208683 --[[Gladiator's Medallion--]], 214027 --[[Adaptation--]], 196029 --[[Relentless--]], 213538 --[[Quickshots--]], 213539 --[[Initiation--]], 213543 --[[Focused Fire--]], 202589 --[[Dragonscale Armor--]], 202624 --[[Catlike Reflexes--]], 202746 --[[Survival Tactics--]], 202797 --[[Viper Sting--]], 202900 --[[Scorpid Sting--]], 202914 --[[Spider Sting--]], 212668 --[[The Beast Within--]], 212669 --[[Separation Anxiety--]], 204190 --[[Wild Protector--]], 212670 --[[Go for the Throat--]], 208652 --[[Dire Beast: Hawk--]], 205691 --[[Dire Beast: Basilisk--]], }; SPELLDB.HUNTER.MARKSMANSHIP.pvpTalents = { 208683 --[[Gladiator's Medallion--]], 214027 --[[Adaptation--]], 196029 --[[Relentless--]], 213538 --[[Quickshots--]], 213539 --[[Initiation--]], 213543 --[[Focused Fire--]], 202589 --[[Dragonscale Armor--]], 202624 --[[Catlike Reflexes--]], 202746 --[[Survival Tactics--]], 202797 --[[Viper Sting--]], 202900 --[[Scorpid Sting--]], 202914 --[[Spider Sting--]], 209793 --[[T.N.T.--]], 213691 --[[Scatter Shot--]], 236776 --[[Hi-Explosive Trap--]], 203129 --[[Trueshot Mastery--]], 203133 --[[Spray and Pray--]], 203155 --[[Sniper Shot--]], }; SPELLDB.HUNTER.SURVIVAL.pvpTalents = { 208683 --[[Gladiator's Medallion--]], 214027 --[[Adaptation--]], 196029 --[[Relentless--]], 232047 --[[Hardiness--]], 232046 --[[Reinforced Armor--]], 232045 --[[Sparring--]], 202589 --[[Dragonscale Armor--]], 202624 --[[Catlike Reflexes--]], 202746 --[[Survival Tactics--]], 202797 --[[Viper Sting--]], 202900 --[[Scorpid Sting--]], 202914 --[[Spider Sting--]], 203235 --[[Hunting Pack--]], 212640 --[[Mending Bandage--]], 53271 --[[Master's Call--]], 203264 --[[Sticky Tar--]], 203340 --[[Diamond Ice--]], 212638 --[[Tracker's Net--]], }; SPELLDB.HUNTER.BEASTMASTERY.artifact = {207068,197344,197248,197354,215779,197139,197160,197162,197047,206910,197343,197080,197038,197178,197138,197140,197199}; SPELLDB.HUNTER.MARKSMANSHIP.artifact = {204147,204089,191048,190852,191339,190529,190520,190514,191328,190462,214826,190467,204219,190503,190449,190457,190567,}; SPELLDB.HUNTER.SURVIVAL.artifact = {203415,203563,203755,203757,221773,203566,203577,224764,225092,203669,203578,203752,203670,203638,203673,203754,203749,};
gpl-3.0
firebaugh/Digitowls
Player/Config/Config_OP_Robot.lua
4
2825
module(..., package.seeall); require('vector') platform = {}; platform.name = 'darwinop' -- Device Interface Libraries dev = {}; dev.body = 'DarwinOPBody'; dev.camera = 'darwinCam'; dev.kinematics = 'DarwinOPKinematics'; --dev.comm='NSLComm'; dev.comm='NullComm'; dev.monitor_comm = 'NSLMonitorCommWired'; dev.game_control='NSLGameControl'; dev.walk='NaoWalk'; dev.kick='NaoKick'; --[[ dev.walk='NSLWalk'; dev.kick='NSLKick'; --]] -- keyframe files km = {}; km.standup_front = 'km_OP_StandupFromFront.lua'; km.standup_back = 'km_OP_StandupFromBack.lua'; --Sitting parameters sit={}; sit.bodyHeight=0.18+0.05; --Fixed with new kinematics sit.bodyHeight=0.17+0.05; --Fixed with new kinematics sit.supportX=-0.020; sit.supportX=-0.010; sit.bodyTilt=5*math.pi/180; sit.dpLimit=vector.new({.1,.01,.03,.1,.3,.1}); sit.dpLimit=vector.new({.1,.01,.06,.1,.3,.1});--Faster sit --Standing parameters stance={}; stance.dpLimit=vector.new({.04, .03, .04, .4, .4, .4}); stance.dpLimit=vector.new({.04, .03, .07, .4, .4, .4});--Faster standup --Servo parameters servo={} servo.type = 1; --1 for CM730, 0 for seeeduino servo.pid = 0; --old version of rx28M servo.syncread= 0; servo.idMap={ 19,20, --Head 2,4,6, --LArm 8,10,12,14,16,18,--LLeg 7,9,11,13,15,17,--RLeg 1,3,5, --RArm -- 21, --Aux servo } servo.dirReverse={ 2, --Head 4, --LArm 6,7,8,9,--LLeg 12,13,16,--RLeg 18,19,20,--RArm } servo.steps=vector.new({ 1024,1024, 1024,1024,1024, 1024,1024,1024,1024,1024,1024, 1024,1024,1024,1024,1024,1024, 1024,1024,1024, 1024, --For aux }); servo.posZero={ 512,512, 205,665,819, 512,512,512,512,512,512, 512,512,512,512,512,512, 819,358,205, 512, --For aux } servo.moveRange=vector.new({ 300,300, 300,300,300, 300,300,300,300,300,300, 300,300,300,300,300,300, 300,300,300, 300, --For aux })*math.pi/180; --Measured IMU bias parameters gyro={}; gyro.rpy={3,2,1} --axis remap, rotation in x,y,z acc={}; acc.xyz={2,1,3}; --axis remap angle={}; angle.gMax = 1.3; angle.gMin= 0.7; angle.accFactor=0.2; gyro.sensitivity=vector.new({1,1,1})/0.273 -- Spec, 0.0008 V/dps / (1.5/512) V/step gyro.zero=vector.new({512,512,512}); --Those biases can be measured using test_imu.lua acc.sensitivity=vector.new({1,-1,-1})/110; --Measured value acc.zero=vector.new({512,512,512}); --Measured value -- Head Parameters head = {}; head.camOffsetZ = 0.37; --head.pitchMin = -35*math.pi/180; head.pitchMin = -55*math.pi/180; head.pitchMax = 68*math.pi/180; head.yawMin = -90*math.pi/180; head.yawMax = 90*math.pi/180; head.cameraPos = {{0.034, 0.0, 0.0332}} --OP, spec value, may need to be recalibrated head.cameraAngle = {{0.0, 40*math.pi/180, 0.0}}; --Default value for production OP head.neckZ=0.0765; --From CoM to neck joint head.neckX=0.013; --From CoM to neck joint head.bodyTilt = 0;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Oldton_Movalpolos/TextIDs.lua
15
1146
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6384; -- Obtained: <item>. GIL_OBTAINED = 6385; -- Obtained <number> gil. KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7564; -- You can't fish here. -- Mining MINING_IS_POSSIBLE_HERE = 7690; -- Mining is possible here if you have -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7737; -- You unlock the chest! CHEST_FAIL = 7738; -- Fails to open the chest. CHEST_TRAP = 7739; -- The chest was trapped! CHEST_WEAK = 7740; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7741; -- The chest was a mimic! CHEST_MOOGLE = 7742; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7743; -- The chest was but an illusion... CHEST_LOCKED = 7744; -- The chest appears to be locked. -- NPCs RAKOROK_DIALOGUE = 7714; -- Nsy pipul. Gattohre! I bisynw! -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results...
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Boneyard_Gully/npcs/_081.lua
12
1433
----------------------------------- -- Area: Boneyard_Gully -- NPC: _081 (Dark Miasma) ----------------------------------- package.loaded["scripts/zones/Boneyard_Gully/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Boneyard_Gully/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (TradeBCNM(player,player:getZoneID(),trade,npc)) then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (EventTriggerBCNM(player,npc)) then return 1; else return 1; end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if (EventUpdateBCNM(player,csid,option)) then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if (EventFinishBCNM(player,csid,option)) then return; end end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Apollyon/mobs/Barometz.lua
7
1266
----------------------------------- -- Area: Apollyon NE -- NPC: Barometz ----------------------------------- package.loaded["scripts/zones/Apollyon/TextIDs"] = nil; ----------------------------------- require("scripts/globals/limbus"); require("scripts/zones/Apollyon/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) local mobID = mob:getID(); -- print(mobID); local mobX = mob:getXPos(); local mobY = mob:getYPos(); local mobZ = mob:getZPos(); if (mobID ==16933045) then -- time T2 GetNPCByID(16932864+81):setPos(459,-1,29); GetNPCByID(16932864+81):setStatus(STATUS_NORMAL); elseif (mobID ==16933049) then -- time T3 GetNPCByID(16932864+82):setPos(480,-1,-39); GetNPCByID(16932864+82):setStatus(STATUS_NORMAL); elseif (mobID ==16933055) then -- item GetNPCByID(16932864+119):setPos(mobX,mobY,mobZ); GetNPCByID(16932864+119):setStatus(STATUS_NORMAL); end end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Riverne-Site_B01/Zone.lua
13
1784
----------------------------------- -- -- Zone: Riverne-Site_B01 -- ----------------------------------- package.loaded["scripts/zones/Riverne-Site_B01/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Riverne-Site_B01/TextIDs"); require("scripts/globals/status"); require("scripts/globals/settings"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(729.749,-20.319,407.153,90); -- {R} end -- ZONE LEVEL RESTRICTION if (ENABLE_COP_ZONE_CAP == 1) then player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,50,0,0); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Den_of_Rancor/npcs/_4g5.lua
27
2382
----------------------------------- -- Area: Den of Rancor -- NPC: Lantern (NE) -- @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 (LNE == 8) then player:messageSpecial(LANTERN_OFFSET + 7); -- already lit elseif (LNE == 9) then npc:openDoor(LANTERNS_STAY_LIT); local ALL = LNW+LSW+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
Kosmos82/kosmosdarkstar
scripts/zones/Heavens_Tower/npcs/_6q2.lua
13
3627
----------------------------------- -- Area: Heaven's Tower -- NPC: Vestal Chamber (chamber of the Star Sibyl) -- @pos 0.1 -49 37 242 ----------------------------------- package.loaded["scripts/zones/Heavens_Tower/TextIDs"] = nil; ----------------------------------- require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Heavens_Tower/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local CurrentMission = player:getCurrentMission(WINDURST); local MissionStatus = player:getVar("MissionStatus"); if (CurrentMission == A_NEW_JOURNEY and MissionStatus == 0) then player:startEvent(0x0099); elseif (player:hasKeyItem(MESSAGE_TO_JEUNO_WINDURST)) then player:startEvent(0x00A6); elseif (player:getRank() == 5 and CurrentMission == 255 and player:hasCompletedMission(WINDURST,THE_FINAL_SEAL) == false) then player:startEvent(0x00BE); elseif (player:hasKeyItem(BURNT_SEAL)) then player:startEvent(0x00C0); elseif (CurrentMission == THE_SHADOW_AWAITS and MissionStatus == 0) then player:startEvent(0x00D6); elseif (CurrentMission == THE_SHADOW_AWAITS and player:hasKeyItem(SHADOW_FRAGMENT)) then player:startEvent(0x00D8); elseif (CurrentMission == SAINTLY_INVITATION and MissionStatus == 0) then player:startEvent(0x0136); elseif (CurrentMission == SAINTLY_INVITATION and MissionStatus == 3) then player:startEvent(0x0138); elseif (CurrentMission == DOLL_OF_THE_DEAD and MissionStatus == 2) then player:startEvent(0x016A); else player:startEvent(0x009A); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x0099) then player:setVar("MissionStatus",1); player:delKeyItem(STAR_CRESTED_SUMMONS); player:addKeyItem(LETTER_TO_THE_AMBASSADOR); player:messageSpecial(KEYITEM_OBTAINED,LETTER_TO_THE_AMBASSADOR); elseif (csid == 0x00A6 or csid == 0x00BE) then if (option == 0) then player:addMission(WINDURST,THE_FINAL_SEAL); player:addKeyItem(NEW_FEIYIN_SEAL); player:messageSpecial(KEYITEM_OBTAINED,NEW_FEIYIN_SEAL); player:setVar("MissionStatus",10); end player:delKeyItem(MESSAGE_TO_JEUNO_WINDURST); elseif (csid == 0x00D6) then player:setVar("MissionStatus",2); player:delKeyItem(STAR_CRESTED_SUMMONS); player:addTitle(STARORDAINED_WARRIOR); elseif (csid == 0x0136) then player:setVar("MissionStatus",1); player:addTitle(HERO_ON_BEHALF_OF_WINDURST); player:addKeyItem(HOLY_ONES_INVITATION); player:messageSpecial(KEYITEM_OBTAINED,HOLY_ONES_INVITATION); elseif (csid == 0x0138) then finishMissionTimeline(player,3,csid,option); elseif (csid == 0x00C0 or csid == 0x00D8) then finishMissionTimeline(player,1,csid,option); elseif (csid == 0x016A) then player:setVar("MissionStatus",3); end end;
gpl-3.0
vinzenz/premake
tests/test_platforms.lua
7
1571
-- -- tests/test_platforms.lua -- Automated test suite for platform handling functions. -- Copyright (c) 2009 Jason Perkins and the Premake project -- T.platforms = { } local testmap = { Native="Win32", x32="Win32", x64="x64" } local sln, r function T.platforms.setup() sln = solution "MySolution" configurations { "Debug", "Release" } end function T.platforms.filter_OnNoSolutionPlatforms() premake.buildconfigs() r = premake.filterplatforms(sln, testmap) test.isequal("", table.concat(r, ":")) end function T.platforms.filter_OnNoSolutionPlatformsAndDefault() premake.buildconfigs() r = premake.filterplatforms(sln, testmap, "x32") test.isequal("x32", table.concat(r, ":")) end function T.platforms.filter_OnIntersection() platforms { "x32", "x64", "Xbox360" } premake.buildconfigs() r = premake.filterplatforms(sln, testmap, "x32") test.isequal("x32:x64", table.concat(r, ":")) end function T.platforms.filter_OnNoIntersection() platforms { "Universal", "Xbox360" } premake.buildconfigs() r = premake.filterplatforms(sln, testmap) test.isequal("", table.concat(r, ":")) end function T.platforms.filter_OnNoIntersectionAndDefault() platforms { "Universal", "Xbox360" } premake.buildconfigs() r = premake.filterplatforms(sln, testmap, "x32") test.isequal("x32", table.concat(r, ":")) end function T.platforms.filter_OnDuplicateKeys() platforms { "Native", "x32" } premake.buildconfigs() r = premake.filterplatforms(sln, testmap, "x32") test.isequal("Native", table.concat(r, ":")) end
gpl-2.0
ychoucha/minetest-game-mineclone
mods/WorldEdit/worldedit_limited/init.lua
26
3114
do return end do local MAX_VOLUME = 30 * 30 * 30 local we = worldedit local volume = we.volume local safewrap = function(func) return function(pos1, pos2, ...) if validbox(pos1, pos2) then return func(pos1, pos2, ...) end return 0, pos1, pos2 end end local validbox = function(pos1, pos2) tpos1, tpos2 = we.sort_pos(pos1, pos2) if volume(tpos1, tpos2) > MAX_VOLUME then return false end --check for ownership of area if ownership mod is installed if owner_defs then local inside = false for _, def in pairs(owner_defs) do --sort positions local tdef = {x1=def.x1, x2 = def.x2, y1=def.y1, y2=def.y2, z1=def.z1, z2=def.z2} if tdef.x1 > tdef.x2 then tdef.x1, tdef.x2 = tdef.x2, tdef.x1 end if tdef.y1 > tdef.y2 then tdef.y1, tdef.y2 = tdef.y2, tdef.y1 end if tdef.z1 > tdef.z2 then tdef.z1, tdef.z2 = tdef.z2, tdef.z1 end --check ownership if tpos1.x >= tdef.x1 and tpos1.x <= tdef.x2 and tpos2.x >= tdef.x1 and tpos2.x <= tdef.x2 and tpos1.y >= tdef.y1 and tpos1.y <= tdef.y2 and tpos2.y >= tdef.y1 and tpos2.y <= tdef.y2 and tpos1.z >= tdef.z1 and tpos1.z <= tdef.z2 and tpos2.z >= tdef.z1 and tpos2.z <= tdef.z2 and name == def.owner then --wip: name isn't available here inside = true break end end if not inside then return false end end return true end worldedit = { sort_pos = we.sort_pos, set = safewrap(we.set), replace = safewrap(we.replace), replaceinverse = safewrap(we.replaceinverse), copy = function(pos1, pos2, axis, amount) tpos1, tpos2 = we.sort_pos(pos1, pos2) tpos1[axis] = tpos1[axis] + amount tpos2[axis] = tpos2[axis] + amount if validbox(pos1, pos2) and validbox(tpos1, tpos2) then we.copy(pos1, pos2, axis, amount) else return 0 end end, move = function(pos1, pos2, axis, amount) tpos1, tpos2 = we.sort_pos(pos1, pos2) tpos1[axis] = tpos1[axis] + amount tpos2[axis] = tpos2[axis] + amount if validbox(pos1, pos2) and validbox(tpos1, tpos2) then we.move(pos1, pos2, axis, amount) else return 0 end end, stack = function(pos1, pos2, axis, count) tpos1, tpos2 = we.sort_pos(pos1, pos2) local length = (tpos2[axis] - tpos1[axis] + 1) * count if count < 0 then tpos1[axis] = tpos1[axis] + length else tpos2[axis] = tpos2[axis] + length end if validbox(tpos1, tpos2) then we.stack(pos1, pos2, axis, amount) else return 0 end end, --wip: add transpose, rotate safely flip = safewrap(we.flip), orient = safewrap(we.orient), fixlight = safewrap(we.fixlight), --wip: add primitives here volume = we.volume, hide = safewrap(we.hide), suppress = safewrap(we.suppress), highlight = safewrap(we.highlight), restore = safewrap(we.restore), serialize = safewrap(we.serialize), allocate = we.allocate, deserialize = function(originpos, value) local tpos1, tpos2 = we.allocate(originpos, value) if validbox(tpos1, tpos2) then we.deserialize(originpos, value) else return 0 end end, } end
lgpl-2.1
Kosmos82/kosmosdarkstar
scripts/globals/mobskills/Hellsnap.lua
31
1162
--------------------------------------------------- -- Hellsnap -- --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) if(mob:getFamily() == 91) then local mobSkin = mob:getModelId(); if (mobSkin == 1840) then return 0; else return 1; end end if(mob:getFamily() == 316) then local mobSkin = mob:getModelId(); if (mobSkin == 1839) then return 0; else return 1; end end return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 10; local dmgmod = 4.0; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded*math.random(2,3)); local typeEffect = EFFECT_STUN; MobPhysicalStatusEffectMove(mob, target, skill, typeEffect, 1, 0, 4); target:delHP(dmg); return dmg; end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Qufim_Island/npcs/Trodden_Snow.lua
13
5395
----------------------------------- -- Area: Qufim Island -- NPC: Trodden Snow -- Mission: ASA - THAT_WHICH_CURDLES_BLOOD -- Mission: ASA - SUGAR_COATED_DIRECTIVE -- @zone 126 -- @pos -19 -17 104 ----------------------------------- package.loaded["scripts/zones/Qufim_Island/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Qufim_Island/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) -- Trade Enfeebling Kit if (player:getCurrentMission(ASA) == THAT_WHICH_CURDLES_BLOOD) then local item = 0; local asaStatus = player:getVar("ASA_Status"); -- TODO: Other Enfeebling Kits if (asaStatus == 0) then item = 2779; else printf("Error: Unknown ASA Status Encountered <%u>", asaStatus); end if (trade:getItemCount() == 1 and trade:hasItemQty(item,1)) then player:tradeComplete(); player:startEvent(0x002c); end end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) --ASA 4 CS: Triggers With At Least 3 Counterseals. if (player:getCurrentMission(ASA) == SUGAR_COATED_DIRECTIVE) then local completedSeals = 0; if (player:hasKeyItem(AMBER_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (player:hasKeyItem(AZURE_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (player:hasKeyItem(CERULEAN_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (player:hasKeyItem(EMERALD_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (player:hasKeyItem(SCARLET_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (player:hasKeyItem(VIOLET_COUNTERSEAL)) then completedSeals = completedSeals + 1; end; if (completedSeals >= 3) then player:setVar("ASA_Status", completedSeals); player:startEvent(0x002d); 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); if (csid==0x002c) then player:addKeyItem(DOMINAS_SCARLET_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_SCARLET_SEAL); player:addKeyItem(DOMINAS_CERULEAN_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_CERULEAN_SEAL); player:addKeyItem(DOMINAS_EMERALD_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_EMERALD_SEAL); player:addKeyItem(DOMINAS_AMBER_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_AMBER_SEAL); player:addKeyItem(DOMINAS_VIOLET_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_VIOLET_SEAL); player:addKeyItem(DOMINAS_AZURE_SEAL); player:messageSpecial(KEYITEM_OBTAINED,DOMINAS_AZURE_SEAL); player:completeMission(ASA,THAT_WHICH_CURDLES_BLOOD); player:addMission(ASA,SUGAR_COATED_DIRECTIVE); player:setVar("ASA_Status",0); player:setVar("ASA4_Amber","0"); player:setVar("ASA4_Azure","0"); player:setVar("ASA4_Cerulean","0"); player:setVar("ASA4_Emerald","0"); player:setVar("ASA4_Scarlet","0"); player:setVar("ASA4_Violet","0"); elseif (csid==0x002d) then local completedSeals = player:getVar("ASA_Status"); -- Calculate Reward if (completedSeals == 3) then player:addGil(GIL_RATE*3000); elseif (completedSeals == 4) then player:addGil(GIL_RATE*10000); elseif (completedSeals == 5) then player:addGil(GIL_RATE*30000); elseif (completedSeals == 6) then player:addGil(GIL_RATE*50000); end -- Clean Up Remaining Key Items player:delKeyItem(DOMINAS_SCARLET_SEAL); player:delKeyItem(DOMINAS_CERULEAN_SEAL); player:delKeyItem(DOMINAS_EMERALD_SEAL); player:delKeyItem(DOMINAS_AMBER_SEAL); player:delKeyItem(DOMINAS_VIOLET_SEAL); player:delKeyItem(DOMINAS_AZURE_SEAL); player:delKeyItem(SCARLET_COUNTERSEAL); player:delKeyItem(CERULEAN_COUNTERSEAL); player:delKeyItem(EMERALD_COUNTERSEAL); player:delKeyItem(AMBER_COUNTERSEAL); player:delKeyItem(VIOLET_COUNTERSEAL); player:delKeyItem(AZURE_COUNTERSEAL); -- Advance Mission player:completeMission(ASA,SUGAR_COATED_DIRECTIVE); player:addMission(ASA,ENEMY_OF_THE_EMPIRE_I); player:setVar("ASA_Status",0); end end;
gpl-3.0
firebaugh/Digitowls
WebotsController/Player/HeadFSM/NaoGoalie/HeadFSM.lua
6
1142
module(..., package.seeall); require('Body') require('fsm') require('headIdle') require('headStart') require('headReady') require('headReadyLookGoal') require('headScan') require('headTrack') require('headLookGoal') require('headSweep') sm = fsm.new(headIdle); sm:add_state(headStart); sm:add_state(headReady); sm:add_state(headReadyLookGoal); sm:add_state(headScan); sm:add_state(headTrack); sm:add_state(headLookGoal); sm:add_state(headSweep); sm:set_transition(headStart, 'done', headTrack); sm:set_transition(headReady, 'done', headReadyLookGoal); sm:set_transition(headReadyLookGoal, 'timeout', headReady); sm:set_transition(headReadyLookGoal, 'lost', headReady); sm:set_transition(headTrack, 'lost', headScan); sm:set_transition(headTrack, 'timeout', headLookGoal); sm:set_transition(headLookGoal, 'timeout', headTrack); sm:set_transition(headLookGoal, 'lost', headSweep); sm:set_transition(headSweep, 'done', headTrack); sm:set_transition(headScan, 'ball', headTrack); sm:set_transition(headScan, 'timeout', headScan); function entry() sm:entry() end function update() sm:update(); end function exit() sm:exit(); end
gpl-3.0
firebaugh/Digitowls
Player/HeadFSM/NaoGoalie/HeadFSM.lua
6
1142
module(..., package.seeall); require('Body') require('fsm') require('headIdle') require('headStart') require('headReady') require('headReadyLookGoal') require('headScan') require('headTrack') require('headLookGoal') require('headSweep') sm = fsm.new(headIdle); sm:add_state(headStart); sm:add_state(headReady); sm:add_state(headReadyLookGoal); sm:add_state(headScan); sm:add_state(headTrack); sm:add_state(headLookGoal); sm:add_state(headSweep); sm:set_transition(headStart, 'done', headTrack); sm:set_transition(headReady, 'done', headReadyLookGoal); sm:set_transition(headReadyLookGoal, 'timeout', headReady); sm:set_transition(headReadyLookGoal, 'lost', headReady); sm:set_transition(headTrack, 'lost', headScan); sm:set_transition(headTrack, 'timeout', headLookGoal); sm:set_transition(headLookGoal, 'timeout', headTrack); sm:set_transition(headLookGoal, 'lost', headSweep); sm:set_transition(headSweep, 'done', headTrack); sm:set_transition(headScan, 'ball', headTrack); sm:set_transition(headScan, 'timeout', headScan); function entry() sm:entry() end function update() sm:update(); end function exit() sm:exit(); end
gpl-3.0
martin-traverse/premake-core
tests/testfx.lua
9
10494
-- -- tests/testfx.lua -- Automated test framework for Premake. -- Copyright (c) 2008-2015 Jason Perkins and the Premake project -- local p = premake -- -- Define a namespace for the testing functions -- test = {} test.suppressed = {} -- -- Capture stderr for testing. -- local stderr_capture = nil local mt = getmetatable(io.stderr) local builtin_write = mt.write mt.write = function(...) if select(1,...) == io.stderr then stderr_capture = (stderr_capture or "") .. select(2,...) else return builtin_write(...) end end -- -- Assertion functions -- function test.capture(expected) local actual = premake.captured() .. premake.eol() -- create line-by-line iterators for both values local ait = actual:gmatch("(.-)" .. premake.eol()) local eit = expected:gmatch("(.-)\n") -- compare each value line by line local linenum = 1 local atxt = ait() local etxt = eit() while etxt do if (etxt ~= atxt) then test.fail("(%d) expected:\n%s\n...but was:\n%s", linenum, etxt, atxt) end linenum = linenum + 1 atxt = ait() etxt = eit() end end function test.closedfile(expected) if expected and not test.value_closedfile then test.fail("expected file to be closed") elseif not expected and test.value_closedfile then test.fail("expected file to remain open") end end function test.contains(expected, actual) if type(expected) == "table" then for i, v in ipairs(expected) do test.contains(v, actual) end elseif not table.contains(actual, expected) then test.fail("expected value %s not found", expected) end end function test.excludes(expected, actual) if type(expected) == "table" then for i, v in ipairs(expected) do test.excludes(v, actual) end elseif table.contains(actual, expected) then test.fail("excluded value %s found", expected) end end function test.fail(format, ...) -- if format is a number then it is the stack depth local depth = 3 local arg = {...} if type(format) == "number" then depth = depth + format format = table.remove(arg, 1) end -- convert nils into something more usefuls for i = 1, #arg do if (arg[i] == nil) then arg[i] = "(nil)" elseif (type(arg[i]) == "table") then arg[i] = "{" .. table.concat(arg[i], ", ") .. "}" end end local msg = string.format(format, unpack(arg)) error(debug.traceback(msg, depth), depth) end function test.filecontains(expected, fn) local f = io.open(fn) local actual = f:read("*a") f:close() if (expected ~= actual) then test.fail("expected %s but was %s", expected, actual) end end function test.hasoutput() local actual = premake.captured() if actual == "" then test.fail("expected output, received none"); end end function test.isemptycapture() local actual = premake.captured() if actual ~= "" then test.fail("expected empty capture, but was %s", actual); end end function test.isequal(expected, actual, depth) depth = depth or 0 if type(expected) == "table" then if expected and not actual then test.fail(depth, "expected table, got nil") end if #expected < #actual then test.fail(depth, "expected %d items, got %d", #expected, #actual) end for k,v in pairs(expected) do test.isequal(expected[k], actual[k], depth + 1) end else if (expected ~= actual) then test.fail(depth, "expected %s but was %s", expected, actual) end end return true end function test.isfalse(value) if (value) then test.fail("expected false but was true") end end function test.isnil(value) if (value ~= nil) then test.fail("expected nil but was " .. tostring(value)) end end function test.isnotnil(value) if (value == nil) then test.fail("expected not nil") end end function test.issame(expected, action) if expected ~= action then test.fail("expected same value") end end function test.istrue(value) if (not value) then test.fail("expected true but was false") end end function test.missing(value, actual) if table.contains(actual, value) then test.fail("unexpected value %s found", value) end end function test.openedfile(fname) if fname ~= test.value_openedfilename then local msg = "expected to open file '" .. fname .. "'" if test.value_openedfilename then msg = msg .. ", got '" .. test.value_openedfilename .. "'" end test.fail(msg) end end function test.success(fn, ...) local ok, err = pcall(fn, ...) if not ok then test.fail("call failed: " .. err) end end function test.stderr(expected) if not expected and stderr_capture then test.fail("Unexpected: " .. stderr_capture) elseif expected then if not stderr_capture or not stderr_capture:find(expected) then test.fail(string.format("expected '%s'; got %s", expected, stderr_capture or "(nil)")) end end end function test.notstderr(expected) if not expected and not stderr_capture then test.fail("Expected output on stderr; none received") elseif expected then if stderr_capture and stderr_capture:find(expected) then test.fail(string.format("stderr contains '%s'; was %s", expected, stderr_capture)) end end end -- -- Some helper functions -- function test.createWorkspace() local wks = workspace("MyWorkspace") configurations { "Debug", "Release" } local prj = test.createproject(wks) return wks, prj end -- Eventually we'll want to deprecate this one and move everyone -- over to createWorkspace() instead (4 Sep 2015). function test.createsolution() local wks = workspace("MySolution") configurations { "Debug", "Release" } local prj = test.createproject(wks) return wks, prj end function test.createproject(wks) local n = #wks.projects + 1 if n == 1 then n = "" end local prj = project ("MyProject" .. n) language "C++" kind "ConsoleApp" return prj end function test.getWorkspace(wks) p.oven.bake() return p.global.getWorkspace(wks.name) end p.alias(test, "getWorkspace", "getsolution") function test.getproject(wks, i) wks = test.getWorkspace(wks) return p.workspace.getproject(wks, i or 1) end function test.getconfig(prj, buildcfg, platform) local wks = test.getWorkspace(prj.workspace) prj = p.workspace.getproject(wks, prj.name) return p.project.getconfig(prj, buildcfg, platform) end -- -- Test stubs -- local function stub_io_open(fname, mode) test.value_openedfilename = fname test.value_openedfilemode = mode return { close = function() test.value_closedfile = true end } end local function stub_io_output(f) end local function stub_print(s) end local function stub_utf8() end local function stub_os_writefile_ifnotequal(content, fname) test.value_openedfilename = fname; test.value_closedfile = true return 0; end -- -- Define a collection for the test suites -- T = {} -- -- Test execution function -- local _OS_host = _OS local _OPTIONS_host = _OPTIONS local function error_handler(err) local msg = err -- if the error doesn't include a stack trace, add one if not msg:find("stack traceback:", 1, true) then msg = debug.traceback(err, 2) end -- trim of the trailing context of the originating xpcall local i = msg:find("[C]: in function 'xpcall'", 1, true) if i then msg = msg:sub(1, i - 3) end -- if the resulting stack trace is only one level deep, ignore it local n = select(2, msg:gsub('\n', '\n')) if n == 2 then msg = msg:sub(1, msg:find('\n', 1, true) - 1) end return msg end local function test_setup(suite, fn) _ACTION = "test" _OS = _OS_host _OPTIONS = {} setmetatable(_OPTIONS, getmetatable(_OPTIONS_host)) stderr_capture = nil premake.clearWarnings() premake.eol("\n") premake.escaper(nil) premake.indent("\t") premake.api.reset() -- reset captured I/O values test.value_openedfilename = nil test.value_openedfilemode = nil test.value_closedfile = false if suite.setup then return xpcall(suite.setup, error_handler) else return true end end local function test_run(suite, fn) local result, err premake.capture(function() result, err = xpcall(fn, error_handler) end) return result, err end local function test_teardown(suite, fn) if suite.teardown then return xpcall(suite.teardown, error_handler) else return true end end function test.declare(id) if T[id] then error("Duplicate test suite " .. id) end T[id] = { _TESTS_DIR = _TESTS_DIR, _SCRIPT_DIR = _SCRIPT_DIR, } return T[id] end function test.suppress(id) if type(id) == "table" then for i = 1, #id do test.suppress(id[i]) end else test.suppressed[id] = true end end function test.runall(suitename, testname) test.print = print local real_print = print local real_open = io.open local real_output = io.output print = stub_print io.open = stub_io_open io.output = stub_io_output os.writefile_ifnotequal = stub_os_writefile_ifnotequal premake.utf8 = stub_utf8 local numpassed = 0 local numfailed = 0 function runtest(suitename, suitetests, testname, testfunc) if suitetests.setup ~= testfunc and suitetests.teardown ~= testfunc and not test.suppressed[suitename .. "." .. testname] then local ok, err = test_setup(suitetests, testfunc) if ok then ok, err = test_run(suitetests, testfunc) end local tok, terr = test_teardown(suitetests, testfunc) ok = ok and tok err = err or terr if (not ok) then test.print(string.format("%s.%s: %s", suitename, testname, err)) numfailed = numfailed + 1 else numpassed = numpassed + 1 end end end function runsuite(suitename, suitetests, testname) if suitetests and not test.suppressed[suitename] then _TESTS_DIR = suitetests._TESTS_DIR _SCRIPT_DIR = suitetests._SCRIPT_DIR if testname then runtest(suitename, suitetests, testname, suitetests[testname]) else for testname, testfunc in pairs(suitetests) do if type(testfunc) == "function" then runtest(suitename, suitetests, testname, testfunc) end end end end end if suitename then runsuite(suitename, T[suitename], testname) else for suitename, suitetests in pairs(T) do runsuite(suitename, suitetests, testname) end end print = real_print io.open = real_open io.output = real_output return numpassed, numfailed end
bsd-3-clause
april-org/april-ann
packages/ann/autoencoders/test/test.lua
3
8265
m1 = ImageIO.read(string.get_path(arg[0]) .. "digits.png"):to_grayscale():invert_colors():matrix() bunch_size = 32 dropout_factor = 0.5 dropout_random = random(123242) train_input = dataset.matrix(m1, { patternSize = {16,16}, offset = {0,0}, numSteps = {80,10}, stepSize = {16,16}, orderStep = {1,0} }) val_input = dataset.matrix(m1, { patternSize = {16,16}, offset = {1280,0}, numSteps = {20,10}, stepSize = {16,16}, orderStep = {1,0} }) m2 = matrix(10,{1,0,0,0,0,0,0,0,0,0}) train_output = dataset.matrix(m2, { patternSize = {10}, offset = {0}, numSteps = {800}, stepSize = {-1}, circular = {true} }) val_output = dataset.matrix(m2, { patternSize = {10}, offset = {0}, numSteps = {200}, stepSize = {-1}, circular = {true} }) layers_table = { { size= 256, actf="logistic"}, -- INPUT LAYER { size= 256, actf="logistic"}, -- FIRST HIDDEN LAYER } perturbation_prob = random(9283424) params_pretrain = { input_dataset = train_input, replacement = nil, shuffle_random = random(1234), weights_random = random(7890), layers = layers_table, -- OUTPUT LAYER (SUPERVISED): classification task, 10 classes (10 digits) supervised_layer = { size = 10, actf = "log_softmax" }, output_datasets = { train_output }, bunch_size = 256, optimizer = function() return ann.optimizer.cg() end, -- training parameters training_options = { global = { ann_options = { weight_decay = 1e-05, rho=0.0001, sig=0.8 }, noise_pipeline = { function(ds) return dataset.perturbation{ dataset = ds, -- WARNING: the function argument mean = 0, variance = 0.01, random = perturbation_prob } end, function(ds) return dataset.salt_noise{ dataset = ds, -- WARNING: the function argument vd = 0.20, zero = 0.0, random = perturbation_prob } end }, min_epochs = 1, max_epochs = 2, pretraining_percentage_stopping_criterion = 0.1, }, } } loss_name = "multi_class_cross_entropy" sdae_table,deep_classifier = ann.autoencoders.greedy_layerwise_pretraining(params_pretrain) codifier_net = ann.autoencoders.build_codifier_from_sdae_table(sdae_table, layers_table) function set_dropout(stack) if dropout_factor > 0.0 then local new_stack = ann.components.stack() for i=1,stack:size(),2 do new_stack:push( stack:get(i), stack:get(i+1) ) if i < stack:size()-2 then new_stack:push( ann.components.dropout{ name="dropout-".. (i+1)/2, prob=dropout_factor, random=dropout_random } ) end end return new_stack else return stack end end deep_classifier = set_dropout(deep_classifier) trainer_deep_classifier = trainable.supervised_trainer(deep_classifier, ann.loss[loss_name](10), bunch_size, ann.optimizer.cg()) trainer_deep_classifier:build() trainer_deep_classifier:set_option("rho", 0.0001) trainer_deep_classifier:set_option("sig", 0.8) -- shallow_classifier = ann.mlp.all_all.generate("256 inputs 256 tanh 128 tanh 10 log_softmax") shallow_classifier = set_dropout(shallow_classifier) trainer_shallow_classifier = trainable.supervised_trainer(shallow_classifier, ann.loss[loss_name](10), bunch_size) trainer_shallow_classifier:build() trainer_shallow_classifier:randomize_weights { random = random(1234), inf = -0.1, sup = 0.1 } -- deep_classifier_wo_pretraining = ann.mlp.all_all.generate("256 inputs 256 logistic 256 logistic 256 logistic 10 log_softmax") deep_classifier_wo_pretraining = set_dropout(deep_classifier_wo_pretraining) trainer_deep_wo_pretraining = trainable.supervised_trainer(deep_classifier_wo_pretraining, ann.loss[loss_name](10), bunch_size) trainer_deep_wo_pretraining:build() trainer_deep_wo_pretraining:randomize_weights{ random = random(1234), inf = -0.1, sup = 0.1 } train_input = dataset.salt_noise{ dataset = train_input, vd = 0.2, zero = 0.0, random = random(95285) } datosentrenar_deep = { input_dataset = train_input, output_dataset = train_output, shuffle = random(8569), bunch_size = 512, } datosentrenar_shallow = { input_dataset = train_input, output_dataset = train_output, shuffle = random(8569) } datosentrenar_deep_wo = { input_dataset = train_input, output_dataset = train_output, shuffle = random(8569) } datosvalidar = { input_dataset = val_input, output_dataset = val_output } -- we scale the weights before dropout if dropout_factor > 0.0 then for name,cnn in trainer_deep_classifier:iterate_weights("^w.*$") do if name ~= "w1" then if cnn.matrix then local w,ow = cnn:matrix() w:scal(1.0/(1.0-dropout_factor)) ow:scal(1.0/(1.0-dropout_factor)) else cnn:scal(1.0/(1.0-dropout_factor)) end end end end print(trainer_deep_classifier:validate_dataset(datosvalidar)) --trainer_deep_classifier:set_option("learning_rate", 0.4) --trainer_deep_classifier:set_option("momentum", 0.0) trainer_deep_classifier:set_option("weight_decay", 0.0) trainer_deep_classifier:set_option("max_norm_penalty", 4.0) trainer_shallow_classifier:set_option("learning_rate", 0.4) trainer_shallow_classifier:set_option("momentum", 0.1) trainer_shallow_classifier:set_option("weight_decay", trainer_deep_classifier:get_option("weight_decay")) trainer_shallow_classifier:set_option("max_norm_penalty", trainer_deep_classifier:get_option("max_norm_penalty")) trainer_deep_wo_pretraining:set_option("learning_rate", trainer_shallow_classifier:get_option("learning_rate")) trainer_deep_wo_pretraining:set_option("momentum", trainer_shallow_classifier:get_option("momentum")) trainer_deep_wo_pretraining:set_option("weight_decay", trainer_deep_classifier:get_option("weight_decay")) trainer_deep_wo_pretraining:set_option("max_norm_penalty", trainer_deep_classifier:get_option("max_norm_penalty")) trainer_deep_classifier:set_layerwise_option("b.*", "max_norm_penalty",0.0) trainer_deep_wo_pretraining:set_layerwise_option("b.*", "max_norm_penalty",0.0) trainer_shallow_classifier:set_layerwise_option("b.*", "max_norm_penalty",0.0) trainer_deep_classifier:set_layerwise_option("b.*", "weight_decay",0.0) trainer_deep_wo_pretraining:set_layerwise_option("b.*", "weight_decay",0.0) trainer_shallow_classifier:set_layerwise_option("b.*", "weight_decay",0.0) for i=1,2 do local mse_tr_deep = trainer_deep_classifier:train_dataset(datosentrenar_deep) local mse_tr_deep_wo = trainer_deep_wo_pretraining:train_dataset(datosentrenar_deep_wo) local mse_tr_shallow = trainer_shallow_classifier:train_dataset(datosentrenar_shallow) local mse_val_deep = trainer_deep_classifier:validate_dataset(datosvalidar) local mse_val_deep_wo = trainer_deep_wo_pretraining:validate_dataset(datosvalidar) local mse_val_shallow = trainer_shallow_classifier:validate_dataset(datosvalidar) printf("%5d %.6f %.6f \t %.6f %.6f \t %.6f %.6f\n", i, mse_tr_deep, mse_val_deep, mse_tr_deep_wo, mse_val_deep_wo, mse_tr_shallow, mse_val_shallow) if trainer_deep_classifier:has_option("learning_rate") then trainer_deep_classifier:set_option("learning_rate", trainer_deep_classifier:get_option("learning_rate")*0.99) end end -- classification print(trainer_deep_classifier:validate_dataset{ input_dataset = val_input, output_dataset = val_output, loss = ann.loss.zero_one() }) print(trainer_deep_wo_pretraining:validate_dataset{ input_dataset = val_input, output_dataset = val_output, loss = ann.loss.zero_one() }) print(trainer_shallow_classifier:validate_dataset{ input_dataset = val_input, output_dataset = val_output, loss = ann.loss.zero_one() }) local img = ann.connections.input_filters_image(trainer_deep_classifier:weights("w1"), {16,16}) ImageIO.write(img, "/tmp/filters.png")
gpl-3.0
Kazuo256/luxproject
lib/lux/info.lua
1
1452
--[[ -- -- Copyright (c) 2013-2017 Wilson Kazuo Mizutani -- -- Permission is hereby granted, free of charge, to any person obtaining a copy -- of this software and associated documentation files (the "Software"), to -- deal in the Software without restriction, including without limitation the -- rights to use, copy, modify, merge, publish, distribute, sublicense, and/or -- sell copies of the Software, and to permit persons to whom the Software is -- furnished to do so, subject to the following conditions: -- -- The above copyright notice and this permission notice shall be included in -- all copies or substantial portions of the Software. -- -- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR -- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, -- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE -- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER -- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, -- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE -- SOFTWARE -- --]] --- Module containing information regarding this LUX Project distribution. -- @module lux.info local info = {} local major = 0 local minor = 6 local patch = 0 --- LUX's version. -- @return A string with the current LUX version. function info.version () return major..'.'..minor..'.'..patch end return info
mit
satanevil/hellbot
plugins/inpm.lua
1114
3008
do local function pairsByKeys (t, f) local a = {} for n in pairs(t) do table.insert(a, n) end table.sort(a, f) local i = 0 -- iterator variable local iter = function () -- iterator function i = i + 1 if a[i] == nil then return nil else return a[i], t[a[i]] end end return iter end local function chat_list(msg) local data = load_data(_config.moderation.data) local groups = 'groups' if not data[tostring(groups)] then return 'No groups at the moment' end local message = 'List of Groups:\n*Use /join (ID) to join*\n\n ' for k,v in pairs(data[tostring(groups)]) do local settings = data[tostring(v)]['settings'] for m,n in pairsByKeys(settings) do if m == 'set_name' then name = n end end message = message .. '👥 '.. name .. ' (ID: ' .. v .. ')\n\n ' end local file = io.open("./groups/lists/listed_groups.txt", "w") file:write(message) file:flush() file:close() return message end local function run(msg, matches) if msg.to.type ~= 'chat' or is_sudo(msg) or is_admin(msg) and is_realm(msg) then local data = load_data(_config.moderation.data) if matches[1] == 'join' and data[tostring(matches[2])] then if is_banned(msg.from.id, matches[2]) then return 'You are banned.' end if is_gbanned(msg.from.id) then return 'You are globally banned.' end if data[tostring(matches[2])]['settings']['lock_member'] == 'yes' and not is_owner2(msg.from.id, matches[2]) then return 'Group is private.' end local chat_id = "chat#id"..matches[2] local user_id = "user#id"..msg.from.id chat_add_user(chat_id, user_id, ok_cb, false) local group_name = data[tostring(matches[2])]['settings']['set_name'] return "Added you to chat:\n\n👥"..group_name.." (ID:"..matches[2]..")" elseif matches[1] == 'join' and not data[tostring(matches[2])] then return "Chat not found." end if matches[1] == 'chats'then if is_admin(msg) and msg.to.type == 'chat' then return chat_list(msg) elseif msg.to.type ~= 'chat' then return chat_list(msg) end end if matches[1] == 'chatlist'then if is_admin(msg) and msg.to.type == 'chat' then send_document("chat#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) elseif msg.to.type ~= 'chat' then send_document("user#id"..msg.from.id, "./groups/lists/listed_groups.txt", ok_cb, false) end end end end return { patterns = { "^[/!](chats)$", "^[/!](chatlist)$", "^[/!](join) (.*)$", "^[/!](kickme) (.*)$", "^!!tgservice (chat_add_user)$" }, run = run, } end
gpl-2.0
permag-ir/permag.ir
libs/url.lua
31
8003
-- کد های پایین در ربات نشان داده نمیشوند -- http://permag.ir -- @permag_ir -- @permag_bots -- @permag local string = require("string") local base = _G local table = require("table") local Url={} Url._VERSION = "URL 1.0.2" function Url.escape(s) return string.gsub(s, "([^A-Za-z0-9_])", function(c) return string.format("%%%02x", string.byte(c)) end) end local function make_set(t) local s = {} for i,v in base.ipairs(t) do s[t[i]] = 1 end return s end local segment_set = make_set { "-", "_", ".", "!", "~", "*", "'", "(", ")", ":", "@", "&", "=", "+", "$", ",", } local function protect_segment(s) return string.gsub(s, "([^A-Za-z0-9_])", function (c) if segment_set[c] then return c else return string.format("%%%02x", string.byte(c)) end end) end function Url.unescape(s) return string.gsub(s, "%%(%x%x)", function(hex) return string.char(base.tonumber(hex, 16)) end) end local function absolute_path(base_path, relative_path) if string.sub(relative_path, 1, 1) == "/" then return relative_path end local path = string.gsub(base_path, "[^/]*$", "") path = path .. relative_path path = string.gsub(path, "([^/]*%./)", function (s) if s ~= "./" then return s else return "" end end) path = string.gsub(path, "/%.$", "/") local reduced while reduced ~= path do reduced = path path = string.gsub(reduced, "([^/]*/%.%./)", function (s) if s ~= "../../" then return "" else return s end end) end path = string.gsub(reduced, "([^/]*/%.%.)$", function (s) if s ~= "../.." then return "" else return s end end) return path end ----------------------------------------------------------------------------- -- Parses a url and returns a table with all its parts according to RFC 2396 -- The following grammar describes the names given to the URL parts -- <url> ::= <scheme>://<authority>/<path>;<params>?<query>#<fragment> -- <authority> ::= <userinfo>@<host>:<port> -- <userinfo> ::= <user>[:<password>] -- <path> :: = {<segment>/}<segment> -- Input -- url: uniform resource locator of request -- default: table with default values for each field -- Returns -- table with the following fields, where RFC naming conventions have -- been preserved: -- scheme, authority, userinfo, user, password, host, port, -- path, params, query, fragment -- Obs: -- the leading '/' in {/<path>} is considered part of <path> ----------------------------------------------------------------------------- function Url.parse(url, default) -- initialize default parameters local parsed = {} for i,v in base.pairs(default or parsed) do parsed[i] = v end -- empty url is parsed to nil if not url or url == "" then return nil, "invalid url" end -- remove whitespace -- url = string.gsub(url, "%s", "") -- get fragment url = string.gsub(url, "#(.*)$", function(f) parsed.fragment = f return "" end) -- get scheme url = string.gsub(url, "^([%w][%w%+%-%.]*)%:", function(s) parsed.scheme = s; return "" end) -- get authority url = string.gsub(url, "^//([^/]*)", function(n) parsed.authority = n return "" end) -- get query stringing url = string.gsub(url, "%?(.*)", function(q) parsed.query = q return "" end) -- get params url = string.gsub(url, "%;(.*)", function(p) parsed.params = p return "" end) -- path is whatever was left if url ~= "" then parsed.path = url end local authority = parsed.authority if not authority then return parsed end authority = string.gsub(authority,"^([^@]*)@", function(u) parsed.userinfo = u; return "" end) authority = string.gsub(authority, ":([^:]*)$", function(p) parsed.port = p; return "" end) if authority ~= "" then parsed.host = authority end local userinfo = parsed.userinfo if not userinfo then return parsed end userinfo = string.gsub(userinfo, ":([^:]*)$", function(p) parsed.password = p; return "" end) parsed.user = userinfo return parsed end ----------------------------------------------------------------------------- -- Rebuilds a parsed URL from its components. -- Components are protected if any reserved or unallowed characters are found -- Input -- parsed: parsed URL, as returned by parse -- Returns -- a stringing with the corresponding URL ----------------------------------------------------------------------------- function Url.build(parsed) local ppath = Url.parse_path(parsed.path or "") local url = Url.build_path(ppath) if parsed.params then url = url .. ";" .. parsed.params end if parsed.query then url = url .. "?" .. parsed.query end local authority = parsed.authority if parsed.host then authority = parsed.host if parsed.port then authority = authority .. ":" .. parsed.port end local userinfo = parsed.userinfo if parsed.user then userinfo = parsed.user if parsed.password then userinfo = userinfo .. ":" .. parsed.password end end if userinfo then authority = userinfo .. "@" .. authority end end if authority then url = "//" .. authority .. url end if parsed.scheme then url = parsed.scheme .. ":" .. url end if parsed.fragment then url = url .. "#" .. parsed.fragment end -- url = string.gsub(url, "%s", "") return url end -- Builds a absolute URL from a base and a relative URL according to RFC 2396 function Url.absolute(base_url, relative_url) if base.type(base_url) == "table" then base_parsed = base_url base_url = Url.build(base_parsed) else base_parsed = Url.parse(base_url) end local relative_parsed = Url.parse(relative_url) if not base_parsed then return relative_url elseif not relative_parsed then return base_url elseif relative_parsed.scheme then return relative_url else relative_parsed.scheme = base_parsed.scheme if not relative_parsed.authority then relative_parsed.authority = base_parsed.authority if not relative_parsed.path then relative_parsed.path = base_parsed.path if not relative_parsed.params then relative_parsed.params = base_parsed.params if not relative_parsed.query then relative_parsed.query = base_parsed.query end end else relative_parsed.path = absolute_path(base_parsed.path or "", relative_parsed.path) end end return Url.build(relative_parsed) end end -- Breaks a path into its segments, unescaping the segments function Url.parse_path(path) local parsed = {} path = path or "" --path = string.gsub(path, "%s", "") string.gsub(path, "([^/]+)", function (s) table.insert(parsed, s) end) for i = 1, #parsed do parsed[i] = Url.unescape(parsed[i]) end if string.sub(path, 1, 1) == "/" then parsed.is_absolute = 1 end if string.sub(path, -1, -1) == "/" then parsed.is_directory = 1 end return parsed end -- Builds a path component from its segments, escaping protected characters. function Url.build_path(parsed, unsafe) local path = "" local n = #parsed if unsafe then for i = 1, n-1 do path = path .. parsed[i] path = path .. "/" end if n > 0 then path = path .. parsed[n] if parsed.is_directory then path = path .. "/" end end else for i = 1, n-1 do path = path .. protect_segment(parsed[i]) path = path .. "/" end if n > 0 then path = path .. protect_segment(parsed[n]) if parsed.is_directory then path = path .. "/" end end end if parsed.is_absolute then path = "/" .. path end return path end return Url -- کد های پایین در ربات نشان داده نمیشوند -- http://permag.ir -- @permag_ir -- @permag_bots -- @permag
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Silver_Knife/Zone.lua
19
1059
----------------------------------- -- -- Zone: Silver Knife -- ----------------------------------- require("scripts/globals/settings"); package.loaded["scripts/zones/Silver_Knife/TextIDs"] = nil; require("scripts/zones/Silver_Knife/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) cs = -1; return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
aStonedPenguin/fprp
gamemode/modules/positions/sv_spawnpos.lua
1
1739
local function SetSpawnPos(ply, args) if not ply:hasfprpPrivilege("rp_commands") then fprp.notify(ply, 1, 2, fprp.getPhrase("need_admin", "setspawn")); return "" end local pos = string.Explode(" ", tostring(ply:GetPos())); local t for k,v in pairs(RPExtraTeams) do if args == v.command then t = k fprp.notify(ply, 0, 4, fprp.getPhrase("created_spawnpos", v.name)); end end if t then fprp.storeTeamSpawnPos(t, pos); else fprp.notify(ply, 1, 4, fprp.getPhrase("could_not_find", tostring(args))); end return "" end fprp.defineChatCommand("setspawn", SetSpawnPos); local function AddSpawnPos(ply, args) if not ply:hasfprpPrivilege("rp_commands") then fprp.notify(ply, 1, 2, fprp.getPhrase("need_admin", "addspawn")); return "" end local pos = string.Explode(" ", tostring(ply:GetPos())); local t for k,v in pairs(RPExtraTeams) do if args == v.command then t = k fprp.notify(ply, 0, 4, fprp.getPhrase("updated_spawnpos", v.name)); end end if t then fprp.addTeamSpawnPos(t, pos); else fprp.notify(ply, 1, 4, fprp.getPhrase("could_not_find", tostring(args))); end return "" end fprp.defineChatCommand("addspawn", AddSpawnPos); local function RemoveSpawnPos(ply, args) if not ply:hasfprpPrivilege("rp_commands") then fprp.notify(ply, 1, 2, fprp.getPhrase("need_admin", "remove spawn")); return "" end local t for k,v in pairs(RPExtraTeams) do if args == v.command then t = k fprp.notify(ply, 0, 4, fprp.getPhrase("updated_spawnpos", v.name)); break end end if t then fprp.removeTeamSpawnPos(t); else fprp.notify(ply, 1, 4, fprp.getPhrase("could_not_find", tostring(args))); end return "" end fprp.defineChatCommand("removespawn", RemoveSpawnPos);
mit
Igalia/snabb
src/lib/protocol/ipv6.lua
7
5307
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local header = require("lib.protocol.header") local htons, ntohs = lib.htons, lib.ntohs local AF_INET6 = 10 local INET6_ADDRSTRLEN = 48 local defaults = { traffic_class = 0, flow_label = 0, next_header = 59, -- no next header hop_limit = 64, } local ipv6hdr_pseudo_t = ffi.typeof[[ struct { char src_ip[16]; char dst_ip[16]; uint16_t ulp_zero; uint16_t ulp_length; uint8_t zero[3]; uint8_t next_header; } __attribute__((packed)) ]] local ipv6_addr_t = ffi.typeof("uint16_t[8]") local ipv6 = subClass(header) -- Class variables ipv6._name = "ipv6" ipv6._ulp = { class_map = { [6] = "lib.protocol.tcp", [17] = "lib.protocol.udp", [47] = "lib.protocol.gre", [58] = "lib.protocol.icmp.header", [115] = "lib.protocol.keyed_ipv6_tunnel", }, method = 'next_header' } header.init(ipv6, { [1] = ffi.typeof[[ struct { uint32_t v_tc_fl; // version, tc, flow_label uint16_t payload_length; uint8_t next_header; uint8_t hop_limit; uint8_t src_ip[16]; uint8_t dst_ip[16]; } __attribute__((packed)) ]] }) -- Class methods function ipv6:new (config) local o = ipv6:superClass().new(self) if not o._recycled then o._ph = ipv6hdr_pseudo_t() end o:version(6) o:traffic_class(config.traffic_class or defaults.traffic_class) o:flow_label(config.flow_label or defaults.flow_label) o:next_header(config.next_header or defaults.next_header) o:hop_limit(config.hop_limit or defaults.hop_limit) o:src(config.src) o:dst(config.dst) return o end function ipv6:new_from_mem(mem, size) local o = ipv6:superClass().new_from_mem(self, mem, size) if o == nil then return nil end if not o._recycled then o._ph = ipv6hdr_pseudo_t() end return o end function ipv6:pton (p) local in_addr = ffi.new("uint8_t[16]") local result = C.inet_pton(AF_INET6, p, in_addr) if result ~= 1 then return false, "malformed IPv6 address: " .. p end return in_addr end function ipv6:ntop (n) local p = ffi.new("char[?]", INET6_ADDRSTRLEN) local c_str = C.inet_ntop(AF_INET6, n, p, INET6_ADDRSTRLEN) return ffi.string(c_str) end function ipv6:get() return self:ntop(self) end function ipv6:set(addr) self:pton(addr) end -- Construct the solicited-node multicast address from the given -- unicast address by appending the last 24 bits to ff02::1:ff00:0/104 function ipv6:solicited_node_mcast (n) local n = ffi.cast("uint8_t *", n) local result = self:pton("ff02:0:0:0:0:1:ff00:0") ffi.copy(ffi.cast("uint8_t *", result)+13, n+13, 3) return result end -- Instance methods function ipv6:version (v) return lib.bitfield(32, self:header(), 'v_tc_fl', 0, 4, v) end function ipv6:traffic_class (tc) return lib.bitfield(32, self:header(), 'v_tc_fl', 4, 8, tc) end function ipv6:dscp (dscp) return lib.bitfield(32, self:header(), 'v_tc_fl', 4, 6, dscp) end function ipv6:ecn (ecn) return lib.bitfield(32, self:header(), 'v_tc_fl', 10, 2, ecn) end function ipv6:flow_label (fl) return lib.bitfield(32, self:header(), 'v_tc_fl', 12, 20, fl) end function ipv6:payload_length (length) if length ~= nil then self:header().payload_length = htons(length) else return(ntohs(self:header().payload_length)) end end function ipv6:next_header (nh) if nh ~= nil then self:header().next_header = nh else return(self:header().next_header) end end function ipv6:hop_limit (limit) if limit ~= nil then self:header().hop_limit = limit else return(self:header().hop_limit) end end function ipv6:src (ip) if ip ~= nil then ffi.copy(self:header().src_ip, ip, 16) else return self:header().src_ip end end function ipv6:src_eq (ip) return C.memcmp(ip, self:header().src_ip, 16) == 0 end function ipv6:dst (ip) if ip ~= nil then ffi.copy(self:header().dst_ip, ip, 16) else return self:header().dst_ip end end function ipv6:dst_eq (ip) return C.memcmp(ip, self:header().dst_ip, 16) == 0 end -- Return a pseudo header for checksum calculation in a upper-layer -- protocol (e.g. icmp). Note that the payload length and next-header -- values in the pseudo-header refer to the effective upper-layer -- protocol. They differ from the respective values of the ipv6 -- header if extension headers are present. function ipv6:pseudo_header (plen, nh) local ph = self._ph ffi.fill(ph, ffi.sizeof(ph)) local h = self:header() ffi.copy(ph, h.src_ip, 32) -- Copy source and destination ph.ulp_length = htons(plen) ph.next_header = nh return(ph) end function selftest() local ipv6_address = "2001:620:0:c101::2" assert(ipv6_address == ipv6:ntop(ipv6:pton(ipv6_address)), 'ipv6 text to binary conversion failed.') end ipv6.selftest = selftest return ipv6
apache-2.0
april-org/april-ann
TEST/xor/xor-MLP-dot-product-action-transpose-weights.lua
3
4626
learning_rate = 0.4 momentum = 0.1 weight_decay = 1e-05 semilla = 1234 aleat = random(semilla) bunch_size = tonumber(arg[1]) or 64 delta = 1e-05 initial_result = { 0.18666581809521, 0.16942968964577, 0.17109067738056, 0.14423334598541 } final_result = { 0.0135539099, 0.9875200987, 0.9875199199, 0.0143862367 } m = matrix.fromString[[ 19 ascii 1.0 0.1 0.2 -1.0 0.3 0.4 -0.5 -1.2 1.0 -2.0 4.0 -4.0 0.1 1.1 -1.5 -1.0 2.0 2.0 -1.0 ]] bias0_m = matrix.fromString[[ 2 ascii 1.0 -1.0 ]] bias1_m = matrix.fromString[[ 3 ascii -0.5 -2.0 0.1 ]] bias2_m = matrix.fromString[[ 1 ascii -1.0 ]] w0_m = matrix.fromString[[ 4 ascii 0.1 0.2 0.3 0.4 ]] w1t_m = matrix.fromString[[ 6 ascii -1.2 4.0 1.1 1.0 -4.0 -1.5 ]] w2_m = matrix.fromString[[ 3 ascii 2.0 2.0 -1.0 ]] function show_weights(lared) lared:show_weights() print() local outds = dataset.matrix(matrix(4)) lared:use_dataset{ input_dataset = ds_input, output_dataset = outds } for i = 1,ds_input:numPatterns() do value = lared:calculate(ds_input:getPattern(i))[1] printf("%s\t %s\t %s\n", table.concat(ds_input:getPattern(i),","), value, outds:getPattern(i)[1]) end print() end function check_result(lared, result) local outds = dataset.matrix(matrix(4)) lared:use_dataset{ input_dataset = ds_input, output_dataset = outds } for i = 1,ds_input:numPatterns() do value = lared:calculate(ds_input:getPattern(i))[1] if math.abs(value - result[i]) > delta then error("Incorrect result using bunch_size=1!!! expected " .. value .. " was " .. result[i]) end if math.abs(outds:getPattern(i)[1] - result[i]) > delta then error("Incorrect result using bunch_size=" .. bunch_size .."!!!") end end end ----------------------------------------------------------- lared = ann.mlp{ bunch_size = bunch_size } -- neuron layers i = ann.units.real_cod{ size = 2, ann = lared, type = "inputs" } h0 = ann.units.real_cod{ size = 2, ann = lared, type = "hidden" } h1 = ann.units.real_cod{ size = 3, ann = lared, type = "hidden" } o = ann.units.real_cod{ size = 1, ann = lared, type = "outputs" } -- connection layers b0 = ann.connections.bias{ size = h0:num_neurons(), ann = lared, w = bias0_m } c0 = ann.connections.all_all{ input_size = i:num_neurons(), output_size = h0:num_neurons(), ann = lared, w = w0_m} b1 = ann.connections.bias{ size = h1:num_neurons(), ann = lared, w = bias1_m } c1 = ann.connections.all_all{ input_size = h1:num_neurons(), output_size = h0:num_neurons(), ann = lared, w = w1t_m } b2 = ann.connections.bias{ size = o:num_neurons(), ann = lared, w = bias2_m } c2 = ann.connections.all_all{ input_size = h1:num_neurons(), output_size = o:num_neurons(), ann = lared, w = w2_m } -- first layer actions lared:push_back_all_all_layer{ input = i, output = h0, bias = b0, weights = c0, actfunc = ann.activations.tanh() } -- second layer actions lared:push_back_all_all_layer{ input = h0, output = h1, bias = b1, weights = c1, actfunc = ann.activations.tanh(), transpose = true } -- third layer actions lared:push_back_all_all_layer{ input = h1, output = o, bias = b2, weights = c2, actfunc = ann.activations.logistic() } lared:set_option("learning_rate", learning_rate) lared:set_option("momentum", momentum) lared:set_option("weight_decay", weight_decay) lared2=ann.mlp.all_all.generate{ topology = "2 inputs 2 tanh 3 tanh 1 logistic", w = m, oldw = m, bunch_size = bunch_size, } lared2:set_option("learning_rate", learning_rate) lared2:set_option("momentum", momentum) lared2:set_option("weight_decay", weight_decay) m_xor = matrix.fromString[[ 4 3 ascii 0 0 0 0 1 1 1 0 1 1 1 0 ]] ds_input = dataset.matrix(m_xor,{patternSize={1,2}}) ds_output = dataset.matrix(m_xor,{offset={0,2},patternSize={1,1}}) -------- -- GO -- -------- check_result(lared, initial_result) check_result(lared2, initial_result) data = { input_dataset = ds_input, output_dataset = ds_output, shuffle = random(1234) } data2 = { input_dataset = ds_input, output_dataset = ds_output, shuffle = random(1234) } for i=1,30000 do lared:train_dataset(data) lared2:train_dataset(data2) end check_result(lared, final_result) check_result(lared2, final_result) print("TEST PASSED!")
gpl-3.0
zfm888/bazi_server
app/v1/paiPan/index.lua
1
4882
--[[ 八字信息获取接口 --]] local base = require "resty.core.base" local format = string.format local decode = WEBSERVER_formatter.decode local json = WEBSERVER_formatter.json local empty = WEBSERVER_table.empty local split = WEBSERVER_str.split local bazi = require "bazi" local function strToTimetable(timeStr) local a = split(timeStr, " ") local b = split(a[1], "-") local c = split(a[2], ":") local dt = { year = tonumber(b[1]), month = tonumber(b[2]), day = tonumber(b[3]), hour = tonumber(c[1]), min = tonumber(c[2]), sec = tonumber(c[3]) } return dt end local function baziPaiPanProc(params) local birthday,sex,ast = params.birthday,params.sex,params.astFlag local lon,lifa = params.longitude,params.calendar local data = {} --时间格式统一为 yyyy-MM-dd hh:mm:ss,输入时分秒在没有时默认为0 local dt = strToTimetable(birthday) local bz = bazi:new(dt,sex,ast,lon,lifa) bz:Paipan() --定气方式 local lifaInfo = bz:printLifa() --公历生日 local mstBirthInfo = bz:printMst() --农历生日 local lunarBirthInfo = bz:printLunar() --虚岁 local nominalAge = bz:printAge() --真太阳时 local astInfo = bz:renderAST() --节气 local solarInfo = bz:renderSolarterms() --四柱信息 local baziInfo = bz:renderBaZi() --大运信息 local dayunInfo = bz:renderDaYun() data = { lifa = lifaInfo, mstBirth = mstBirthInfo, lunarBirth = lunarBirthInfo, nominalAge = nominalAge, ast = astInfo, solar = solarInfo, bazi = baziInfo, dayun = dayunInfo } return data end local function doBusiness(params) if empty(params) then return WEBSERVER_error.busi_error("request params is empty!") end local status,baziData = pcall(baziPaiPanProc,params) if empty(baziData) then return WEBSERVER_error.busi_error("can't get correct bazi information!") end return baziData end local function getParams() local req = WEBSERVER_request:new() if string.upper(req.method) ~= 'POST' then WEBSERVER_error.param_error('http method is not POST, params error') end local reqBody = req:get_request_body() local status, reqJson = pcall(decode, reqBody) if not status then WEBSERVER_error.param_error('decode request body params error') end local data = reqJson["data"] local params = {} if data then --birthday(生日),sex(性别),AST(太阳时 apparent solar time) --lon(出生地经度:longitude),lifa(历法 calendar ) local birthday = data["birthday"] --生日 local sex = tonumber(data["sex"]) --性别 local astFlag = tonumber(data["astFlag"]) --是否真太阳时 local longitude = tonumber(data["longitude"]) --出生地级度 local calendar = tonumber(data["calendar"]) if not birthday or type(birthday) ~= 'string' then WEBSERVER_error.param_error("birthday params error") end if not sex or sex < 0 then WEBSERVER_error.param_error("sex params error") end if not astFlag then astFlag = 0 else if astFlag ~= 0 and astFlag ~=1 then WEBSERVER_error.param_error("apparent solar time params error") end end --默认中央经度 if not longitude then longitude = 120 end --默认平气法定冬至 if not calendar then calendar = 12 end params['birthday'] = birthday params['sex'] = sex params['astFlag'] = astFlag params['longitude'] = longitude params['calendar'] = calendar end return params end local function output(format_result) local resp = WEBSERVER_response:new() resp:write(format_result) resp:finish() end ------------------------------------------------------------ -- main script begin here : local status, params = pcall(getParams) local result = {} if status then local status, data = pcall(doBusiness,params) --ngx.log(ngx.DEBUG,"data type is "..(data)) if status then if data == nil then result["code"] = 200 result["msg"] = 'biz_error' result["data"] = '' else result["code"] = 0 result["msg"] = '' result["data"] = data end else result["code"] = data.code or 200 result["msg"] = data.msg or "biz_error" result["data"] = '' end else result["code"] = params.code result["msg"] = params.msg result["data"] = '' end local res = WEBSERVER_formatter.json(result) output(res)
gpl-3.0
Xamla/xamla_egomo
egomo_tools/lua/robot_control.lua
1
15903
--- A module for moving the robot with ROS and MoveIT -- @classmod RobotControl local function checkModuleInstalled(name) if package.loaded[name] then -- package already loaded, so it exists return true else for _, searcher in ipairs(package.searchers or package.loaders) do local loader = searcher(name) if type(loader) == 'function' then package.preload[name] = loader return true end end return false end end -- Import section local ros = require 'ros' local moveit if checkModuleInstalled('moveit') then moveit = require 'moveit' else moveit = nil end local tf = ros.tf local sleep = sys.sleep local math = math local sock = require 'socket' local ffi =require 'ffi' -- no more external access after this point _ENV = nil RobotControl = { robotAvailable, rosMoveGroup, planningScene, rosSpinner, } --- Constructor of the robot class. -- It initializes ROS, adds collision objects to the scene (right now they fit to the Xamla lab -- and have to be changed if the robot is positioned in a different environment). -- It also initializes the movegroups for MoveIT. -- @param idString string that identifies the robots node in ROS -- @param robotSpeed maximum speed of the robot. The value may be beteen zero and one function RobotControl:new(idString, robotSpeed) o = {} setmetatable(o, self) self.__index = self if moveit == nil then print("moveit not found") robotAvailable=false ros.init(idString) -- short initialisation, just for ROS but no moment/scene related things ros.Time.init() rosSpinner = ros.AsyncSpinner() -- background job rosSpinner:start() else -- full initialisation robotSpeed = robotSpeed or 0.1 if robotSpeed > 1 then print("Invalid velocity scaling factor: "..robotSpeed". Valid range: 0 to 1") print("Scaling set to 0.4") robotSpeed=0.4 end print("Robot speed scaling set to "..robotSpeed) ros.init(idString) ros.Time.init() rosSpinner = ros.AsyncSpinner() -- background job rosSpinner:start() self.planningScene = moveit.PlanningSceneInterface() self.planningScene:addPlane('ground plane', 0, 0, 1, -0.001) self.rosMoveGroup = moveit.MoveGroup('manipulator') self.rosMoveGroup:setPlanningTime(10.0); self.rosMoveGroup:setMaxVelocityScalingFactor(robotSpeed) self.rosMoveGroup:setGoalTolerance(1E-4) -- self.rosMoveGroup:setPlannerId("BKPIECEkConfigDefault"); self.rosMoveGroup:getCurrentState() self.rosMoveGroup:setStartStateToCurrentState() print('Current end effector link:') print(self.rosMoveGroup:getEndEffectorLink()) -- Collision box for table box_pose = tf.Transform() box_pose:setOrigin({0.05, 0.45, -0.431}) rot = box_pose:getRotation() rot:setRPY(0,0,-45,1) box_pose:setRotation(rot) self.planningScene:addBox('ground', 0.8, 0.90, 0.8, box_pose) -- Collision box for wall boxWall_pose = tf.Transform() boxWall_pose:setOrigin({-0.0, -0.45, 0.0}) rot = boxWall_pose:getRotation() rot:setRPY(0,0,0,1) boxWall_pose:setRotation(rot) self.planningScene:addBox('WallA', 10.1, 0.1, 10.8, boxWall_pose) -- Collision box for wall boxWallB_pose = tf.Transform() boxWallB_pose:setOrigin({-0.8, -0.0, 0.0}) rot = boxWallB_pose:getRotation() rot:setRPY(0,0,-90,1) boxWallB_pose:setRotation(rot) self.planningScene:addBox('WallB', 10.1, 0.1, 10.8, boxWallB_pose) end return o end --- Returns the moveIT move groups which is required for planning -- @return a moveGroup object function RobotControl:GetMoveGroup() return self.rosMoveGroup end --- Returns the planning scene interface -- @return Planning scene interface function RobotControl:GetPlanningSceneInterface() return self.planningScene end --- Creates a pose that can be used to move the robot by providing a position and a rotation -- @param pos torch.Tensor 3x1 position in robot base coordinates -- @param rot torch.Tensor 3x3 rotation matrix function RobotControl:CreatePose(pos, rot) local pose = tf.Transform() pose:setOrigin(pos) pose:setRotation(rot) return pose:toTensor() end --- Move robot to pose "pose", using move group "rosMoveGroup" -- @param pose target robot pose, type torch.Tensor(4,4) -- @treturn bool true if robot has been moved successfully (planning was successfull) function RobotControl:MoveRobotTo(pose) if robotAvailable == false then -- without robot, just ignore the move command print("Robot would move to: ") print(pose) sys.sleep(1.0) return true end if (pose == nil) then print("RobotControl:MoveRobotTo: Target pose is nil!!") return false end self.rosMoveGroup:getCurrentState() self.rosMoveGroup:setStartStateToCurrentState() self.rosMoveGroup:setPoseTarget(pose) print("----- Start Planning ------") local s, p = self.rosMoveGroup:plan() local currentStartPose= self.rosMoveGroup:getCurrentPose() print("----- Planning Finished ------") if s == 0 then return false end print("-------- Moving ... -----------") self.rosMoveGroup:execute(p) print("-------- Move Done ---------") return true end function RobotControl:Normalize(v) -- Private -- Utility function for PointAtPose return v / torch.norm(v) end --- Calculates the TCP pose required to point the TCP z axis to point at with TCP at position eye -- eye becomes origin, 'at' lies on x-axis -- @param eye torch.Tensor(3,1); TCP position in x, y, z -- @param at torch.Tensor(3,1); Point to look at -- @param up torch.Tensor({0, 0, 1}); up direction of the camera -- @return torch.Tensor(4,4), robot pose function RobotControl:PointAtPose(eye, at, up, handEye) local zaxis = self:Normalize(at - eye) local xaxis = self:Normalize(torch.cross(zaxis, up)) local yaxis = torch.cross(zaxis, xaxis) local basis = torch.Tensor(3,3) basis[{{},{1}}] = xaxis basis[{{},{2}}] = yaxis basis[{{},{3}}] = zaxis local t = tf.Transform() t:setBasis(basis) t:setOrigin(eye) local tcpLookat=t:toTensor():clone() if handEye ~= nil then tcpLookat = tcpLookat*torch.inverse(handEye) end return tcpLookat end function RobotControl:RotateGripper(currPose, alpha) local t = tf.Transform() t:fromTensor(currPose) local newRot = t:getRotation() * tf.Quaternion({0,0,1}, alpha) t:setRotation(newRot) return t:toTensor() end --- Calculates the tool center pose for a given camera view -- Calculates the tool center point pose which corresponds to a camera located at distance from target point looking at target point -- with angle polarAngle and azimuthalAngle (in radians) -- @param targetPoint torch.Tensor(3,1); point to look at with the camera -- @param distance distance in meter between targetPoint and camera -- @param polarAngle polar angle in radians -- @param azimuthalAngle azimuthal angle in radians -- @param handEye torch.Tensor(4,4); hand-eye transformation matrix between TCP and camera -- @param upInverse -- @return torch.Tensor(4,4); robot pose function RobotControl:WebCamLookAt(targetPoint, distance, polarAngle, azimuthalAngle, handEye, upInverse) local r=distance local theta=azimuthalAngle local phi=polarAngle local upInverse=upInverse or false local upVector if upInverse then upVector = torch.DoubleTensor({0,0,-1}) else upVector = torch.DoubleTensor({0,0,1}) end local offset = torch.DoubleTensor({math.sin(phi)*(r*math.sin(theta)), math.cos(phi)*(r*(-1)*math.sin(theta)), r*math.cos(theta)}) local eyePoint = targetPoint + offset local eyePose = self:PointAtPose(eyePoint, targetPoint, upVector) local poseForTCP = eyePose*torch.inverse(handEye) return poseForTCP end --- -- function RobotControl:LookDown(targetPoint, rotZangle, handEye) local eyePose = CreatePose(targetPoint, tf.Quaternion({0,0,1}, rotZangle)) local poseTCP = eyePose * torch.inverse(handEye) return poseTCP end --- Reads the current pose of the robot usung the associated move group. -- The function returns a table containing the pose in different formats: -- pose.full: 4x4 torch.Tensor pose of the TCP -- pose.x, pose.y pose.z position of the TCP in robot base coordinates -- pose.roll pose.pitch pose.yaw orientation of the TCP as Roll, Pitch, Yaw -- @param printData prints the data on the command line -- @return table with fields full, x, y, z, roll, pitch, yaw function RobotControl:ReadRobotPose(printData) if robotAvailable == false then -- without robot, return an empty position table return {} end printData = printData or false local pose = self.rosMoveGroup:getCurrentPose_StampedTransform() local origin = pose:getOrigin() local rpy = pose:getRotation():getRPY() local readBackPose = {} readBackPose["full"]=pose:toTensor() readBackPose["x"]=origin[1] readBackPose["y"]=origin[2] readBackPose["z"]=origin[3] readBackPose["roll"]=rpy[1] readBackPose["pitch"]=rpy[2] readBackPose["yaw"]=rpy[3] if printData then print(string.format('robot position: x=%.4f, y=%.4f, z=%.4f; roll=%.4f, pitch=%.4f, yaw=%.4f', readBackPose["x"], readBackPose["y"], readBackPose["z"], readBackPose["roll"], readBackPose["pitch"], readBackPose["yaw"])) end return readBackPose end --- -- Returns the robots pose (TCP) as 4x4 torch.Tensor -- @return torch.Tensor pose of the TCP function RobotControl:GetPose() if robotAvailable == false then return torch.DoubleTensor(4,4):zero() else return self.rosMoveGroup:getCurrentPose_StampedTransform():toTensor() end end -- Direct read of the robot pose via socket connection -- *** START *** function RobotControl:interpret_as_double(x) local u64_buf = ffi.typeof('uint64_t[1]')() local double_ptr_ctype = ffi.typeof('double*') u64_buf[0] = x return ffi.cast(double_ptr_ctype, u64_buf)[0] end function RobotControl:unpackVector(r, D) local v = torch.DoubleTensor(D) for i = 1,D do v[i] = self:interpret_as_double(bit.bswap(r:readUInt64())) end return v end function RobotControl:decode(block) local s = torch.ByteStorage():string(block) local r = ros.StorageReader(s) local len = bit.bswap(r:readInt32()) if len == #block then return { time = bit.bswap(r:readInt64()), q_target = self:unpackVector(r, 6), -- Target joint positions qd_target = self:unpackVector(r, 6), -- Target joint velocities qdd_target = self:unpackVector(r, 6), -- Target joint accelerations i_target = self:unpackVector(r, 6), -- Target joint currents m_target = self:unpackVector(r, 6), -- Target joint moments (torques) q_actual = self:unpackVector(r, 6), -- Actual joint positions qd_actual = self:unpackVector(r, 6), -- Actual joint velocities i_actual = self:unpackVector(r, 6), -- Actual joint currents i_contro_ = self:unpackVector(r, 6), -- Joint control currents tool_vector_actual = self:unpackVector(r, 6), -- Actual Cartesian coordinates of the tool: (x,y,z,rx,ry,rz), where rx, ry and rz is a rotation vector representation of the tool orientation tcp_speed_actual = self:unpackVector(r, 6), -- Actual speed of the tool given in Cartesian coordinates tcp_force = self:unpackVector(r, 6), -- Generalised forces in the TCP tool_vector_target = self:unpackVector(r, 6), -- Target Cartesian coordinates of the tool: (x,y,z,rx,ry,rz), where rx, ry and rz is a rotation vector representation of the tool orientation tcp_speed_target = self:unpackVector(r, 6), -- Target speed of the tool given in Cartesian coordinates digital_input_bits = bit.bswap(r:readInt64()), -- Current state of the digital inputs. NOTE: these are bits encoded as int64_t, e.g. a value of 5 corresponds to bit 0 and bit 2 set high motor_temp = self:unpackVector(r, 6), -- Temperature of each joint in degrees celsius controller_time = bit.bswap(r:readInt64()) -- Controller realtime thread execution time } end end --- Reads the internal state of the robot ny calling the UR5 interface directly (no MoveIT). -- @return table of all readable internal parameters of the UR5 function RobotControl:ReadUR5data() if robotAvailable == false then return end local client = socket.tcp() client:connect('ur5', 30003) client:settimeout(0.01, 'b') for i=1,1000 do local r, e, p = client:receive(2048) if e == 'timeout' then r = p end if not r then error(e) end if #r > 0 then local y = self:decode(r) if y then client:close() return y end end end client:close() error('no valid data block received') end --- Extracts the joint coordinates from the UR5 data -- @param data the raw data read by ReadUR5data -- @param printData a bool value that indicates if the data should be printed on the screen -- @return ??? function RobotControl:DecodeUR5actualJointState(data, printData) local printData = printData or false local jointPos = data.q_actual local jointVel = data.qd_actual local jointCurrent = data.i_actual if printData then local names = self:GetUR5JointNames() for i=1, 6 do print(names[i].." = "..math.deg(jointPos[i])) end end return jointPos, jointVel, jointCurrent end --- Function to create for each joint a human readable name -- @return table with joint names [1] = "Base"... [6] = "Wrist3" function RobotControl:GetUR5JointNames() local names = {} names[1]="Base" names[2]="Shoulder" names[3]="Elbow" names[4]="Wrist1" names[5]="Wrist2" names[6]="Wrist3" return names end function RobotControl:rotateRPY(roll, pitch, yaw) -- X, Y', Z'' ; roll-pitch-yaw = roll-nick-gier local psi, theta, phi = yaw, pitch, roll local cos, sin = math.cos, math.sin local R = torch.Tensor({ { cos(theta)*cos(psi), sin(phi)*sin(theta)*cos(psi)-cos(phi)*sin(psi), cos(phi)*sin(theta)*cos(psi)+sin(phi)*sin(psi), 0 }, { cos(theta)*sin(psi), sin(phi)*sin(theta)*sin(psi)+cos(phi)*cos(psi), cos(phi)*sin(theta)*sin(psi)-sin(phi)*cos(psi), 0 }, { -sin(theta), sin(phi)*cos(theta), cos(phi)*cos(theta), 0 }, { 0, 0, 0, 1 }, }) return R end --- Extracts the TCP Pose from the UR5 data without MoveIT. -- The function returns a table containing the pose in different formats: -- pose.full: 4x4 torch.Tensor pose of the TCP -- pose.x, pose.y pose.z position of the TCP in robot base coordinates -- pose.roll pose.pitch pose.yaw orientation of the TCP as Roll, Pitch, Yaw -- @param data the raw data read by ReadUR5data -- @param printData prints the data on the command line function RobotControl:DecodeUR5TcpPose(data, printData) local ur_tcp = data.tool_vector_actual local axis = ur_tcp[{{4,6}}] local phi = torch.norm(ur_tcp[{{4,6}}]) local pose = ros.tf.Transform() pose:setOrigin(ur_tcp[{{1,3}}]) pose:setRotation(ros.tf.Quaternion(axis, phi)) local origin = pose:getOrigin() local rpy = pose:getRotation():getRPY() local readBackPose = {} readBackPose["full"]=pose:toTensor() readBackPose["x"]=origin[1] readBackPose["y"]=origin[2] readBackPose["z"]=origin[3] readBackPose["roll"]=rpy[1] readBackPose["pitch"]=rpy[2] readBackPose["yaw"]=rpy[3] if printData then print(string.format('robot position via UR5: x=%.4f, y=%.4f, z=%.4f; roll=%.4f, pitch=%.4f, yaw=%.4f', readBackPose["x"], readBackPose["y"], readBackPose["z"], readBackPose["roll"], readBackPose["pitch"], readBackPose["yaw"])) end return readBackPose end -- *** END *** direct read of robot pose via socket return RobotControl
bsd-3-clause
harveyhu2012/luci
modules/admin-full/luasrc/model/cbi/admin_network/iface_add.lua
79
3091
--[[ LuCI - Lua Configuration Interface Copyright 2009-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 nw = require "luci.model.network".init() local fw = require "luci.model.firewall".init() local utl = require "luci.util" local uci = require "luci.model.uci".cursor() m = SimpleForm("network", translate("Create Interface")) m.redirect = luci.dispatcher.build_url("admin/network/network") m.reset = false newnet = m:field(Value, "_netname", translate("Name of the new interface"), translate("The allowed characters are: <code>A-Z</code>, <code>a-z</code>, " .. "<code>0-9</code> and <code>_</code>" )) newnet:depends("_attach", "") newnet.default = arg[1] and "net_" .. arg[1]:gsub("[^%w_]+", "_") newnet.datatype = "uciname" newproto = m:field(ListValue, "_netproto", translate("Protocol of the new interface")) netbridge = m:field(Flag, "_bridge", translate("Create a bridge over multiple interfaces")) sifname = m:field(Value, "_ifname", translate("Cover the following interface")) sifname.widget = "radio" sifname.template = "cbi/network_ifacelist" sifname.nobridges = true mifname = m:field(Value, "_ifnames", translate("Cover the following interfaces")) mifname.widget = "checkbox" mifname.template = "cbi/network_ifacelist" mifname.nobridges = true local _, p for _, p in ipairs(nw:get_protocols()) do if p:is_installed() then newproto:value(p:proto(), p:get_i18n()) if not p:is_virtual() then netbridge:depends("_netproto", p:proto()) end if not p:is_floating() then sifname:depends({ _bridge = "", _netproto = p:proto()}) mifname:depends({ _bridge = "1", _netproto = p:proto()}) end end end function newproto.validate(self, value, section) local name = newnet:formvalue(section) if not name or #name == 0 then newnet:add_error(section, translate("No network name specified")) elseif m:get(name) then newnet:add_error(section, translate("The given network name is not unique")) end local proto = nw:get_protocol(value) if proto and not proto:is_floating() then local br = (netbridge:formvalue(section) == "1") local ifn = br and mifname:formvalue(section) or sifname:formvalue(section) for ifn in utl.imatch(ifn) do return value end return nil, translate("The selected protocol needs a device assigned") end return value end function newproto.write(self, section, value) local name = newnet:formvalue(section) if name and #name > 0 then local br = (netbridge:formvalue(section) == "1") and "bridge" or nil local net = nw:add_network(name, { proto = value, type = br }) if net then local ifn for ifn in utl.imatch( br and mifname:formvalue(section) or sifname:formvalue(section) ) do net:add_interface(ifn) end nw:save("network") nw:save("wireless") end luci.http.redirect(luci.dispatcher.build_url("admin/network/network", name)) end end return m
apache-2.0
Kosmos82/kosmosdarkstar
scripts/zones/Windurst_Waters/npcs/Maysoon.lua
25
2162
----------------------------------- -- Area: Windurst Waters -- NPC: Maysoon -- Starts and Finishes Quest: Hoist the Jelly, Roger -- Involved in Quests: Cook's Pride -- @zone 238 -- @pos -105 -2 69 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Windurst_Waters/TextIDs"); require("scripts/globals/settings"); require("scripts/globals/quests"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(WINDURST,HOIST_THE_JELLY_ROGER) == QUEST_ACCEPTED) then if (trade:hasItemQty(4508,1) == true and trade:getGil() == 0 and trade:getItemCount() == 1) then player:startEvent(0x2711); -- Finish quest "Hoist the Jelly, Roger" end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) CooksPride = player:getQuestStatus(JEUNO,COOK_S_PRIDE); HoistTheJelly = player:getQuestStatus(WINDURST,HOIST_THE_JELLY_ROGER); if (CooksPride == QUEST_ACCEPTED and HoistTheJelly == QUEST_AVAILABLE) then player:startEvent(0x2710); -- Start quest "Hoist the Jelly, Roger" else player:startEvent(0x010a); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x2710) then player:addQuest(WINDURST,HOIST_THE_JELLY_ROGER); elseif (csid == 0x2711) then player:completeQuest(WINDURST,HOIST_THE_JELLY_ROGER); player:addKeyItem(SUPER_SOUP_POT); player:messageSpecial(KEYITEM_OBTAINED,SUPER_SOUP_POT); player:addFame(WINDURST,30); player:tradeComplete(); end end;
gpl-3.0
firebaugh/Digitowls
WebotsController/Player.old/World/World.lua
4
6476
module(..., package.seeall); require('PoseFilter'); require('Filter2D'); require('Body'); require('vector'); require('util'); require('vcm'); require('gcm'); require 'mcm' ballFilter = Filter2D.new(); ball = {}; ball.t = 0; --Detection time ball.x = 1.0; ball.y = 0; ball.vx = 0; ball.vy = 0; pose = {}; pose.x = 0; pose.y = 0; pose.a = 0; pose.tGoal = 0; --Goal detection time uOdometry0 = vector.new({0, 0, 0}); count = 0; cResample = Config.world.cResample; playerID = Config.game.playerID; odomScale = Config.world.odomScale; enableVelocity = Config.vision.enable_velocity_detection; if( enableVelocity == 1 ) then require('Velocity'); -- Add Velocity for Ball end function entry() count = 0; if( enableVelocity == 1 ) then Velocity.entry(); end end function update_odometry() count = count + 1; uOdometry, uOdometry0 = mcm.get_odometry(uOdometry0); uOdometry[1] = odomScale[1]*uOdometry[1]; uOdometry[2] = odomScale[2]*uOdometry[2]; uOdometry[3] = odomScale[3]*uOdometry[3]; ballFilter:odometry(uOdometry[1], uOdometry[2], uOdometry[3]); PoseFilter.odometry(uOdometry[1], uOdometry[2], uOdometry[3]); end function update_vision() -- resample? if count % cResample == 0 then PoseFilter.resample(); PoseFilter.add_noise(); end -- ball if (vcm.get_ball_detect() == 1) then ball.t = Body.get_time(); local v = vcm.get_ball_v(); local dr = vcm.get_ball_dr(); local da = vcm.get_ball_da(); ballFilter:observation_xy(v[1], v[2], dr, da); Body.set_indicator_ball({1,0,0}); -- Update the velocity if( enableVelocity==1 ) then Velocity.update(); ball.vx, ball.vy, dodge = Velocity.getVelocity(); local speed = math.sqrt(ball.vx^2 + ball.vy^2); local stillTime = mcm.get_walk_stillTime(); if( stillTime > 1.5 ) then print('Speed: '..speed..', Vel: ('..ball.vx..', '..ball.vy..') Still Time: '..stillTime); end end else Body.set_indicator_ball({0,0,0}); end -- TODO: handle goal detections more generically if vcm.get_goal_detect() == 1 then pose.tGoal = Body.get_time(); local color = vcm.get_goal_color(); local goalType = vcm.get_goal_type(); local v1 = vcm.get_goal_v1(); local v2 = vcm.get_goal_v2(); local v = {v1, v2}; if color == Config.color.yellow then if (goalType == 0) then PoseFilter.post_yellow_unknown(v); elseif(goalType == 1) then PoseFilter.post_yellow_left(v); elseif(goalType == 2) then PoseFilter.post_yellow_right(v); elseif(goalType == 3) then PoseFilter.goal_yellow(v); end -- indicator Body.set_indicator_goal({1,1,0}); elseif color == Config.color.cyan then if (goalType == 0) then PoseFilter.post_cyan_unknown(v); elseif(goalType == 1) then PoseFilter.post_cyan_left(v); elseif(goalType == 2) then PoseFilter.post_cyan_right(v); elseif(goalType == 3) then PoseFilter.goal_cyan(v); end -- indicator Body.set_indicator_goal({0,0,1}); end else -- indicator Body.set_indicator_goal({0,0,0}); end -- line update if vcm.get_line_detect() == 1 then local v = vcm.get_line_v(); local a = vcm.get_line_angle(); PoseFilter.line(v, a); end ball.x, ball.y = ballFilter:get_xy(); pose.x,pose.y,pose.a = PoseFilter.get_pose(); update_shm(); end function update_shm() -- update shm values wcm.set_robot_pose({pose.x, pose.y, pose.a}); wcm.set_ball_xy({ball.x, ball.y}); wcm.set_ball_t(ball.t); wcm.set_ball_velocity( {ball.vx, ball.vy} ); wcm.set_goal_t(pose.tGoal); wcm.set_goal_attack(get_goal_attack()); wcm.set_goal_defend(get_goal_defend()); wcm.set_goal_attack_bearing(get_attack_bearing()); wcm.set_goal_attack_angle(get_attack_angle()); wcm.set_goal_defend_angle(get_defend_angle()); end function exit() end function get_ball() return ball; end function get_pose() return pose; end function zero_pose() PoseFilter.zero_pose(); end function get_attack_bearing() if gcm.get_team_color() == 1 then -- red attacks cyan goal postAttack = PoseFilter.postCyan; else -- blue attack yellow goal postAttack = PoseFilter.postYellow; end -- make sure not to shoot back towards defensive goal: local xPose = math.min(math.max(pose.x, -0.99*PoseFilter.xLineBoundary), 0.99*PoseFilter.xLineBoundary); local yPose = pose.y; local aPost = {} aPost[1] = math.atan2(postAttack[1][2]-yPose, postAttack[1][1]-xPose); aPost[2] = math.atan2(postAttack[2][2]-yPose, postAttack[2][1]-xPose); local daPost = math.abs(PoseFilter.mod_angle(aPost[1]-aPost[2])); attackHeading = aPost[2] + .5*daPost; attackBearing = PoseFilter.mod_angle(attackHeading - pose.a); return attackBearing, daPost; end function get_goal_attack() if gcm.get_team_color() == 1 then -- red attacks cyan goal return {PoseFilter.postCyan[1][1], 0, 0}; else -- blue attack yellow goal return {PoseFilter.postYellow[1][1], 0, 0}; end end function get_goal_defend() if gcm.get_team_color() == 1 then -- red defends yellow goal return {PoseFilter.postYellow[1][1], 0, 0}; else -- blue defends cyan goal return {PoseFilter.postCyan[1][1], 0, 0}; end end function get_attack_angle() goalAttack = get_goal_attack(); dx = goalAttack[1] - pose.x; dy = goalAttack[2] - pose.y; return mod_angle(math.atan2(dy, dx) - pose.a); end function get_defend_angle() goalDefend = get_goal_defend(); dx = goalDefend[1] - pose.x; dy = goalDefend[2] - pose.y; return mod_angle(math.atan2(dy, dx) - pose.a); end function get_team_color() return gcm.get_team_color(); end function pose_global(pRelative, pose) local ca = math.cos(pose[3]); local sa = math.sin(pose[3]); return vector.new{pose[1] + ca*pRelative[1] - sa*pRelative[2], pose[2] + sa*pRelative[1] + ca*pRelative[2], pose[3] + pRelative[3]}; end function pose_relative(pGlobal, pose) local ca = math.cos(pose[3]); local sa = math.sin(pose[3]); local px = pGlobal[1]-pose[1]; local py = pGlobal[2]-pose[2]; local pa = pGlobal[3]-pose[3]; return vector.new{ca*px + sa*py, -sa*px + ca*py, mod_angle(pa)}; end function mod_angle(a) -- Reduce angle to [-pi, pi) a = a % (2*math.pi); if (a >= math.pi) then a = a - 2*math.pi; end return a; end
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Temenos/npcs/Armoury_Crate.lua
14
8397
----------------------------------- -- Area: Temenos -- NPC: Armoury Crate ----------------------------------- package.loaded["scripts/zones/Temenos/TextIDs"] = nil; ------------------------------------- require("scripts/globals/titles"); require("scripts/globals/quests"); require("scripts/zones/Temenos/TextIDs"); require("scripts/globals/limbus"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local CofferID = npc:getID(); local CofferType=0; local lootID=0; local InstanceRegion=0; local addtime=0; local DespawnOtherCoffer=false; local MimicID=0; local X = npc:getXPos(); local Y = npc:getYPos(); local Z = npc:getZPos(); for coffer = 1,table.getn (ARMOURY_CRATES_LIST_TEMENOS),2 do if (ARMOURY_CRATES_LIST_TEMENOS[coffer] == CofferID-16928768) then CofferType=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][1]; InstanceRegion=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][2]; addtime=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][3]; DespawnOtherCoffer=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][4]; MimicID=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][5]; lootID=ARMOURY_CRATES_LIST_TEMENOS[coffer+1][6]; end end printf("CofferID : %u",CofferID-16928768); printf("Coffertype %u",CofferType); printf("InstanceRegion: %u",InstanceRegion); printf("addtime: %u",addtime); printf("MimicID: %u",MimicID); printf("lootID: %u",lootID); local coffer = CofferID-16928768; if (CofferType == cTIME) then player:addTimeToSpecialBattlefield(InstanceRegion,addtime); elseif (CofferType == cITEM) then if (InstanceRegion == Central_Temenos_4th_Floor and coffer~=79) then local randmimic = math.random(1,24) print("randmimic" ..randmimic); if ( randmimic < 19) then local MimicList={16928986,16928987,16928988,16928989,16928990,16928991,16928992,16928993,16928994,16928995,16928996,16928997,16928998,16928999,16929000,16929001,16929002,16929003}; GetMobByID(MimicList[randmimic]):setSpawn(X,Y,Z); SpawnMob(MimicList[randmimic]):setPos(X,Y,Z); GetMobByID(MimicList[randmimic]):updateClaim(player); else player:BCNMSetLoot(lootID,InstanceRegion,CofferID); player:getBCNMloot(); end -- despawn les coffer du meme groupe for coffer = 1, table.getn (ARMOURY_CRATES_LIST_TEMENOS), 2 do if (ARMOURY_CRATES_LIST_TEMENOS[coffer+1][5] == MimicID) then GetNPCByID(16928768+ARMOURY_CRATES_LIST_TEMENOS[coffer]):setStatus(STATUS_DISAPPEAR); end end else player:BCNMSetLoot(lootID, InstanceRegion, CofferID); player:getBCNMloot(); end elseif (CofferType == cRESTORE) then player:RestoreAndHealOnBattlefield(InstanceRegion); elseif (CofferType == cMIMIC) then if (coffer == 284) then GetMobByID(16928844):setSpawn(X,Y,Z); SpawnMob(16928844):setPos(X,Y,Z) GetMobByID(16928844):updateClaim(player); elseif (coffer == 321) then GetMobByID(16928853):setSpawn(X,Y,Z); SpawnMob(16928853):setPos(X,Y,Z); GetMobByID(16928853):updateClaim(player); elseif (coffer == 348) then GetMobByID(16928862):setSpawn(X,Y,Z); SpawnMob(16928862):setPos(X,Y,Z); GetMobByID(16928862):updateClaim(player); elseif (coffer == 360) then GetMobByID(16928871):setSpawn(X,Y,Z); SpawnMob(16928871):setPos(X,Y,Z); GetMobByID(16928871):updateClaim(player); elseif (coffer == 393) then GetMobByID(16928880):setSpawn(X,Y,Z); SpawnMob(16928880):setPos(X,Y,Z); GetMobByID(16928880):updateClaim(player); elseif (coffer == 127) then GetMobByID(16928889):setSpawn(X,Y,Z); SpawnMob(16928889):setPos(X,Y,Z); GetMobByID(16928889):updateClaim(player); elseif (coffer == 123) then GetMobByID(16928894):setSpawn(X,Y,Z); SpawnMob(16928894):setPos(X,Y,Z); GetMobByID(16928894):updateClaim(player); end end if (DespawnOtherCoffer == true) then HideArmouryCrates(InstanceRegion,TEMENOS); if (InstanceRegion==Temenos_Eastern_Tower) then --despawn mob of the current floor if (coffer == 173 or coffer == 215 or coffer == 284 or coffer == 40) then --floor 1 if (GetMobAction(16928840) > 0) then DespawnMob(16928840); end if (GetMobAction(16928841) > 0) then DespawnMob(16928841); end if (GetMobAction(16928842) > 0) then DespawnMob(16928842); end if (GetMobAction(16928843) > 0) then DespawnMob(16928843); end GetNPCByID(16929228):setStatus(STATUS_NORMAL); elseif (coffer == 174 or coffer == 216 or coffer == 321 or coffer == 45) then --floor 2 if (GetMobAction(16928849) > 0) then DespawnMob(16928849); end if (GetMobAction(16928850) > 0) then DespawnMob(16928850); end if (GetMobAction(16928851) > 0) then DespawnMob(16928851); end if (GetMobAction(16928852) > 0) then DespawnMob(16928852); end GetNPCByID(16929229):setStatus(STATUS_NORMAL); elseif (coffer == 181 or coffer == 217 or coffer == 348 or coffer == 46) then --floor 3 if (GetMobAction(16928858) > 0) then DespawnMob(16928858); end if (GetMobAction(16928859) > 0) then DespawnMob(16928859); end if (GetMobAction(16928860) > 0) then DespawnMob(16928860); end if (GetMobAction(16928861) > 0) then DespawnMob(16928861); end GetNPCByID(16929230):setStatus(STATUS_NORMAL); elseif (coffer == 182 or coffer == 236 or coffer == 360 or coffer == 47) then --floor 4 if (GetMobAction(16928867) > 0) then DespawnMob(16928867); end if (GetMobAction(16928868) > 0) then DespawnMob(16928868); end if (GetMobAction(16928869) > 0) then DespawnMob(16928869); end if (GetMobAction(16928870) > 0) then DespawnMob(16928870); end GetNPCByID(16929231):setStatus(STATUS_NORMAL); elseif (coffer == 183 or coffer == 261 or coffer == 393 or coffer == 68) then --floor 5 if (GetMobAction(16928876) > 0) then DespawnMob(16928876); end if (GetMobAction(16928877) > 0) then DespawnMob(16928877); end if (GetMobAction(16928878) > 0) then DespawnMob(16928878); end if (GetMobAction(16928879) > 0) then DespawnMob(16928879); end GetNPCByID(16929232):setStatus(STATUS_NORMAL); elseif (coffer == 277 or coffer == 190 or coffer == 127 or coffer == 69) then --floor 6 if (GetMobAction(16928885) > 0) then DespawnMob(16928885); end if (GetMobAction(16928886) > 0) then DespawnMob(16928886); end if (GetMobAction(16928887) > 0) then DespawnMob(16928887); end if (GetMobAction(16928888) > 0) then DespawnMob(16928888); end GetNPCByID(16929233):setStatus(STATUS_NORMAL); elseif (coffer == 70 or coffer == 123) then --floor 7 if (GetMobAction(16928892) > 0) then DespawnMob(16928892); end if (GetMobAction(16928893) > 0) then DespawnMob(16928893); end GetNPCByID(16929234):setStatus(STATUS_NORMAL); end end end npc:setStatus(STATUS_DISAPPEAR); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) end;
gpl-3.0
april-org/april-ann
packages/bayesian/lua_src/priors.lua
3
4276
get_table_from_dotted_string("bayesian", true) ------------------------------------------------------------------------------ local make_value = function(value) return { t="value", value=value } end local make_dist = function(dist, arg) return { t="dist", dist=dist, arg=arg } end local make_transform = function(func, arg) return { t="transform", func=func, arg=arg } end local normalize_shape = function(d, w) if w then if d:size() == 1 and w:dim(2) ~= 1 then return w:rewrap(w:size(),1) else april_assert(d:size() == w:dim(2), "Incompatible matrix size, found %dx%d, expected %dx%d", w:dim(1), w:dim(2), w:dim(1), d:size()) end end return w end local sampling_funcs = { value = function(v) return function() return v.value end end, dist = function(v, outcomes) local arg = {} for i=1,#v.arg do arg[i] = april_assert(outcomes[v.arg[i]], "Undefined value of '%s'", v.arg[i]) end local d = stats.dist[v.dist](table.unpack(arg)) v.obj = d return function(rng, w) local w = normalize_shape(d, w) return d:sample(rng, w) end end, transform = function(v, outcomes) local arg = {} for i=1,#v.arg do arg[i] = april_assert(outcomes[v.arg[i]], "Undefined value of '%s'", v.arg[i]) if isa(arg[i], matrix) then arg[i] = arg[i]:clone() end end local r = v.func(table.unpack(arg)) return function() return r end end, } ----------------------------------------------------------------------------- local priors_class,priors_methods = class("bayesian.priors") bayesian.priors = priors_class -- global environment function priors_class:constructor(tree,order,outcomes) self.tree = tree or {} self.order = order or {} self.outcomes = outcomes or {} end function priors_methods:compute_neg_log_prior(weights) error("NOT IMPLEMENTED") local logprob = 0.0 for name,m in pairs(self.outcomes) do local d = self.tree[name].obj if d then local out = d:logpdf(m) logprob = logprob + out:sum() end end for name,w in pairs(weights) do local v = self.tree[name] if v and v.obj then local d = v.obj local w = normalize_shape(d, w) local out = d:logpdf(w) logprob = logprob + out:sum() end end return -logprob end function priors_methods:ctor_name() return "bayesian.priors" end function priors_methods:ctor_params() return self.tree,self.order,self.outcomes end function priors_methods:value(name, value) april_assert(not self.tree[name], "Redifition of value '%s'", target) table.insert(self.order, name) self.tree[name] = make_value(value) return name end function priors_methods:follows(target, dist, ...) assert(type(dist) == "string", "Expected a string with the distribution name") april_assert(stats.dist[dist], "Unknown distribution %s\n", dist) april_assert(not self.tree[target], "Redifition of target '%s' dist", target) table.insert(self.order, target) self.tree[target] = make_dist(dist, { ... }) return target end function priors_methods:transform(target, func, ...) april_assert(not self.tree[target], "Redifition of trans. '%s'", target) table.insert(self.order, target) self.tree[target] = make_transform(func, { ... }) return target end function priors_methods:sample(rng, weights) local outcomes = {} for _,name in ipairs(self.order) do local v = assert( self.tree[name] ) local s = sampling_funcs[v.t](v, outcomes) local w = weights(name) if not w then outcomes[name] = s(rng, w) end -- if w then w:copy(outcomes[name]) end end self.outcomes = outcomes return outcomes end function priors_methods:update_gradients_with_priors(weights, grads) for name,w in pairs(weights) do local wgrads = assert( grads(name) ) local v = self.tree[name] if v then assert(v.t == "dist", "Expected a distribution") local d = assert(v.obj, "Needs to call sample before") local w = normalize_shape(d, w) local wgrads = normalize_shape(d, wgrads) d:logpdf_derivative(w, wgrads) end end end ------------------------------------------------------------------------------
gpl-3.0
beforan/r-dailyprogrammer
2014-12-31/Game.lua
1
1987
local Game = function () local game = {} local targetDie, scoringDice, score, initd local init = function () --first time initialisation --define new functions to be exposed now that it's safe local roll = function () targetDie:roll() for _, d in ipairs(scoringDice) do d:roll() end end local solve = function () local n = #scoringDice for combo = 0, 2^n local dice = {} local combobits = bitset(combo, n) end end local bitset = function(val, nBits) --[[ returns a binary representation of val as a table of bits (0/1), zero-padded to nBits ]] local mod, t = 0, {} while val > 0 do val, mod = math.floor(val/2), math.mod(val, 2) table.insert(t, mod) end while #t < nBits do table.insert(t, 0) end return t end local getTarget = function () return targetDie:getLastRoll() end local getScoringRolls = function () local rolls, str = {}, "" for _, d in ipairs(scoringDice) do table.insert(rolls, d:getLastRoll()) if str ~= "" then str = str .. " " end str = str .. d:getLastRoll() end --overload tostring(), to save a separate public method :) setmetatable(rolls, { __tostring = function () return str end }) return rolls end end local setup = function (targetSides, diceSides, nDice) --(re) initialise properties targetDie = Die(targetSides) scoringDice = {} for i = 1, nDice do table.insert(scoringDice, Die(diceSides)) end score = 0 if not initd then init() end end local notImplemented = function () error("Game not initialised. Have you run setup()?") end --expose public interface game.setup = setup return game end return Game()
mit
Kosmos82/kosmosdarkstar
scripts/globals/mobskills/Tebbad_Wing.lua
33
1231
--------------------------------------------- -- Tebbad Wing -- -- Description: A hot wind deals Fire damage to enemies within a very wide area of effect. Additional effect: Plague -- Type: Magical -- Utsusemi/Blink absorb: Wipes shadows -- Range: 30' radial. -- Notes: Used only by Tiamat, Smok and Ildebrann --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:hasStatusEffect(EFFECT_MIGHTY_STRIKES)) then return 1; elseif (mob:AnimationSub() == 1) then return 1; elseif (target:isBehind(mob, 48) == true) then return 1; end return 0; end; function onMobWeaponSkill(target, mob, skill) local typeEffect = EFFECT_PLAGUE; MobStatusEffectMove(mob, target, typeEffect, 10, 0, 120); local dmgmod = 1; local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*5,ELE_FIRE,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_FIRE,MOBPARAM_WIPE_SHADOWS); target:delHP(dmg); return dmg; end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/globals/spells/battlefield_elegy.lua
3
1706
----------------------------------------- -- Spell: Battlefield Elegy ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local duration = 120; local power = 256; local pCHR = caster:getStat(MOD_CHR); local mCHR = target:getStat(MOD_CHR); local dCHR = (pCHR - mCHR); local resm = applyResistance(caster,spell,target,dCHR,SINGING_SKILL,0); if (resm < 0.5) then spell:setMsg(85);--resist message return 1; end if (100 * math.random() < target:getMod(MOD_SLOWRES)) then spell:setMsg(85); -- resisted spell else local iBoost = caster:getMod(MOD_ELEGY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); power = power + iBoost*10; if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then power = power * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then power = power * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end -- Try to overwrite weaker elegy if (target:addStatusEffect(EFFECT_ELEGY,power,0,duration)) then spell:setMsg(237); else spell:setMsg(75); -- no effect end end return EFFECT_ELEGY; end;
gpl-3.0
martin-traverse/premake-core
tests/api/test_register.lua
7
1704
-- -- tests/api/test_register.lua -- Tests the new API registration function. -- Copyright (c) 2012 Jason Perkins and the Premake project -- local suite = test.declare("api_register") local api = premake.api -- -- Setup and teardown -- function suite.teardown() testapi = nil end -- -- Verify that the function exists. -- function suite.registerFunctionExists() test.isequal("function", type(premake.api.register)) end -- -- When called, a new function with with provided name should -- added to the global namespace. -- function suite.createsNewGlobalFunction() api.register { name = "testapi", kind = "string", scope = "project" } test.isequal("function", type(testapi)); end -- -- Verify that an error is raised if no name is provided. -- function suite.raisesError_onMissingName() ok, err = pcall(function () api.register { kind = "string", scope = "project" } end) test.isfalse(ok) end -- -- Verify that an error is raised if the name is already in use. -- function suite.raisesError_onExistingGlobalName() testapi = "testapi" ok, err = pcall(function () api.register { name = "testapi", kind = "string", scope = "project" } end) test.isfalse(ok) end -- -- Verify that an error is raised if an invalid kind is used. -- function suite.raisesError_onInvalidKind() ok, err = pcall(function () api.register { name = "testapi", kind = "bogus", scope = "project" } end) test.isfalse(ok) end -- -- Verify that key-value forms are accepted. -- function suite.succeeds_onKeyValueForm() ok, err = pcall(function () api.register { name = "testapi", kind = "string", keyed = true, scope = "project" } end) test.istrue(ok) end
bsd-3-clause
Kosmos82/kosmosdarkstar
scripts/zones/Beaucedine_Glacier_[S]/npcs/Moana_CA.lua
13
1079
----------------------------------- -- Area: Beaucedine Glacier (S) -- NPC: Moana, C.A. -- Type: Campaign Arbiter -- @zone: 136 -- @pos -27.237 -60.888 -48.111 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Beaucedine_Glacier_[S]/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x01c5); 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
harveyhu2012/luci
applications/luci-splash/luasrc/model/cbi/splash/splash.lua
52
3212
--[[ LuCI - Lua Configuration Interface 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 ]]-- require("luci.model.uci") m = Map("luci_splash", translate("Client-Splash"), translate("Client-Splash is a hotspot authentification system for wireless mesh networks.")) s = m:section(NamedSection, "general", "core", translate("General")) s.addremove = false s:option(Value, "leasetime", translate("Clearance time"), translate("Clients that have accepted the splash are allowed to use the network for that many hours.")) local redir = s:option(Value, "redirect_url", translate("Redirect target"), translate("Clients are redirected to this page after they have accepted the splash. If this is left empty they are redirected to the page they had requested.")) redir.rmempty = true s:option(Value, "limit_up", translate("Upload limit"), translate("Clients upload speed is limited to this value (kbyte/s)")) s:option(Value, "limit_down", translate("Download limit"), translate("Clients download speed is limited to this value (kbyte/s)")) s:option(DummyValue, "_tmp", "", translate("Bandwidth limit for clients is only activated when both up- and download limit are set. " .. "Use a value of 0 here to completely disable this limitation. Whitelisted clients are not limited.")) s = m:section(TypedSection, "iface", translate("Interfaces"), translate("Interfaces that are used for Splash.")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true local uci = luci.model.uci.cursor() zone = s:option(ListValue, "zone", translate("Firewall zone"), translate("Splash rules are integrated in this firewall zone")) uci:foreach("firewall", "zone", function (section) zone:value(section.name) end) iface = s:option(ListValue, "network", translate("Network"), translate("Intercept client traffic on this Interface")) uci:foreach("network", "interface", function (section) if section[".name"] ~= "loopback" then iface:value(section[".name"]) end end) uci:foreach("network", "alias", function (section) iface:value(section[".name"]) end) s = m:section(TypedSection, "whitelist", translate("Whitelist"), translate("MAC addresses of whitelisted clients. These do not need to accept the splash and are not bandwidth limited.")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true s:option(Value, "mac", translate ("MAC Address")) s = m:section(TypedSection, "blacklist", translate("Blacklist"), translate("MAC addresses in this list are blocked.")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true s:option(Value, "mac", translate ("MAC Address")) s = m:section(TypedSection, "subnet", translate("Allowed hosts/subnets"), translate("Destination hosts and networks that are excluded from splashing, i.e. they are always allowed.")) s.template = "cbi/tblsection" s.addremove = true s.anonymous = true s:option(Value, "ipaddr", translate("IP Address")) s:option(Value, "netmask", translate("Netmask"), translate("optional when using host addresses")).rmempty = true return m
apache-2.0
martin-traverse/premake-core
src/actions/vstudio/vs2010_vcxproj_user.lua
17
3269
-- -- vs2010_vcxproj_user.lua -- Generate a Visual Studio 201x C/C++ project .user file -- Copyright (c) 2011-2015 Jason Perkins and the Premake project -- local p = premake local m = p.vstudio.vc2010 -- -- Generate a Visual Studio 201x C++ user file. -- m.elements.user = function(cfg) return { m.debugSettings, } end function m.generateUser(prj) -- Only want output if there is something to configure local contents = {} local size = 0 for cfg in p.project.eachconfig(prj) do contents[cfg] = p.capture(function() p.push(2) p.callArray(m.elements.user, cfg) p.pop(2) end) size = size + #contents[cfg] end if size > 0 then m.xmlDeclaration() m.userProject() for cfg in p.project.eachconfig(prj) do p.push('<PropertyGroup %s>', m.condition(cfg)) if #contents[cfg] > 0 then p.outln(contents[cfg]) end p.pop('</PropertyGroup>') end p.pop('</Project>') end end -- -- Output the opening <Project> tag. -- function m.userProject() local action = premake.action.current() p.push('<Project ToolsVersion="%s" xmlns="http://schemas.microsoft.com/developer/msbuild/2003">', action.vstudio.toolsVersion) end m.elements.debugSettings = function(cfg) return { m.localDebuggerCommand, m.localDebuggerWorkingDirectory, m.debuggerFlavor, m.localDebuggerCommandArguments, m.localDebuggerDebuggerType, m.localDebuggerEnvironment, m.localDebuggerMergeEnvironment, } end function m.debugSettings(cfg) p.callArray(m.elements.debugSettings, cfg) end function m.debuggerFlavor(cfg) if cfg.debugdir or cfg.debugcommand then p.w('<DebuggerFlavor>WindowsLocalDebugger</DebuggerFlavor>') end end function m.localDebuggerCommand(cfg) if cfg.debugcommand then local dir = path.translate(cfg.debugcommand) p.w('<LocalDebuggerCommand>%s</LocalDebuggerCommand>', dir) end end function m.localDebuggerDebuggerType(cfg) if cfg.debuggertype then p.w('<LocalDebuggerDebuggerType>%s</LocalDebuggerDebuggerType>', cfg.debuggertype) end end function m.localDebuggerCommandArguments(cfg) if #cfg.debugargs > 0 then p.x('<LocalDebuggerCommandArguments>%s</LocalDebuggerCommandArguments>', table.concat(cfg.debugargs, " ")) end end function m.localDebuggerWorkingDirectory(cfg) if cfg.debugdir then local dir = p.vstudio.path(cfg, cfg.debugdir) p.x('<LocalDebuggerWorkingDirectory>%s</LocalDebuggerWorkingDirectory>', dir) end end function m.localDebuggerEnvironment(cfg) if #cfg.debugenvs > 0 then local envs = table.concat(cfg.debugenvs, "\n") if cfg.flags.DebugEnvsInherit then envs = envs .. "\n$(LocalDebuggerEnvironment)" end p.w('<LocalDebuggerEnvironment>%s</LocalDebuggerEnvironment>', envs) if cfg.flags.DebugEnvsDontMerge then p.w(2,'<LocalDebuggerMergeEnvironment>false</LocalDebuggerMergeEnvironment>') end end end function m.localDebuggerMergeEnvironment(cfg) if #cfg.debugenvs > 0 and cfg.flags.DebugEnvsDontMerge then p.w(2,'<LocalDebuggerMergeEnvironment>false</LocalDebuggerMergeEnvironment>') end end
bsd-3-clause
justincormack/snabbswitch
src/lib/protocol/tcp.lua
7
5100
module(..., package.seeall) local ffi = require("ffi") local C = ffi.C local lib = require("core.lib") local header = require("lib.protocol.header") local ipsum = require("lib.checksum").ipsum local ntohs, htons, ntohl, htonl = lib.ntohs, lib.htons, lib.ntohl, lib.htonl local tcp = subClass(header) -- Class variables tcp._name = "tcp" tcp._ulp = { method = nil } tcp:init( { [1] = ffi.typeof[[ struct { uint16_t src_port; uint16_t dst_port; uint32_t seq; uint32_t ack; uint16_t off_flags; //data offset:4 reserved:3 NS:1 CWR:1 ECE:1 URG:1 ACK:1 PSH:1 RST:1 SYN:1 FIN:1 uint16_t window_size; uint16_t checksum; uint16_t pad; } __attribute__((packed)) ]], }) -- Class methods function tcp:new (config) local o tcp:superClass().new(self) o:src_port(config.src_port) o:dst_port(config.dst_port) o:seq_num(config.seq) o:ack_num(config.ack) o:window_size(config.window_size) o:header().pad = 0 o:offset(config.offset or 0) o:ns(config.ns or 0) o:cwr(config.cwr or 0) o:ece(config.ece or 0) o:urg(config.urg or 0) o:ack(config.ack or 0) o:psh(config.psh or 0) o:rst(config.rst or 0) o:syn(config.syn or 0) o:fin(config.fin or 0) o:checksum() return o end -- Instance methods function tcp:src_port (port) local h = self:header() if port ~= nil then h.src_port = htons(port) end return ntohs(h.src_port) end function tcp:dst_port (port) local h = self:header() if port ~= nil then h.dst_port = htons(port) end return ntohs(h.dst_port) end function tcp:seq_num (seq) local h = self:header() if seq ~= nil then h.seq = htonl(seq) end return ntohl(h.seq) end function tcp:ack_num (ack) local h = self:header() if ack ~= nil then h.ack = htonl(ack) end return ntohl(h.ack) end function tcp:offset (offset) -- ensure reserved bits are 0 lib.bitfield(16, self:header(), 'off_flags', 4, 3, 0) return lib.bitfield(16, self:header(), 'off_flags', 0, 4, offset) end -- set all flags at once function tcp:flags (flags) return lib.bitfield(16, self:header(), 'off_flags', 7, 9, flags) end function tcp:ns (ns) return lib.bitfield(16, self:header(), 'off_flags', 7, 1, ns) end function tcp:cwr (cwr) return lib.bitfield(16, self:header(), 'off_flags', 8, 1, cwr) end function tcp:ece (ece) return lib.bitfield(16, self:header(), 'off_flags', 9, 1, ece) end function tcp:urg (urg) return lib.bitfield(16, self:header(), 'off_flags', 10, 1, urg) end function tcp:ack (ack) return lib.bitfield(16, self:header(), 'off_flags', 11, 1, ack) end function tcp:psh (psh) return lib.bitfield(16, self:header(), 'off_flags', 12, 1, psh) end function tcp:rst (rst) return lib.bitfield(16, self:header(), 'off_flags', 13, 1, rst) end function tcp:syn (syn) return lib.bitfield(16, self:header(), 'off_flags', 14, 1, syn) end function tcp:fin (fin) return lib.bitfield(16, self:header(), 'off_flags', 15, 1, fin) end function tcp:window_size (window_size) local h = self:header() if window_size ~= nil then h.window_size = htons(window_size) end return ntohs(h.window_size) end function tcp:checksum (payload, length, ip) local h = self:header() if payload then local csum = 0 if ip then -- Checksum IP pseudo-header local ph = ip:pseudo_header(length + self:sizeof(), 6) csum = ipsum(ffi.cast("uint8_t *", ph), ffi.sizeof(ph), 0) end -- Add TCP header h.checksum = 0 csum = ipsum(ffi.cast("uint8_t *", h), self:sizeof(), bit.bnot(csum)) -- Add TCP payload h.checksum = htons(ipsum(payload, length, bit.bnot(csum))) end return ntohs(h.checksum) end -- override the default equality method function tcp:eq (other) --compare significant fields return (self:src_port() == other:src_port()) and (self:dst_port() == other:dst_port()) and (self:seq_num() == other:seq_num()) and (self:ack_num() == other:ack_num()) end local function test_tcp_checksum () local ipv4 = require("lib.protocol.ipv4") local IP_BASE = 14 local IP_HDR_SIZE = 20 local TCP_BASE = IP_BASE + IP_HDR_SIZE local TCP_HDR_SIZE = 20 local PAYLOAD_BASE = TCP_BASE + TCP_HDR_SIZE local p = packet.from_string(lib.hexundump([[ 52:54:00:02:02:02 52:54:00:01:01:01 08 00 45 00 00 34 59 1a 40 00 40 06 00 00 c0 a8 14 a9 6b 15 f0 b4 de 0b 01 bb e7 db 57 bc 91 cd 18 32 80 10 05 9f 00 00 00 00 01 01 08 0a 06 0c 5c bd fa 4a e1 65 ]], 66)) local ip_hdr = ipv4:new_from_mem(p.data + IP_BASE, IP_HDR_SIZE) local tcp_hdr = tcp:new_from_mem(p.data + TCP_BASE, TCP_HDR_SIZE) local payload_length = p.length - PAYLOAD_BASE local csum = tcp_hdr:checksum(p.data + PAYLOAD_BASE, payload_length, ip_hdr) assert(csum == 0x382a, "Wrong TCP checksum") end function selftest () test_tcp_checksum() end tcp.selftest = selftest return tcp
apache-2.0
mahdib9/kp
plugins/plugins.lua
325
6164
do -- Returns the key (index) in the config.enabled_plugins table local function plugin_enabled( name ) for k,v in pairs(_config.enabled_plugins) do if name == v then return k end end -- If not found return false end -- Returns true if file exists in plugins folder local function plugin_exists( name ) for k,v in pairs(plugins_names()) do if name..'.lua' == v then return true end end return false end local function list_all_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..nsum..'. '..v..' '..status..'\n' end end local text = text..'\nThere are '..nsum..' plugins installed.\n'..nact..' plugins enabled and '..nsum-nact..' disabled' return text end local function list_plugins(only_enabled) local text = '' local nsum = 0 for k, v in pairs( plugins_names( )) do -- ✔ enabled, ❌ disabled local status = '❌' nsum = nsum+1 nact = 0 -- Check if is enabled for k2, v2 in pairs(_config.enabled_plugins) do if v == v2..'.lua' then status = '✔' end nact = nact+1 end if not only_enabled or status == '✔' then -- get the name v = string.match (v, "(.*)%.lua") text = text..v..' '..status..'\n' end end local text = text..'\n'..nact..' plugins enabled from '..nsum..' plugins installed.' return text end local function reload_plugins( ) plugins = {} load_plugins() return list_plugins(true) end local function enable_plugin( plugin_name ) print('checking if '..plugin_name..' exists') -- Check if plugin is enabled if plugin_enabled(plugin_name) then return 'Plugin '..plugin_name..' is enabled' end -- Checks if plugin exists if plugin_exists(plugin_name) then -- Add to the config table table.insert(_config.enabled_plugins, plugin_name) print(plugin_name..' added to _config table') save_config() -- Reload the plugins return reload_plugins( ) else return 'Plugin '..plugin_name..' does not exists' end end local function disable_plugin( name, chat ) -- Check if plugins exists if not plugin_exists(name) then return 'Plugin '..name..' does not exists' end local k = plugin_enabled(name) -- Check if plugin is enabled if not k then return 'Plugin '..name..' not enabled' end -- Disable and reload table.remove(_config.enabled_plugins, k) save_config( ) return reload_plugins(true) end local function disable_plugin_on_chat(receiver, plugin) if not plugin_exists(plugin) then return "Plugin doesn't exists" end if not _config.disabled_plugin_on_chat then _config.disabled_plugin_on_chat = {} end if not _config.disabled_plugin_on_chat[receiver] then _config.disabled_plugin_on_chat[receiver] = {} end _config.disabled_plugin_on_chat[receiver][plugin] = true save_config() return 'Plugin '..plugin..' disabled on this chat' end local function reenable_plugin_on_chat(receiver, plugin) if not _config.disabled_plugin_on_chat then return 'There aren\'t any disabled plugins' end if not _config.disabled_plugin_on_chat[receiver] then return 'There aren\'t any disabled plugins for this chat' end if not _config.disabled_plugin_on_chat[receiver][plugin] then return 'This plugin is not disabled' end _config.disabled_plugin_on_chat[receiver][plugin] = false save_config() return 'Plugin '..plugin..' is enabled again' end local function run(msg, matches) -- Show the available plugins if matches[1] == '!plugins' and is_sudo(msg) then --after changed to moderator mode, set only sudo return list_all_plugins() end -- Re-enable a plugin for this chat if matches[1] == 'enable' and matches[3] == 'chat' then local receiver = get_receiver(msg) local plugin = matches[2] print("enable "..plugin..' on this chat') return reenable_plugin_on_chat(receiver, plugin) end -- Enable a plugin if matches[1] == 'enable' and is_sudo(msg) then --after changed to moderator mode, set only sudo local plugin_name = matches[2] print("enable: "..matches[2]) return enable_plugin(plugin_name) end -- Disable a plugin on a chat if matches[1] == 'disable' and matches[3] == 'chat' then local plugin = matches[2] local receiver = get_receiver(msg) print("disable "..plugin..' on this chat') return disable_plugin_on_chat(receiver, plugin) end -- Disable a plugin if matches[1] == 'disable' and is_sudo(msg) then --after changed to moderator mode, set only sudo if matches[2] == 'plugins' then return 'This plugin can\'t be disabled' end print("disable: "..matches[2]) return disable_plugin(matches[2]) end -- Reload all the plugins! if matches[1] == 'reload' and is_sudo(msg) then --after changed to moderator mode, set only sudo return reload_plugins(true) end end return { description = "Plugin to manage other plugins. Enable, disable or reload.", usage = { moderator = { "!plugins disable [plugin] chat : disable plugin only this chat.", "!plugins enable [plugin] chat : enable plugin only this chat.", }, sudo = { "!plugins : list all plugins.", "!plugins enable [plugin] : enable plugin.", "!plugins disable [plugin] : disable plugin.", "!plugins reload : reloads all plugins." }, }, patterns = { "^!plugins$", "^!plugins? (enable) ([%w_%.%-]+)$", "^!plugins? (disable) ([%w_%.%-]+)$", "^!plugins? (enable) ([%w_%.%-]+) (chat)", "^!plugins? (disable) ([%w_%.%-]+) (chat)", "^!plugins? (reload)$" }, run = run, moderated = true, -- set to moderator mode --privileged = true } end
gpl-2.0
AmirPGA/AmirPGA
plugins/banhammer.lua
27
10471
local function is_user_whitelisted(id) local hash = 'whitelist:user#id'..id local white = redis:get(hash) or false return white end local function is_chat_whitelisted(id) local hash = 'whitelist:chat#id'..id local white = redis:get(hash) or false return white end local function kick_user(user_id, chat_id) local chat = 'chat#id'..chat_id local user = 'user#id'..user_id chat_del_user(chat, user, ok_cb, true) end local function ban_user(user_id, chat_id) -- Save to redis local hash = 'banned:'..chat_id..':'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function superban_user(user_id, chat_id) -- Save to redis local hash = 'superbanned:'..user_id redis:set(hash, true) -- Kick from chat kick_user(user_id, chat_id) end local function is_banned(user_id, chat_id) local hash = 'banned:'..chat_id..':'..user_id local banned = redis:get(hash) return banned or false end local function is_super_banned(user_id) local hash = 'superbanned:'..user_id local superbanned = redis:get(hash) return superbanned or false end local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat if action == 'chat_add_user' or action == 'chat_add_user_link' then local user_id if msg.action.link_issuer then user_id = msg.from.id else user_id = msg.action.user.id end print('Checking invited user '..user_id) local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, msg.to.id) if superbanned or banned then print('User is banned!') kick_user(user_id, msg.to.id) end end -- No further checks return msg end -- BANNED USER TALKING if msg.to.type == 'chat' then local user_id = msg.from.id local chat_id = msg.to.id local superbanned = is_super_banned(user_id) local banned = is_banned(user_id, chat_id) if superbanned then print('SuperBanned user talking!') superban_user(user_id, chat_id) msg.text = '' end if banned then print('Banned user talking!') ban_user(user_id, chat_id) msg.text = '' end end -- WHITELIST local hash = 'whitelist:enabled' local whitelist = redis:get(hash) local issudo = is_sudo(msg) -- Allow all sudo users even if whitelist is allowed if whitelist and not issudo then print('Whitelist enabled and not sudo') -- Check if user or chat is whitelisted local allowed = is_user_whitelisted(msg.from.id) if not allowed then print('User '..msg.from.id..' not whitelisted') if msg.to.type == 'chat' then allowed = is_chat_whitelisted(msg.to.id) if not allowed then print ('Chat '..msg.to.id..' not whitelisted') else print ('Chat '..msg.to.id..' whitelisted :)') end end else print('User '..msg.from.id..' allowed :)') end if not allowed then msg.text = '' end else print('Whitelist not enabled or is sudo') end return msg end local function username_id(cb_extra, success, result) local get_cmd = cb_extra.get_cmd local receiver = cb_extra.receiver local chat_id = cb_extra.chat_id local member = cb_extra.member local text = 'No user @'..member..' in this group.' for k,v in pairs(result.members) do vusername = v.username if vusername == member then member_username = member member_id = v.id if get_cmd == 'kick' then return kick_user(member_id, chat_id) elseif get_cmd == 'ban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'superban user' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned!') return superban_user(member_id, chat_id) elseif get_cmd == 'whitelist user' then local hash = 'whitelist:user#id'..member_id redis:set(hash, true) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] whitelisted') elseif get_cmd == 'whitelist delete user' then local hash = 'whitelist:user#id'..member_id redis:del(hash) return send_large_msg(receiver, 'User @'..member..' ['..member_id..'] removed from whitelist') end end end return send_large_msg(receiver, text) end local function run(msg, matches) if matches[1] == 'kickme' then kick_user(msg.from.id, msg.to.id) end if not is_momod(msg) then return nil end local receiver = get_receiver(msg) if matches[4] then get_cmd = matches[1]..' '..matches[2]..' '..matches[3] elseif matches[3] then get_cmd = matches[1]..' '..matches[2] else get_cmd = matches[1] end if matches[1] == 'ban' then local user_id = matches[3] local chat_id = msg.to.id if msg.to.type == 'chat' then if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then ban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'banned:'..chat_id..':'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end else return 'This isn\'t a chat group' end end if matches[1] == 'superban' and is_admin(msg) then local user_id = matches[3] local chat_id = msg.to.id if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then superban_user(user_id, chat_id) send_large_msg(receiver, 'User '..user_id..' globally banned!') else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=chat_id, member=member}) end end if matches[2] == 'delete' then local hash = 'superbanned:'..user_id redis:del(hash) return 'User '..user_id..' unbanned' end end if matches[1] == 'kick' then if msg.to.type == 'chat' then if string.match(matches[2], '^%d+$') then kick_user(matches[2], msg.to.id) else local member = string.gsub(matches[2], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end else return 'This isn\'t a chat group' end end if matches[1] == 'whitelist' then if matches[2] == 'enable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:set(hash, true) return 'Enabled whitelist' end if matches[2] == 'disable' and is_sudo(msg) then local hash = 'whitelist:enabled' redis:del(hash) return 'Disabled whitelist' end if matches[2] == 'user' then if string.match(matches[3], '^%d+$') then local hash = 'whitelist:user#id'..matches[3] redis:set(hash, true) return 'User '..matches[3]..' whitelisted' else local member = string.gsub(matches[3], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:set(hash, true) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] whitelisted' end if matches[2] == 'delete' and matches[3] == 'user' then if string.match(matches[4], '^%d+$') then local hash = 'whitelist:user#id'..matches[4] redis:del(hash) return 'User '..matches[4]..' removed from whitelist' else local member = string.gsub(matches[4], '@', '') chat_info(receiver, username_id, {get_cmd=get_cmd, receiver=receiver, chat_id=msg.to.id, member=member}) end end if matches[2] == 'delete' and matches[3] == 'chat' then if msg.to.type ~= 'chat' then return 'This isn\'t a chat group' end local hash = 'whitelist:chat#id'..msg.to.id redis:del(hash) return 'Chat '..msg.to.print_name..' ['..msg.to.id..'] removed from whitelist' end end end return { description = "Plugin to manage bans, kicks and white/black lists.", usage = { user = "!kickme : Exit from group", moderator = { "!whitelist <enable>/<disable> : Enable or disable whitelist mode", "!whitelist user <user_id> : Allow user to use the bot when whitelist mode is enabled", "!whitelist user <username> : Allow user to use the bot when whitelist mode is enabled", "!whitelist chat : Allow everybody on current chat to use the bot when whitelist mode is enabled", "!whitelist delete user <user_id> : Remove user from whitelist", "!whitelist delete chat : Remove chat from whitelist", "!ban user <user_id> : Kick user from chat and kicks it if joins chat again", "!ban user <username> : Kick user from chat and kicks it if joins chat again", "!ban delete <user_id> : Unban user", "!kick <user_id> : Kick user from chat group by id", "!kick <username> : Kick user from chat group by username", }, admin = { "!superban user <user_id> : Kick user from all chat and kicks it if joins again", "!superban user <username> : Kick user from all chat and kicks it if joins again", "!superban delete <user_id> : Unban user", }, }, patterns = { "^!(whitelist) (enable)$", "^!(whitelist) (disable)$", "^!(whitelist) (user) (.*)$", "^!(whitelist) (chat)$", "^!(whitelist) (delete) (user) (.*)$", "^!(whitelist) (delete) (chat)$", "^!(ban) (user) (.*)$", "^!(ban) (delete) (.*)$", "^!(superban) (user) (.*)$", "^!(superban) (delete) (.*)$", "^!(kick) (.*)$", "^!(kickme)$", "^!!tgservice (.+)$", }, run = run, pre_process = pre_process }
gpl-2.0
shadow0162/countly-sdk-cocos2d-x
samples/HelloPluginsLua/src/TestFBShareScene.lua
6
13701
local visibleSize = cc.Director:getInstance():getVisibleSize() local origin = cc.Director:getInstance():getVisibleOrigin() local posBR = cc.p(origin.x + visibleSize.width, origin.y) local TestFBShareScene = class("TestFBShareScene",function() return cc.Scene:create() end) function TestFBShareScene.create() local scene = TestFBShareScene.new() return scene end function TestFBShareScene:ctor() local title = cc.Label:createWithSystemFont("Test Facebook share", "Arial", 32) title:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - 50) self:addChild(title) local sdkVersion = "SDK Version is: " .. plugin.FacebookAgent:getInstance():getSDKVersion() local subTitle = cc.Label:createWithSystemFont(sdkVersion, "Arial", 12) subTitle:setPosition(origin.x + visibleSize.width / 2, origin.y + visibleSize.height - 74) self:addChild(subTitle) self:createLayerMenu() end function TestFBShareScene:sceenshot(filename) local visibleSize = cc.Director:getInstance():getVisibleSize() local origin = cc.Director:getInstance():getVisibleOrigin() local tex = cc.RenderTexture:create(visibleSize.width, visibleSize.height, cc.TEXTURE2_D_PIXEL_FORMAT_RGB_A8888) tex:setPosition((origin.x + visibleSize.width) / 2, (origin.y + visibleSize.height) / 2) tex:begin() cc.Director:getInstance():getRunningScene():visit() tex:endToLua() local imgPath = cc.FileUtils:getInstance():getWritablePath() if imgPath == "" then return "" end local ret = tex:saveToFile(filename, cc.IMAGE_FORMAT_JPEG) if ret then imgPath = imgPath .. filename print(string.format("save image to %s", imgPath)) return imgPath end return "" end local secondMenuItem_SL = { {"share a simple link", function(tag, sender) local params = { dialog = "share_link", link = "http://www.cocos2d-x.org", } if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg) print(msg) end) else params.dialog = "feed_dialog" plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg) print(msg) end) end end}, {"share a Text link", function(tag, sender) local params = { dialog = "share_link", name = "Cocos2dx-lua web site", caption = "Cocos2dx-lua caption", description = "Cocos2dx-lua description", link = "http://www.cocos2d-x.org", } if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg) print(msg) end) else params.dialog = "feed_dialog" plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg) print(msg) end) end end}, {"share a Picture link", function(tag, sender) local params = { dialog = "share_link", name = "Cocos2dx-lua web site", caption = "Cocos2dx-lua caption", description = "Cocos2dx-lua description", to = "100006738453912",--android only web view support picture = "http://files.cocos2d-x.org/images/orgsite/logo.png", link = "http://www.cocos2d-x.org", } if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg) print(msg) end) else params.dialog = "feed_dialog" plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg) print(msg) end) end end}, {"share a media link", function(tag, sender) local params = { dialog = "share_link", name = "Cocos2dx-lua web site", caption = "Cocos2dx-lua caption", description = "Cocos2dx-lua description", media_source = "http://221.203.1.212/youku/6775B002C8F48839F6AFA63BDA/0300200100540438A173C515AA2BED245C4903-F675-B311-EF1A-4544B5C04370.mp4", link = "http://www.cocos2d-x.org", } -- only support in web dialog plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg) print(msg) end) end}, } local secondMenuItem_AR = { {"Invites request", function(tag, sender) local params = { message = "Cocos2dx-lua is a great game engine", title = "Cocos2dx-lua title", } plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg) print(msg) end) end}, {"Target invite request", function(tag, sender) local params = { message = "Cocos2dx-lua is a great game engine", title = "Cocos2dx-lua title", to = "100006738453912, 10204182777160522", } --android only web view support to plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg) print(msg) end) end}, {"Specific lists of friends", function(tag, sender) local params = { message = "Cocos2dx-lua is a great game engine", title = "Cocos2dx-lua title", filters = "[{\"name\":\"company\", \"user_ids\":[\"100006738453912\",\"10204182777160522\"]}]", } -- android not support filters plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg) print(msg) end) end}, {"Sending requests explicitly", function(tag, sender) local params = { message = "Cocos2dx-lua is a great game engine", to = "100006738453912", action_type = "send", object_id = "191181717736427",-- 191181717736427 1426774790893461 } --android not support action_type plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg) print(msg) end) end}, {"Turn-based games", function(tag, sender) local params = { message = "Cocos2dx-lua is a great game engine", title = "Cocos2dx-lua title", to = "100006738453912", action_type = "turn", } -- android not support action_type plugin.FacebookAgent:getInstance():appRequest(params, function(ret, msg) print(msg) end) end}, } function TestFBShareScene:showSecondMenu(tag) local secondMenu = self:getChildByTag(2) if nil ~= secondMenu then local visibleSize = cc.Director:getInstance():getVisibleSize() local origin = cc.Director:getInstance():getVisibleOrigin() local posBR = cc.p(origin.x + visibleSize.width, origin.y) secondMenu:removeAllChildren() local top = 90 if 0 == tag then for i = 1, table.getn(secondMenuItem_SL) do local label = cc.Label:createWithSystemFont(secondMenuItem_SL[i][1], "Arial", 18) local menuItem = cc.MenuItemLabel:create(label) menuItem:registerScriptTapHandler(secondMenuItem_SL[i][2]) menuItem:setPosition(cc.p(visibleSize.width / 9, visibleSize.height - top)) secondMenu:addChild(menuItem, 0, i - 1 ) top = top + 50 end else for i = 1, table.getn(secondMenuItem_AR) do local label = cc.Label:createWithSystemFont(secondMenuItem_AR[i][1], "Arial", 18) local menuItem = cc.MenuItemLabel:create(label) menuItem:registerScriptTapHandler(secondMenuItem_AR[i][2]) menuItem:setPosition(cc.p(visibleSize.width / 9, visibleSize.height - top)) secondMenu:addChild(menuItem, 0, i - 1 ) top = top + 50 end end end end function TestFBShareScene:createLayerMenu() local backItem = cc.MenuItemFont:create("Back") backItem:registerScriptTapHandler(function() cc.Director:getInstance():replaceScene(require("HelloWorldScene").create()) end) local backSize = backItem:getContentSize() backItem:setPosition(posBR.x - backSize.width / 2, posBR.y + backSize.height / 2) local menu = cc.Menu:create(backItem) menu:setPosition(cc.p(0,0)) self:addChild(menu, 0, 1) local menuItemNames = { {"Share link", function(tag, sender) self:showSecondMenu(0) end}, {"Share open graph", function(tag, sender) local params = { dialog = "share_open_graph", action_type = "cocostestmyfc:share", preview_property_name = "cocos_document", title = "Cocos2dx-lua Game Engine", image = "http://files.cocos2d-x.org/images/orgsite/logo.png", url = "http://cocos2d-x.org/docs/catalog/en", description = "cocos document", } if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg) print(msg) end) else print("Can't open dialog for share_open_graph") end end}, {"Share photo", function(tag, sender) local fileName = "facebookshare.jpg" local imgPath = self:sceenshot(fileName) local delay = cc.DelayTime:create(2.0) local share = cc.CallFunc:create(function( ... ) local params = { dialog = "share_photo", photo = imgPath, } if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg) print(msg) end) else print("Can't open dialog for share_open_graph") end end) local seq = cc.Sequence:create(delay, share) self:runAction(seq) end}, {"Link message", function(tag, sender) local params = { dialog = "message_link", description = "Cocos2dx-lua is a great game engine", title = "Cocos2dx-lua", link = "http://www.cocos2d-x.org", imageUrl = "http://files.cocos2d-x.org/images/orgsite/logo.png", } if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg ) print(msg) end) else print("Can't open dialog for message_link") end end}, {"Open graph message", function(tag, sender) local params = { dialog = "share_open_graph", action_type = "cocostestmyfc:share", preview_property_name = "cocos_document", title = "Cocos2dx-lua Game Engine", image = "http://files.cocos2d-x.org/images/orgsite/logo.png", url = "http://cocos2d-x.org/docs/catalog/en", description = "cocos document", } if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg ) print(msg) end) else print("Can't open dialog for message_open_graph") end end}, {"Photo message", function(tag, sender) local fileName = "facebookmessage.jpg" local imgPath = self:sceenshot(fileName) local delay = cc.DelayTime:create(2.0) local share = cc.CallFunc:create(function() local params = { dialog = "message_photo", photo = imgPath, } if plugin.FacebookAgent:getInstance():canPresentDialogWithParams(params) then plugin.FacebookAgent:getInstance():dialog(params, function(ret, msg ) print(msg) end) else print("Can't open dialog for message_photo") end end) local seq = cc.Sequence:create(delay, share) self:runAction(seq) end}, {"App request", function(tag, sender) self:showSecondMenu(1) end}, } local y_pos = 0 for i = 1, table.getn(menuItemNames) do local label = cc.Label:createWithSystemFont(menuItemNames[i][1], "Arial", 22) local menuItem = cc.MenuItemLabel:create(label) menuItem:registerScriptTapHandler(menuItemNames[i][2]) y_pos = visibleSize.height - 35 * (i - 1) - 100 menuItem:setPosition(origin.x + 100, y_pos) menu:addChild(menuItem, 0, i -1 ) end --create second menu local secondMenu = cc.Menu:create() secondMenu:setPosition(cc.p(340, 0)) self:addChild(secondMenu, 0, 2) end return TestFBShareScene
mit
Kosmos82/kosmosdarkstar
scripts/globals/items/marinara_pizza.lua
18
1599
----------------------------------------- -- ID: 5743 -- Item: marinara_pizza -- Food Effect: 3hours, All Races ----------------------------------------- -- Health Points 20 -- Attack +20% (cap 50 @ 250 base attack) -- Accuracy +10% (54) -- Undead Killer ----------------------------------------- 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,5743); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 20); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 50); target:addMod(MOD_FOOD_ACCP, 10); target:addMod(MOD_FOOD_ACC_CAP, 54); target:addMod(MOD_UNDEAD_KILLER, 5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 20); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 50); target:delMod(MOD_FOOD_ACCP, 10); target:delMod(MOD_FOOD_ACC_CAP, 54); target:delMod(MOD_UNDEAD_KILLER, 5); end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Hall_of_Transference/Zone.lua
5
6470
----------------------------------- -- -- Zone: Hall_of_Transference -- ----------------------------------- package.loaded["scripts/zones/Hall_of_Transference/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/teleports"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/zones/Hall_of_Transference/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1,-281,-5,277,-276,0,284); -- Holla zone:registerRegion(2,276,-84,-82,283,-80,-75); -- Mea zone:registerRegion(3,-283,-45,-283,-276,-40,-276); -- Dem zone:registerRegion(4,0,0,0,0,0,0); zone:registerRegion(5,288.847,-83.960,-40.693,291.209,-79.960,-37.510); -- Mea Sky Teleporter zone:registerRegion(6,-240.181,-3.960,268.409,-237.671,1.960,271.291); -- Holla Sky Teleporter zone:registerRegion(7,-240.797,-43.960,-291.552,-237.944,-39.960,-288.954); -- Dem Sky Teleporter end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(274,-82,-62 ,180); elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS) then if (player:getVar("cspromy3") == 1) then if prevZone == 102 then if (player:hasKeyItem(LIGHT_OF_DEM) and player:hasKeyItem(LIGHT_OF_MEA) and not(player:hasKeyItem(LIGHT_OF_HOLLA))) then cs = 0x009B; end elseif prevZone == 108 then if (player:hasKeyItem(LIGHT_OF_HOLLA) and player:hasKeyItem(LIGHT_OF_MEA) and not(player:hasKeyItem(LIGHT_OF_DEM))) then cs = 0x009B; end elseif prevZone == 117 then if (player:hasKeyItem(LIGHT_OF_HOLLA) and player:hasKeyItem(LIGHT_OF_DEM) and not(player:hasKeyItem(LIGHT_OF_MEA))) then cs = 0x009B; end -- cs you got when you enter hall of transference for the last promyvion end end end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) switch (region:GetRegionID()): caseof { [1] = function (x) -- Holla player:setVar("option",1); player:startEvent(103); end, [2] = function (x) -- Mea player:setVar("option",1); player:startEvent(104); end, [3] = function (x) -- Dem player:setVar("option",1); player:startEvent(105); end, [4] = function (x) player:setVar("option",2); player:startEvent(103); end, [5] = function (x) if (player:getVar("MeaChipRegistration") == 1) then local Rand = math.random(1,100); if (Rand <= 95) then -- 5% Chance chip breaks player:startEvent(0x00A1); -- To Sky else player:startEvent(0x00A9); -- Chip Breaks! end else player:startEvent(0x00A2); -- Please Register.. end end, [6] = function (x) if (player:getVar("HollaChipRegistration") == 1) then local Rand = math.random(1,100); if (Rand <= 95) then -- 5% Chance chip breaks player:startEvent(0x00A1); -- To Sky else player:startEvent(0x00AA); -- Chip Breaks! end else player:startEvent(0x00A2); -- Please Register.. end end, [7] = function (x) if (player:getVar("DemChipRegistration") == 1) then local Rand = math.random(1,100); if (Rand <= 95) then -- 5% Chance chip breaks player:startEvent(0x00A1); -- To Sky else player:startEvent(0x00AB); -- Chip Breaks! end else player:startEvent(0x00A2); -- Please Register.. end end, } end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 103 and option == 1) then player:setPos(340.082, 19.103, -59.979, 127, 102); -- To La Theine Plateau {R} elseif (csid == 104 and option == 1) then player:setPos(179.92, 35.15, 260.137, 64, 117); -- To Tahrongi Canyon {R} elseif (csid == 105 and option == 1) then player:setPos(139.974, 19.103, 219.989, 128, 108); -- To Konschtat Highlands {R} elseif (csid == 155) then player:setVar("cspromy3",0) player:setVar("cslastpromy",1) if (not(player:hasKeyItem(LIGHT_OF_DEM))) then -- print("shouldbezonedtodem") player:setPos(185.891, 0, -52.331, 128, 18); -- To Promyvion Dem {R} elseif (not(player:hasKeyItem(LIGHT_OF_HOLLA))) then -- print("shouldbezonedtoholla") player:setPos(92.033, 0, 80.380, 255, 16); -- To Promyvion Holla {R} elseif (not(player:hasKeyItem(LIGHT_OF_MEA))) then player:setPos(-93.268, 0, 170.749, 162, 20); -- To Promyvion Mea {R} end elseif (csid == 161 and option == 1) then toSkyGreenPorterLeft(player); elseif (csid == 169 and option == 1) then player:setVar("MeaChipRegistration",0); toSkyGreenPorterLeft(player); elseif (csid == 170 and option == 1) then player:setVar("HollaChipRegistration",0); toSkyGreenPorterLeft(player); elseif (csid == 171 and option == 1) then player:setVar("DemChipRegistration",0); toSkyGreenPorterLeft(player); end end;
gpl-3.0
martin-traverse/premake-core
tests/base/test_context.lua
17
1060
-- -- tests/base/test_context.lua -- Test suite for the configuration context API. -- Copyright (c) 2012-2014 Jason Perkins and the Premake project -- local suite = test.declare("context") local context = premake.context local configset = premake.configset local field = premake.field -- -- Setup and teardown -- local ctx, cset function suite.setup() cset = configset.new() ctx = context.new(cset) end -- -- Make sure that new() returns a valid object. -- function suite.new_returnsValidObject() test.isequal("table", type(ctx)) end -- -- Context should be able to retrieve a default value from -- the configuration set, using the field name. -- function suite.returnsConfigValue_onExistingValue() configset.store(cset, field.get("targetextension"), ".so") test.isequal(".so", ctx.targetextension) end -- -- Tokens encountered in enabled fields should be expanded. -- function suite.doesExpandTokens() configset.store(cset, field.get("targetname"), "MyProject%{1 + 1}") test.isequal("MyProject2", ctx.targetname) end
bsd-3-clause
Humbedooh/ponymail
site/api/thread.lua
2
4563
--[[ Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to You 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. ]]-- -- This is thread.lua - a script for fetching a thread based on a message -- that is in said thread. local JSON = require 'cjson' local elastic = require 'lib/elastic' local aaa = require 'lib/aaa' local user = require 'lib/user' local cross = require 'lib/cross' local config = require 'lib/config' local utils = require 'lib/utils' local emls_thrd -- func that fetches all children of an original topic email thingy local function fetchChildren(r, pdoc, c, biglist, account) c = (c or 0) + 1 -- don't fetch more than 250 subtrees, we don't want to nest ad nauseam if c > 250 then return {} end -- biglist is for making sure we dont' fetch something twice biglist = biglist or {} local children = {} -- find any emails that reference this one local emid = r:escape(pdoc['message-id']) local docs = elastic.findFast( ('in-reply-to:"%s" OR references:"%s"'):format(emid, emid), 50, "mbox") for k, doc in pairs(docs) do -- if we haven't seen this email before, check for its kids and add it to the bunch if (not biglist[doc['message-id']]) and aaa.canAccessDoc(r, doc, account) then biglist[doc['message-id']] = true local mykids = fetchChildren(r, doc, c, biglist, account) if not account and config.antispam then doc = utils.anonymizeHdrs(doc) end local dc = { tid = doc.mid, mid = doc.mid, subject = doc.subject, from = doc.from, id = doc.request_id, epoch = doc.epoch, children = mykids, irt = doc['in-reply-to'] } table.insert(children, dc) table.insert(emls_thrd, dc) else biglist[doc['message-id']] = true docs[k] = nil end end return children end function handle(r) cross.contentType(r, "application/json; charset=UTF-8") local DEBUG = config.debug or false local START = DEBUG and r:clock() or nil local get = r:parseargs() -- get the parameter (if any) and tidy it up local eid = (get.id or ""):gsub("\"", "") -- If it is the empty string then set it to "1" so ES doesn't barf -- N.B. ?id is treated as ?id=1 if #eid == 0 then eid = "1" end local doc = elastic.get("mbox", eid, true) emls_thrd = {} -- Try searching by mid if not found, for backward compat if not doc or not doc.mid then local docs = elastic.find("message-id:\"" .. r:escape(eid) .. "\"", 1, "mbox") if #docs == 1 then doc = docs[1] end if #docs == 0 and #eid == utils.SHORTENED_LINK_LEN then docs = elastic.find("mid:" .. r:escape(eid) .. "*", 1, "mbox") end if #docs == 1 then doc = docs[1] end end if get.timetravel then doc = utils.findParent(r, doc, elastic) end local doclist = {} -- did we find an email? if doc then local account = user.get(r) if doc and doc.mid and aaa.canAccessDoc(r, doc, account) then if not account and config.antispam then doc = utils.anonymizeHdrs(doc) end table.insert(emls_thrd, doc) doc.children = fetchChildren(r, doc, 1, nil, account) doc.tid = doc.mid doc.id = doc.request_id --doc.body = nil r:puts(JSON.encode({ took = DEBUG and (r:clock() - START) or nil, emails = emls_thrd, })) return cross.OK end end r:puts(JSON.encode{error = "No such e-mail or you do not have access to it."}) return cross.OK end cross.start(handle)
apache-2.0
Kosmos82/kosmosdarkstar
scripts/zones/Upper_Jeuno/npcs/Laila.lua
6
10576
----------------------------------- -- Area: Upper Jeuno -- NPC: Laila -- Type: Job Quest Giver -- @zone: 244 -- @pos -54.045 -1 100.996 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) --TODO-- -- make sure the surrounding npcs react to the player accordingly after each quest. There are a few event IDs that I don't recall using -- make global variables for all these event hexvalues and put them in textids --TODO-- ----------------------------------- package.loaded["scripts/zones/Upper_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); require("scripts/zones/Upper_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local lakesideMin = player:getQuestStatus(JEUNO,LAKESIDE_MINUET); local lakeProg = player:getVar("Lakeside_Minuet_Progress"); if (lakesideMin == QUEST_AVAILABLE and player:getMainLvl() >= ADVANCED_JOB_LEVEL and ENABLE_WOTG == 1) then player:startEvent(0x277f); -- Start quest csid, asks for Key Item Stardust Pebble elseif (lakesideMin == QUEST_COMPLETED and player:needToZone()) then player:startEvent(0x2787); elseif (player:hasKeyItem(STARDUST_PEBBLE)) then player:startEvent(0x2786); -- Ends Quest elseif (lakeProg == 3) then player:startEvent(0x2781); elseif (lakesideMin == QUEST_ACCEPTED) then player:startEvent(0x2780) -- After accepting, reminder elseif ((player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_AVAILABLE or (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_COMPLETED and player:hasItem(19203)==false)) and player:getMainJob()==JOB_DNC and player:getMainLvl()>=40) then player:startEvent(0x2791); elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_ACCEPTED and player:getVar("QuestStatus_DNC_AF1")==5 and player:seenKeyItem(THE_ESSENCE_OF_DANCE) and player:getMainJob()==JOB_DNC) then player:startEvent(0x2795); elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_ACCEPTED) then player:startEvent(0x2796); --Dancer AF: The Road to Divadom-- elseif (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_COMPLETED and player:getQuestStatus(JEUNO,THE_ROAD_TO_DIVADOM) == QUEST_AVAILABLE and player:getMainJob()==JOB_DNC) then player:startEvent(0x2798); -- CSID 10136 elseif (player:getVar("roadToDivadomCS") == 1) then player:startEvent(0x2799); -- quest chat line after the quest has been accepted elseif (player:getVar("roadToDivadomCS") == 4) then player:startEvent(0x279B); --CSID 10139 elseif (player:getVar("roadToDivadomCS") == 5) then player:startEvent(0x27BA); --CSID 10170. This should only occur if the player's inventory was full during the chain of events that start in the elseif above. --Dancer AF: Comeback Queen-- elseif (player:getQuestStatus(JEUNO,THE_ROAD_TO_DIVADOM) == QUEST_COMPLETED and player:getQuestStatus(JEUNO, COMEBACK_QUEEN) == QUEST_AVAILABLE and player:getMainJob()==JOB_DNC) then player:startEvent(0x279F); elseif (player:getVar("comebackQueenCS") == 1) then player:startEvent(0x27A0); -- quest chat line after quest accepted; Rhea and Olgald have a line as well. elseif (player:getVar("comebackQueenCS") == 2) then player:startEvent(0x27A3); elseif (player:getVar("comebackQueenCS") == 3 or player:getVar("comebackQueenCS") == 6) then local currentVanaDay = VanadielDayOfTheYear(); if (player:getVar("comebackQueenDanceOffTimer") < currentVanaDay) then player:startEvent(0x27A7); -- play laila cs 10152->10154 olgald: 1053 if they lose the minigame else player:startEvent(0x279C); end; elseif (player:getVar("comebackQueenCS") == 4 or player:getVar("comebackQueenCS") == 5) then player:startEvent(0x27AA); --This occurs if the player's inventory was full during the final chain of events or if the player speaks with laila afterwards. else player:startEvent(0x2788); -- Default 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 == 0x277f and option == 1) then player:addQuest(JEUNO,LAKESIDE_MINUET); elseif (csid == 0x2786) then player:setVar("Lakeside_Minuet_Progress",0); player:completeQuest(JEUNO,LAKESIDE_MINUET); player:addTitle(TROUPE_BRILIOTH_DANCER); player:unlockJob(19); player:messageSpecial(UNLOCK_DANCER); player:addFame(JEUNO, 30); player:delKeyItem(STARDUST_PEBBLE); player:needToZone(true); elseif (csid==0x2791) then if (player:getQuestStatus(JEUNO,THE_UNFINISHED_WALTZ) == QUEST_COMPLETED) then player:delQuest(JEUNO,THE_UNFINISHED_WALTZ); player:delKeyItem(THE_ESSENCE_OF_DANCE); end player:addQuest(JEUNO,THE_UNFINISHED_WALTZ); player:setVar("QuestStatus_DNC_AF1", 1); elseif (csid==0x2795) then player:setVar("QuestStatus_DNC_AF1", 0); player:addItem(19203); -- war hoop player:messageSpecial(ITEM_OBTAINED,19203); player:completeQuest(JEUNO,THE_UNFINISHED_WALTZ); --Dancer AF: The Road to Divadom-- elseif (csid == 0x2798) then -- Road To Divadom pt 1 player:setVar("roadToDivadomCS", 1); player:addQuest(JEUNO, THE_ROAD_TO_DIVADOM); elseif (csid == 0x279B) then -- string of events player:startEvent(0x27E6); elseif (csid == 0x27E6) then player:startEvent(0x27E7); elseif (csid == 0x27E7) then player:setVar("roadToDivadomCS", 5); player:startEvent(0x27BA); elseif (csid == 0x27BA) then if (player:getFreeSlotsCount() == 0) then --do nothing. player doesn't have room to receive the reward item. player:messageSpecial( ITEM_CANNOT_BE_OBTAINED, 15660); -- the names of the gender specific items are the same else player:completeQuest(JEUNO, THE_ROAD_TO_DIVADOM); player:setVar("roadToDivadomCS", 0); player:setVar("dancerTailorCS", 1); -- allows player to start dancer version of Coffer AF. check Olgald and Matthias(@Bastok Markets) for the rest of the quest line --determine what gender the player is so we can give the correct item local playerGender = player:getGender(); local dancersTights = 15660 - playerGender; player:addItem(dancersTights); player:messageSpecial(ITEM_OBTAINED, dancersTights); player:completeQuest(JEUNO, THE_ROAD_TO_DIVADOM); end; --Dancer AF: Comeback Queen -- elseif (csid == 0x279F) then player:setVar("comebackQueenCS", 1); player:addQuest(JEUNO, COMEBACK_QUEEN); player:addKeyItem(WYATTS_PROPOSAL); player:messageSpecial( KEYITEM_OBTAINED, WYATTS_PROPOSAL); elseif (csid == 0x27A3) then player:setVar("comebackQueenCS", 3); local danceOffTimer = VanadielDayOfTheYear(); player:setVar("comebackQueenDanceOffTimer", danceOffTimer); elseif (csid == 0x27A7) then --the dance off minigame if (option > 0) then -- player won the minigame player:startEvent(0x27E0); -- starts exhausting string of events else player:setVar("comebackQueenCS", 6); -- have surrounding npcs use losing state CS local danceOffTimer = VanadielDayOfTheYear(); player:setVar("comebackQueenDanceOffTimer", danceOffTimer); end; elseif (csid == 0x27E0) then player:startEvent(0x27E1); elseif (csid == 0x27E1) then player:startEvent(0x27E2); elseif (csid == 0x27E2) then player:setVar("comebackQueenCS", 4); player:startEvent(0x27E3); elseif (csid == 0x27E3) then --finally reward the player if (player:getFreeSlotsCount() == 0) then --do nothing. player doesn't have room to receive the reward item. player:messageSpecial( ITEM_CANNOT_BE_OBTAINED, 14578); -- the names of the gender specific items are the same else player:completeQuest(JEUNO, COMEBACK_QUEEN); player:setVar("comebackQueenCS", 5); -- final state for all of the surrounding NPCs --determine what gender the player is so we can give the correct item local playerGender = player:getGender(); local dancersCasaque = 14579 - playerGender; player:addItem(dancersCasaque); player:messageSpecial(ITEM_OBTAINED, dancersCasaque); player:completeQuest(JEUNO, COMEBACK_QUEEN); end; elseif (csid == 0x27AA) then if (player:getVar("comebackQueenCS") == 4) then -- player's inventory was full at the end of the final cutscene if (player:getFreeSlotsCount() == 0) then --do nothing. player doesn't have room to receive the reward item. player:messageSpecial( ITEM_CANNOT_BE_OBTAINED, 14578); -- the names of the gender specific items are the same else player:completeQuest(JEUNO, COMEBACK_QUEEN); player:setVar("comebackQueenCS", 5); -- final state for all of the surrounding NPCs --determine what gender the player is so we can give the correct item local playerGender = player:getGender(); local dancersCasaque = 14579 - playerGender; player:addItem(dancersCasaque); player:messageSpecial(ITEM_OBTAINED, dancersCasaque); player:completeQuest(JEUNO, COMEBACK_QUEEN); end; --the surrounding NPCs should have their dialogue check comebackqueenCS as well. end; end; end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Chateau_dOraguille/npcs/Perfaumand.lua
13
1712
----------------------------------- -- Area: Chateau d'Oraguille -- NPC: Perfaumand -- Involved in Quest: Lure of the Wildcat (San d'Oria) -- @pos -39 -3 69 233 ----------------------------------- package.loaded["scripts/zones/Chateau_dOraguille/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Chateau_dOraguille/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE) == QUEST_ACCEPTED) then if (trade:hasItemQty(532,1) and trade:getItemCount() == 1) then -- Trade Magicmart_flyer player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local WildcatSandy = player:getVar("WildcatSandy"); if (player:getQuestStatus(SANDORIA,LURE_OF_THE_WILDCAT_SAN_D_ORIA) == QUEST_ACCEPTED and player:getMaskBit(WildcatSandy,18) == false) then player:startEvent(0x0230); else player:startEvent(0x020a); 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 == 0x0230) then player:setMaskBit(player:getVar("WildcatSandy"),"WildcatSandy",18,true); end end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/globals/abilities/devotion.lua
44
1670
----------------------------------- -- Ability: Devotion -- Sacrifices HP to grant a party member the same amount in MP. -- Obtained: White Mage Level 75 -- Recast Time: 0:10:00 -- Duration: Instant -- Target: Party member, cannot target self. ----------------------------------- require("scripts/globals/status"); require("scripts/globals/utils"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) if (player:getID() == target:getID()) then return MSGBASIC_CANNOT_PERFORM_TARG,0; elseif (player:getHP() < 4) then -- Fails if HP < 4 return MSGBASIC_UNABLE_TO_USE_JA,0; else return 0,0; end end; ----------------------------------- -- onUseAbility ----------------------------------- function onUseAbility(player,target,ability) -- Plus 5 percent mp recovers per extra devotion merit local meritBonus = player:getMerit(MERIT_DEVOTION) - 5; -- printf("Devotion Merit Bonus: %d", meritBonus); local mpPercent = (25 + meritBonus) / 100; -- printf("Devotion MP Percent: %f", mpPercent); local damageHP = math.floor(player:getHP() * 0.25); -- printf("Devotion HP Damage: %d", damageHP); -- If stoneskin is present, it should absorb damage... damageHP = utils.stoneskin(player, damageHP); -- printf("Devotion HP Damage (after Stoneskin): %d", damageHP); local healMP = player:getHP() * mpPercent; healMP = utils.clamp(healMP, 0,target:getMaxMP() - target:getMP()); -- printf("Devotion MP Healed: %d", healMP); player:delHP(damageHP); target:addMP(healMP); return healMP; end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Al_Zahbi/npcs/Macici.lua
53
2304
----------------------------------- -- Area: Al Zahbi -- NPC: Macici -- Type: Smithing Normal/Adv. Image Support -- @pos -35.163 -1 -31.351 48 ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); require("scripts/zones/Al_Zahbi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local guildMember = isGuildMember(player,8); if (guildMember == 1) then if (trade:hasItemQty(2184,1) and trade:getItemCount() == 1) then if (player:hasStatusEffect(EFFECT_SMITHING_IMAGERY) == false) then player:tradeComplete(); player:startEvent(0x00E9,8,0,0,0,188,0,2,0); else npc:showText(npc, IMAGE_SUPPORT_ACTIVE); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local guildMember = isGuildMember(player,8); local SkillLevel = player:getSkillLevel(SKILL_SMITHING); if (guildMember == 1) then if (player:hasStatusEffect(EFFECT_SMITHING_IMAGERY) == false) then player:startEvent(0x00E8,8,SkillLevel,0,511,188,0,2,2184); else player:startEvent(0x00E8,8,SkillLevel,0,511,188,6566,2,2184); end else player:startEvent(0x00E8,0,0,0,0,0,0,2,0); -- Standard Dialogue end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x00E8 and option == 1) then player:messageSpecial(IMAGE_SUPPORT,0,2,1); player:addStatusEffect(EFFECT_SMITHING_IMAGERY,1,0,120); elseif (csid == 0x00E9) then player:messageSpecial(IMAGE_SUPPORT,0,2,0); player:addStatusEffect(EFFECT_SMITHING_IMAGERY,3,0,480); end end;
gpl-3.0
premake/premake-dlang
tools/dmd.lua
7
8729
-- -- d/tools/dmd.lua -- Provides dmd-specific configuration strings. -- Copyright (c) 2013-2015 Andrew Gough, Manu Evans, and the Premake project -- local tdmd = {} local project = premake.project local config = premake.config local d = premake.modules.d -- -- Set default tools -- tdmd.gcc = {} tdmd.gcc.dc = "dmd" tdmd.optlink = {} tdmd.optlink.dc = "dmd" -- ///////////////////////////////////////////////////////////////////////// -- dmd + GCC toolchain -- ///////////////////////////////////////////////////////////////////////// -- -- Return a list of LDFLAGS for a specific configuration. -- tdmd.gcc.ldflags = { architecture = { x86 = { "-m32" }, x86_64 = { "-m64" }, }, kind = { SharedLib = "-shared", StaticLib = "-lib", } } function tdmd.gcc.getldflags(cfg) local flags = config.mapFlags(cfg, tdmd.gcc.ldflags) return flags end -- -- Return a list of decorated additional libraries directories. -- tdmd.gcc.libraryDirectories = { architecture = { x86 = "-L-L/usr/lib", x86_64 = "-L-L/usr/lib64", } } function tdmd.gcc.getLibraryDirectories(cfg) local flags = config.mapFlags(cfg, tdmd.gcc.libraryDirectories) -- Scan the list of linked libraries. If any are referenced with -- paths, add those to the list of library search paths for _, dir in ipairs(config.getlinks(cfg, "system", "directory")) do table.insert(flags, '-L-L' .. project.getrelative(cfg.project, dir)) end return flags end -- -- Return the list of libraries to link, decorated with flags as needed. -- function tdmd.gcc.getlinks(cfg, systemonly) local result = {} local links if not systemonly then links = config.getlinks(cfg, "siblings", "object") for _, link in ipairs(links) do -- skip external project references, since I have no way -- to know the actual output target path if not link.project.external then if link.kind == premake.STATICLIB then -- Don't use "-l" flag when linking static libraries; instead use -- path/libname.a to avoid linking a shared library of the same -- name if one is present table.insert(result, "-L" .. project.getrelative(cfg.project, link.linktarget.abspath)) else table.insert(result, "-L-l" .. link.linktarget.basename) end end end end -- The "-l" flag is fine for system libraries links = config.getlinks(cfg, "system", "fullpath") for _, link in ipairs(links) do if path.isframework(link) then table.insert(result, "-framework " .. path.getbasename(link)) elseif path.isobjectfile(link) then table.insert(result, "-L" .. link) else table.insert(result, "-L-l" .. path.getbasename(link)) end end return result end -- ///////////////////////////////////////////////////////////////////////// -- tdmd + OPTLINK toolchain -- ///////////////////////////////////////////////////////////////////////// -- -- Return a list of LDFLAGS for a specific configuration. -- tdmd.optlink.ldflags = { architecture = { x86 = { "-m32" }, x86_64 = { "-m64" }, }, kind = { SharedLib = "-shared", StaticLib = "-lib", } } function tdmd.optlink.getldflags(cfg) local flags = config.mapFlags(cfg, tdmd.optlink.ldflags) return flags end -- -- Return a list of decorated additional libraries directories. -- function tdmd.optlink.getLibraryDirectories(cfg) local flags = {} -- Scan the list of linked libraries. If any are referenced with -- paths, add those to the list of library search paths for _, dir in ipairs(config.getlinks(cfg, "system", "directory")) do table.insert(flags, '-Llib "' .. project.getrelative(cfg.project, dir) .. '"') end return flags end -- -- Returns a list of linker flags for library names. -- function tdmd.optlink.getlinks(cfg) local result = {} local links = config.getlinks(cfg, "dependencies", "object") for _, link in ipairs(links) do -- skip external project references, since I have no way -- to know the actual output target path if not link.project.externalname then local linkinfo = config.getlinkinfo(link) if link.kind == premake.STATICLIB then table.insert(result, project.getrelative(cfg.project, linkinfo.abspath)) end end end -- The "-l" flag is fine for system libraries links = config.getlinks(cfg, "system", "basename") for _, link in ipairs(links) do if path.isobjectfile(link) then table.insert(result, link) elseif path.hasextension(link, premake.systems[cfg.system].staticlib.extension) then table.insert(result, link) end end return result end -- ///////////////////////////////////////////////////////////////////////// -- common dmd code (either toolchain) -- ///////////////////////////////////////////////////////////////////////// -- if we are compiling on windows, we need to specialise to OPTLINK as the linker -- OR!!! if cfg.system ~= premake.WINDOWS then if string.match( os.getversion().description, "Windows" ) ~= nil then -- TODO: on windows, we may use OPTLINK or MSLINK (for Win64)... -- printf("TODO: select proper linker for 32/64 bit code") premake.tools.dmd = tdmd.optlink else premake.tools.dmd = tdmd.gcc end local dmd = premake.tools.dmd -- -- Returns list of D compiler flags for a configuration. -- dmd.dflags = { architecture = { x86 = "-m32", x86_64 = "-m64", }, flags = { CodeCoverage = "-cov", Deprecated = "-d", Documentation = "-D", FatalWarnings = "-w", GenerateHeader = "-H", GenerateJSON = "-X", GenerateMap = "-map", NoBoundsCheck = "-noboundscheck", Profile = "-profile", Quiet = "-quiet", -- Release = "-release", RetainPaths = "-op", SymbolsLikeC = "-gc", UnitTest = "-unittest", Verbose = "-v", }, floatingpoint = { None = "-nofloat", }, optimize = { On = "-O -inline", Full = "-O -inline", Size = "-O -inline", Speed = "-O -inline", }, pic = { On = "-fPIC", }, warnings = { Default = "-wi", Extra = "-wi", }, symbols = { On = "-g", } } function dmd.getdflags(cfg) local flags = config.mapFlags(cfg, dmd.dflags) if config.isDebugBuild(cfg) then table.insert(flags, "-debug") else table.insert(flags, "-release") end -- TODO: When DMD gets CRT options, map StaticRuntime and DebugRuntime if cfg.flags.Documentation then if cfg.docname then table.insert(flags, "-Df" .. premake.quoted(cfg.docname)) end if cfg.docdir then table.insert(flags, "-Dd" .. premake.quoted(cfg.docdir)) end end if cfg.flags.GenerateHeader then if cfg.headername then table.insert(flags, "-Hf" .. premake.quoted(cfg.headername)) end if cfg.headerdir then table.insert(flags, "-Hd" .. premake.quoted(cfg.headerdir)) end end return flags end -- -- Decorate versions for the DMD command line. -- function dmd.getversions(versions, level) local result = {} for _, version in ipairs(versions) do table.insert(result, '-version=' .. version) end if level then table.insert(result, '-version=' .. level) end return result end -- -- Decorate debug constants for the DMD command line. -- function dmd.getdebug(constants, level) local result = {} for _, constant in ipairs(constants) do table.insert(result, '-debug=' .. constant) end if level then table.insert(result, '-debug=' .. level) end return result end -- -- Decorate import file search paths for the DMD command line. -- function dmd.getimportdirs(cfg, dirs) local result = {} for _, dir in ipairs(dirs) do dir = project.getrelative(cfg.project, dir) table.insert(result, '-I' .. premake.quoted(dir)) end return result end -- -- Returns the target name specific to compiler -- function dmd.gettarget(name) return "-of" .. name end -- -- Returns makefile-specific configuration rules. -- dmd.makesettings = { } function dmd.getmakesettings(cfg) local settings = config.mapFlags(cfg, dmd.makesettings) return table.concat(settings) end -- -- Retrieves the executable command name for a tool, based on the -- provided configuration and the operating environment. -- -- @param cfg -- The configuration to query. -- @param tool -- The tool to fetch, one of "dc" for the D compiler, or "ar" for the static linker. -- @return -- The executable command name for a tool, or nil if the system's -- default value should be used. -- dmd.tools = { -- dmd will probably never support any foreign architectures...? } function dmd.gettoolname(cfg, tool) local names = dmd.tools[cfg.architecture] or dmd.tools[cfg.system] or {} local name = names[tool] return name or dmd[tool] end
bsd-3-clause
Kosmos82/kosmosdarkstar
scripts/zones/Gustav_Tunnel/mobs/Goblin_Mercenary.lua
6
1043
---------------------------------- -- Area: Gustav Tunnel -- MOB: Goblin Mercenary -- Note: Place holder Wyvernpoacher Drachlox ----------------------------------- require("scripts/globals/groundsofvalor"); require("scripts/zones/Gustav_Tunnel/MobIDs"); ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer,ally) checkGoVregime(ally,mob,764,3); checkGoVregime(ally,mob,765,3); local mobID = mob:getID(); if (Wyvernpoacher_Drachlox_PH[mobID] ~= nil) then local ToD = GetServerVariable("[POP]Wyvernpoacher_Drachlox"); if (ToD <= os.time(t) and GetMobAction(Wyvernpoacher_Drachlox) == 0) then if (math.random(1,20) == 5) then UpdateNMSpawnPoint(Wyvernpoacher_Drachlox); GetMobByID(Wyvernpoacher_Drachlox):setRespawnTime(GetMobRespawnTime(mobID)); SetServerVariable("[PH]Wyvernpoacher_Drachlox", mobID); DeterMob(mobID, true); end end end end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/zones/Port_Jeuno/npcs/Squintrox_Dryeyes.lua
13
4859
----------------------------------- -- Area: Port Jeuno -- NPC: Squintrox Dryeyes -- Type: Addon Mission Merchant -- @pos -100.071 -1 11.869 246 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local now = tonumber(os.date("%j")); local count = trade:getItemCount(); local sLux = trade:hasItemQty(2740,1); local sLuna = trade:hasItemQty(2741,1); local sAstrum = trade:hasItemQty(2742,1); local orcArmor = trade:hasItemQty(2757,1); local quadavBack = trade:hasItemQty(596,1); local yagCaulk = trade:hasItemQty(2759,1); local eKitBlind = trade:hasItemQty(2780,1); local eKitPoison = trade:hasItemQty(2779,1); local eKitSilence = trade:hasItemQty(2782,1); local eKitSleep = trade:hasItemQty(2781,1); local uggalepihWhistle = trade:hasItemQty(1184,1); local ACPm = player:getCurrentMission(ACP); local AMKm = player:getCurrentMission(AMK); local ASAm = player:getCurrentMission(ASA); local CrimsonKey = player:hasKeyItem(CRIMSON_KEY); local LastCrimson = player:getVar("LastCrimsonKey"); -- When last Crimson key was obtained if (ENABLE_ACP == 0 and ENABLE_AMK == 0 and ENABLE_ASA ==0) then player:showText(npc,GET_LOST); else -- Crimson Key: Trade Seedspall's Lux, Luna, Astrum if (ENABLE_ACP == 1 and sLux and sLuna and sAstrum and count == 3 and ACPm >= GATHERER_OF_LIGHT_I and CrimsonKey == false and now ~= LastCrimson) then -- and timer stuff here) then player:tradeComplete(); player:addKeyItem(CRIMSON_KEY); player:setVar("LastCrimsonKey", os.date("%j")); player:messageSpecial(DRYEYES_2); player:messageSpecial(KEYITEM_OBTAINED,CRIMSON_KEY); elseif (sLux and sLuna and sAstrum and count == 3 and (now == LastCrimson or CrimsonKey == true)) then player:messageSpecial(DRYEYES_3,CRIMSON_KEY); -- White Coral Key: -- elseif (ENABLE_AMK == 1 and -- haven't even started AMK related trades yet. end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_ACP == 0 and ENABLE_AMK == 0 and ENABLE_ASA ==0) then player:showText(npc,GET_LOST); else player:startEvent(0x0143); 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); -- uncommented printf till we have all optionIDs mapped out. local now = tonumber(os.date("%j")); local ACPm = player:getCurrentMission(ACP); local AMKm = player:getCurrentMission(AMK); local ASAm = player:getCurrentMission(ASA); local salad = player:hasKeyItem(BOWL_OF_BLAND_GOBLIN_SALAD); local juice = player:hasKeyItem(JUG_OF_GREASY_GOBLIN_JUICE); local grub = player:hasKeyItem(CHUNK_OF_SMOKED_GOBLIN_GRUB); local ViridianKey = player:hasKeyItem(VIRIDIAN_KEY); local LastViridian = player:getVar("LastViridianKey"); -- When last Viridian key was obtained if (csid == 0x0143) then if (option == 1) then player:showText(player,DRYEYES_1); elseif (option == 100) then if (salad and juice and grub and ACPm >= GATHERER_OF_LIGHT_I and ViridianKey == false and now ~= LastViridian) then player:addKeyItem(VIRIDIAN_KEY); player:delKeyItem(BOWL_OF_BLAND_GOBLIN_SALAD); player:delKeyItem(JUG_OF_GREASY_GOBLIN_JUICE); player:delKeyItem(CHUNK_OF_SMOKED_GOBLIN_GRUB); player:setVar("LastViridianKey", os.date("%j")); player:showText(player,DRYEYES_2); player:messageSpecial(KEYITEM_OBTAINED,VIRIDIAN_KEY); elseif (now == LastViridian or ViridianKey == true) then player:messageSpecial(DRYEYES_3,VIRIDIAN_KEY); else -- player:showText(player, ? ); -- Doesn't seem to be a message for trying when you don't have the key items? end -- Blue coral Key -- elseif (option == 101) then -- if -- end end end end;
gpl-3.0
AmirPGA/AmirPGA
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
mahdib9/kp
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
Kosmos82/kosmosdarkstar
scripts/zones/Attohwa_Chasm/npcs/qm1.lua
13
1613
----------------------------------- -- Area: Attohwa Chasm -- NPC: ??? (qm1) -- @pos -402.574 3.999 -202.750 7 ----------------------------------- package.loaded["scripts/zones/Attohwa_Chasm/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Attohwa_Chasm/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) -- Antlion Trap: ID 1825 -- Alastor Antlion: ID 16806248 -- UPDATE `mob_spawn_points` SET `pos_x`='-402.574', `pos_y`='3.999', `pos_z`='-202.75', `pos_rot`='7' WHERE (`mobid`='16806242') local feelerID =16806242; local feelerAntlion = GetMobByID(feelerID); local npcX = npc:getXPos(); local npcY = npc:getYPos(); local npcZ = npc:getZPos(); feelerAntlion:setSpawn(npcX-3,npcY-2,npcZ-1); if (GetMobAction(feelerID) == 0 and trade:hasItemQty(1825,1) and trade:getItemCount() == 1) then player:tradeComplete(); SpawnMob(feelerID,120):updateClaim(player); end end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(OCCASIONAL_LUMPS); 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
Kosmos82/kosmosdarkstar
scripts/zones/Windurst_Waters/npcs/Sohdede.lua
13
1054
----------------------------------- -- Area: Windurst Waters -- NPC: Sohdede -- Type: Standard NPC -- @zone: 238 -- @pos -60.601 -7.499 111.639 -- -- Auto-Script: Requires Verification (Verfied By Brawndo) ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x0176); 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
thing-nacho/slua
build/lsqlite3-master/tests-sqlite3.lua
12
19268
--[[-------------------------------------------------------------------------- Author: Michael Roth <mroth@nessie.de> Copyright (c) 2004, 2005 Michael Roth <mroth@nessie.de> Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. --]]-------------------------------------------------------------------------- require "lsqlite3" require "lunit" lunit.setprivfenv() lunit.import "assertions" lunit.import "checks" ------------------------------- -- Basic open and close test -- ------------------------------- lunit.wrap("open_memory", function() local db = assert_userdata( sqlite3.open_memory() ) assert( db:close() ) end) lunit.wrap("open", function() local filename = "/tmp/__lua-sqlite3-20040906135849." .. os.time() local db = assert_userdata( sqlite3.open(filename) ) assert( db:close() ) os.remove(filename) end) ------------------------------------- -- Presence of db member functions -- ------------------------------------- local db_funcs = lunit.TestCase("Database Member Functions") function db_funcs:setup() self.db = assert( sqlite3.open_memory() ) end function db_funcs:teardown() assert( self.db:close() ) end function db_funcs:test() local db = self.db assert_function( db.close ) assert_function( db.exec ) --e assert_function( db.irows ) assert_function( db.rows ) --e assert_function( db.cols ) --e assert_function( db.first_irow ) --e assert_function( db.first_row ) --e assert_function( db.first_cols ) assert_function( db.prepare ) assert_function( db.interrupt ) assert_function( db.last_insert_rowid ) assert_function( db.changes ) assert_function( db.total_changes ) end --------------------------------------- -- Presence of stmt member functions -- --------------------------------------- local stmt_funcs = lunit.TestCase("Statement Member Functions") function stmt_funcs:setup() self.db = assert( sqlite3.open_memory() ) self.stmt = assert( self.db:prepare("CREATE TABLE test (id, content)") ) end function stmt_funcs:teardown() --e- assert( self.stmt:close() ) assert( self.stmt:finalize() ) --e+ assert( self.db:close() ) end function stmt_funcs:test() local stmt = self.stmt --e assert_function( stmt.close ) assert_function( stmt.reset ) --e assert_function( stmt.exec ) assert_function( stmt.bind ) --e assert_function( stmt.irows ) --e assert_function( stmt.rows ) --e assert_function( stmt.cols ) --e assert_function( stmt.first_irow ) --e assert_function( stmt.first_row ) --e assert_function( stmt.first_cols ) --e assert_function( stmt.column_names ) --e assert_function( stmt.column_decltypes ) --e assert_function( stmt.column_count ) --e + assert_function( stmt.isopen ) assert_function( stmt.step ) assert_function( stmt.reset ) assert_function( stmt.finalize ) assert_function( stmt.columns ) assert_function( stmt.bind ) assert_function( stmt.bind_values ) assert_function( stmt.bind_names ) assert_function( stmt.bind_blob ) assert_function( stmt.bind_parameter_count ) assert_function( stmt.bind_parameter_name ) assert_function( stmt.get_value ) assert_function( stmt.get_values ) assert_function( stmt.get_name ) assert_function( stmt.get_names ) assert_function( stmt.get_type ) assert_function( stmt.get_types ) assert_function( stmt.get_uvalues ) assert_function( stmt.get_unames ) assert_function( stmt.get_utypes ) assert_function( stmt.get_named_values ) assert_function( stmt.get_named_types ) assert_function( stmt.idata ) assert_function( stmt.inames ) assert_function( stmt.itypes ) assert_function( stmt.data ) assert_function( stmt.type ) --e + end ------------------ -- Tests basics -- ------------------ local basics = lunit.TestCase("Basics") function basics:setup() self.db = assert_userdata( sqlite3.open_memory() ) end function basics:teardown() assert_number( self.db:close() ) end function basics:create_table() assert_number( self.db:exec("CREATE TABLE test (id, name)") ) end function basics:drop_table() assert_number( self.db:exec("DROP TABLE test") ) end function basics:insert(id, name) assert_number( self.db:exec("INSERT INTO test VALUES ("..id..", '"..name.."')") ) end function basics:update(id, name) assert_number( self.db:exec("UPDATE test SET name = '"..name.."' WHERE id = "..id) ) end function basics:test_create_drop() self:create_table() self:drop_table() end function basics:test_multi_create_drop() self:create_table() self:drop_table() self:create_table() self:drop_table() end function basics:test_insert() self:create_table() self:insert(1, "Hello World") self:insert(2, "Hello Lua") self:insert(3, "Hello sqlite3") end function basics:test_update() self:create_table() self:insert(1, "Hello Home") self:insert(2, "Hello Lua") self:update(1, "Hello World") end --------------------------------- -- Statement Column Info Tests -- --------------------------------- lunit.wrap("Column Info Test", function() local db = assert_userdata( sqlite3.open_memory() ) assert_number( db:exec("CREATE TABLE test (id INTEGER, name TEXT)") ) local stmt = assert_userdata( db:prepare("SELECT * FROM test") ) assert_equal(2, stmt:columns(), "Wrong number of columns." ) local names = assert_table( stmt:get_names() ) assert_equal(2, #(names), "Wrong number of names.") assert_equal("id", names[1] ) assert_equal("name", names[2] ) local types = assert_table( stmt:get_types() ) assert_equal(2, #(types), "Wrong number of declaration types.") assert_equal("INTEGER", types[1] ) assert_equal("TEXT", types[2] ) assert_equal( sqlite3.OK, stmt:finalize() ) assert_equal( sqlite3.OK, db:close() ) end) --------------------- -- Statement Tests -- --------------------- st = lunit.TestCase("Statement Tests") function st:setup() self.db = assert( sqlite3.open_memory() ) assert_equal( sqlite3.OK, self.db:exec("CREATE TABLE test (id, name)") ) assert_equal( sqlite3.OK, self.db:exec("INSERT INTO test VALUES (1, 'Hello World')") ) assert_equal( sqlite3.OK, self.db:exec("INSERT INTO test VALUES (2, 'Hello Lua')") ) assert_equal( sqlite3.OK, self.db:exec("INSERT INTO test VALUES (3, 'Hello sqlite3')") ) end function st:teardown() assert_equal( sqlite3.OK, self.db:close() ) end function st:check_content(expected) local stmt = assert( self.db:prepare("SELECT * FROM test ORDER BY id") ) local i = 0 for row in stmt:rows() do i = i + 1 assert( i <= #(expected), "Too many rows." ) assert_equal(2, #(row), "Two result column expected.") assert_equal(i, row[1], "Wrong 'id'.") assert_equal(expected[i], row[2], "Wrong 'name'.") end assert_equal( #(expected), i, "Too few rows." ) assert_number( stmt:finalize() ) end function st:test_setup() assert_pass(function() self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3" } end) assert_error(function() self:check_content{ "Hello World", "Hello Lua" } end) assert_error(function() self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "To much" } end) assert_error(function() self:check_content{ "Hello World", "Hello Lua", "Wrong" } end) assert_error(function() self:check_content{ "Hello World", "Wrong", "Hello sqlite3" } end) assert_error(function() self:check_content{ "Wrong", "Hello Lua", "Hello sqlite3" } end) end function st:test_questionmark_args() local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (?, ?)") ) assert_number( stmt:bind_values(0, "Test") ) assert_error(function() stmt:bind_values("To few") end) assert_error(function() stmt:bind_values(0, "Test", "To many") end) end function st:test_questionmark() local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (?, ?)") ) assert_number( stmt:bind_values(4, "Good morning") ) assert_number( stmt:step() ) assert_number( stmt:reset() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } assert_number( stmt:bind_values(5, "Foo Bar") ) assert_number( stmt:step() ) assert_number( stmt:reset() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } assert_number( stmt:finalize() ) end --[===[ function st:test_questionmark_multi() local stmt = assert_userdata( self.db:prepare([[ INSERT INTO test VALUES (?, ?); INSERT INTO test VALUES (?, ?) ]])) assert( stmt:bind_values(5, "Foo Bar", 4, "Good morning") ) assert_number( stmt:step() ) assert_number( stmt:reset() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } assert_number( stmt:finalize() ) end ]===] function st:test_identifiers() local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, :name)") ) assert_number( stmt:bind_values(4, "Good morning") ) assert_number( stmt:step() ) assert_number( stmt:reset() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } assert_number( stmt:bind_values(5, "Foo Bar") ) assert_number( stmt:step() ) assert_number( stmt:reset() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } assert_number( stmt:finalize() ) end --[===[ function st:test_identifiers_multi() local stmt = assert_table( self.db:prepare([[ INSERT INTO test VALUES (:id1, :name1); INSERT INTO test VALUES (:id2, :name2) ]])) assert( stmt:bind_values(5, "Foo Bar", 4, "Good morning") ) assert( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } end ]===] function st:test_identifiers_names() --local stmt = assert_userdata( self.db:prepare({"name", "id"}, "INSERT INTO test VALUES (:id, $name)") ) local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, $name)") ) assert_number( stmt:bind_names({name="Good morning", id=4}) ) assert_number( stmt:step() ) assert_number( stmt:reset() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } assert_number( stmt:bind_names({name="Foo Bar", id=5}) ) assert_number( stmt:step() ) assert_number( stmt:reset() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } assert_number( stmt:finalize() ) end --[===[ function st:test_identifiers_multi_names() local stmt = assert_table( self.db:prepare( {"name", "id1", "id2"},[[ INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]])) assert( stmt:bind_values("Hoho", 4, 5) ) assert( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" } end ]===] function st:test_colon_identifiers_names() local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, :name)") ) assert_number( stmt:bind_names({name="Good morning", id=4}) ) assert_number( stmt:step() ) assert_number( stmt:reset() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } assert_number( stmt:bind_names({name="Foo Bar", id=5}) ) assert_number( stmt:step() ) assert_number( stmt:reset() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } assert_number( stmt:finalize() ) end --[===[ function st:test_colon_identifiers_multi_names() local stmt = assert_table( self.db:prepare( {":name", ":id1", ":id2"},[[ INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]])) assert( stmt:bind_values("Hoho", 4, 5) ) assert( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" } end function st:test_dollar_identifiers_names() local stmt = assert_table( self.db:prepare({"$name", "$id"}, "INSERT INTO test VALUES (:id, $name)") ) assert_table( stmt:bind_values("Good morning", 4) ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning" } assert_table( stmt:bind_values("Foo Bar", 5) ) assert_table( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Good morning", "Foo Bar" } end function st:test_dollar_identifiers_multi_names() local stmt = assert_table( self.db:prepare( {"$name", "$id1", "$id2"},[[ INSERT INTO test VALUES (:id1, $name); INSERT INTO test VALUES ($id2, :name) ]])) assert( stmt:bind_values("Hoho", 4, 5) ) assert( stmt:exec() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hoho", "Hoho" } end ]===] function st:test_bind_by_names() local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES (:id, :name)") ) local args = { } args.id = 5 args.name = "Hello girls" assert( stmt:bind_names(args) ) assert_number( stmt:step() ) assert_number( stmt:reset() ) args.id = 4 args.name = "Hello boys" assert( stmt:bind_names(args) ) assert_number( stmt:step() ) assert_number( stmt:reset() ) self:check_content{ "Hello World", "Hello Lua", "Hello sqlite3", "Hello boys", "Hello girls" } assert_number( stmt:finalize() ) end -------------------------------- -- Tests binding of arguments -- -------------------------------- b = lunit.TestCase("Binding Tests") function b:setup() self.db = assert( sqlite3.open_memory() ) assert_number( self.db:exec("CREATE TABLE test (id, name, u, v, w, x, y, z)") ) end function b:teardown() assert_number( self.db:close() ) end function b:test_auto_parameter_names() local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES(:a, $b, :a2, :b2, $a, :b, $a3, $b3)") ) local parameters = assert_number( stmt:bind_parameter_count() ) assert_equal( 8, parameters ) assert_equal( ":a", stmt:bind_parameter_name(1) ) assert_equal( "$b", stmt:bind_parameter_name(2) ) assert_equal( ":a2", stmt:bind_parameter_name(3) ) assert_equal( ":b2", stmt:bind_parameter_name(4) ) assert_equal( "$a", stmt:bind_parameter_name(5) ) assert_equal( ":b", stmt:bind_parameter_name(6) ) assert_equal( "$a3", stmt:bind_parameter_name(7) ) assert_equal( "$b3", stmt:bind_parameter_name(8) ) end function b:test_auto_parameter_names() local stmt = assert_userdata( self.db:prepare("INSERT INTO test VALUES($a, $b, $a2, $b2, $a, $b, $a3, $b3)") ) local parameters = assert_number( stmt:bind_parameter_count() ) assert_equal( 6, parameters ) assert_equal( "$a", stmt:bind_parameter_name(1) ) assert_equal( "$b", stmt:bind_parameter_name(2) ) assert_equal( "$a2", stmt:bind_parameter_name(3) ) assert_equal( "$b2", stmt:bind_parameter_name(4) ) assert_equal( "$a3", stmt:bind_parameter_name(5) ) assert_equal( "$b3", stmt:bind_parameter_name(6) ) end function b:test_no_parameter_names_1() local stmt = assert_userdata( self.db:prepare([[ SELECT * FROM test ]])) local parameters = assert_number( stmt:bind_parameter_count() ) assert_equal( 0, (parameters) ) end function b:test_no_parameter_names_2() local stmt = assert_userdata( self.db:prepare([[ INSERT INTO test VALUES(?, ?, ?, ?, ?, ?, ?, ?) ]])) local parameters = assert_number( stmt:bind_parameter_count() ) assert_equal( 8, (parameters) ) assert_nil( stmt:bind_parameter_name(1) ) end -------------------------------------------- -- Tests loop break and statement reusage -- -------------------------------------------- ---------------------------- -- Test for bugs reported -- ---------------------------- bug = lunit.TestCase("Bug-Report Tests") function bug:setup() self.db = assert( sqlite3.open_memory() ) end function bug:teardown() assert_number( self.db:close() ) end --[===[ function bug:test_1() self.db:exec("CREATE TABLE test (id INTEGER PRIMARY KEY, value TEXT)") local query = assert_userdata( self.db:prepare("SELECT id FROM test WHERE value=?") ) assert_table ( query:bind_values("1") ) assert_nil ( query:first_cols() ) assert_table ( query:bind_values("2") ) assert_nil ( query:first_cols() ) end ]===] function bug:test_nils() -- appeared in lua-5.1 (holes in arrays) local function check(arg1, arg2, arg3, arg4, arg5) assert_equal(1, arg1) assert_equal(2, arg2) assert_nil(arg3) assert_equal(4, arg4) assert_nil(arg5) end self.db:create_function("test_nils", 5, function(arg1, arg2, arg3, arg4, arg5) check(arg1, arg2, arg3, arg4, arg5) end, {}) assert_number( self.db:exec([[ SELECT test_nils(1, 2, NULL, 4, NULL) ]]) ) for arg1, arg2, arg3, arg4, arg5 in self.db:urows([[ SELECT 1, 2, NULL, 4, NULL ]]) do check(arg1, arg2, arg3, arg4, arg5) end for row in self.db:rows([[ SELECT 1, 2, NULL, 4, NULL ]]) do assert_table( row ) check(row[1], row[2], row[3], row[4], row[5]) end end ---------------------------- -- Test for collation fun -- ---------------------------- colla = lunit.TestCase("Collation Tests") function colla:setup() local function collate(s1,s2) -- if p then print("collation callback: ",s1,s2) end s1=s1:lower() s2=s2:lower() if s1==s2 then return 0 elseif s1<s2 then return -1 else return 1 end end self.db = assert( sqlite3.open_memory() ) assert_nil(self.db:create_collation('CINSENS',collate)) self.db:exec[[ CREATE TABLE test(id INTEGER PRIMARY KEY,content COLLATE CINSENS); INSERT INTO test VALUES(NULL,'hello world'); INSERT INTO test VALUES(NULL,'Buenos dias'); INSERT INTO test VALUES(NULL,'HELLO WORLD'); INSERT INTO test VALUES(NULL,'Guten Tag'); INSERT INTO test VALUES(NULL,'HeLlO WoRlD'); INSERT INTO test VALUES(NULL,'Bye for now'); ]] end function colla:teardown() assert_number( self.db:close() ) end function colla:test() --for row in db:nrows('SELECT * FROM test') do -- print(row.id,row.content) --end local n = 0 for row in self.db:nrows('SELECT * FROM test WHERE content="hElLo wOrLd"') do -- print(row.id,row.content) assert_equal (row.content:lower(), "hello world") n = n + 1 end assert_equal (n, 3) end lunit.run()
mit
vizewang/skynet
test/testmongodb.lua
62
2661
local skynet = require "skynet" local mongo = require "mongo" local bson = require "bson" local host, db_name = ... function test_insert_without_index() local db = mongo.client({host = host}) db[db_name].testdb:dropIndex("*") db[db_name].testdb:drop() local ret = db[db_name].testdb:safe_insert({test_key = 1}); assert(ret and ret.n == 1) local ret = db[db_name].testdb:safe_insert({test_key = 1}); assert(ret and ret.n == 1) end function test_insert_with_index() local db = mongo.client({host = host}) db[db_name].testdb:dropIndex("*") db[db_name].testdb:drop() db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index"}) local ret = db[db_name].testdb:safe_insert({test_key = 1}) assert(ret and ret.n == 1) local ret = db[db_name].testdb:safe_insert({test_key = 1}) assert(ret and ret.n == 0) end function test_find_and_remove() local db = mongo.client({host = host}) db[db_name].testdb:dropIndex("*") db[db_name].testdb:drop() db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index"}) local ret = db[db_name].testdb:safe_insert({test_key = 1}) assert(ret and ret.n == 1) local ret = db[db_name].testdb:safe_insert({test_key = 2}) assert(ret and ret.n == 1) local ret = db[db_name].testdb:findOne({test_key = 1}) assert(ret and ret.test_key == 1) local ret = db[db_name].testdb:find({test_key = {['$gt'] = 0}}):sort({test_key = -1}):skip(1):limit(1) assert(ret:count() == 2) assert(ret:count(true) == 1) if ret:hasNext() then ret = ret:next() end assert(ret and ret.test_key == 1) db[db_name].testdb:delete({test_key = 1}) db[db_name].testdb:delete({test_key = 2}) local ret = db[db_name].testdb:findOne({test_key = 1}) assert(ret == nil) end function test_expire_index() local db = mongo.client({host = host}) db[db_name].testdb:dropIndex("*") db[db_name].testdb:drop() db[db_name].testdb:ensureIndex({test_key = 1}, {unique = true, name = "test_key_index", expireAfterSeconds = 1, }) db[db_name].testdb:ensureIndex({test_date = 1}, {expireAfterSeconds = 1, }) local ret = db[db_name].testdb:safe_insert({test_key = 1, test_date = bson.date(os.time())}) assert(ret and ret.n == 1) local ret = db[db_name].testdb:findOne({test_key = 1}) assert(ret and ret.test_key == 1) for i = 1, 1000 do skynet.sleep(11); local ret = db[db_name].testdb:findOne({test_key = 1}) if ret == nil then return end end assert(false, "test expire index failed"); end skynet.start(function() test_insert_without_index() test_insert_with_index() test_find_and_remove() test_expire_index() print("mongodb test finish."); end)
mit
Kosmos82/kosmosdarkstar
scripts/zones/Port_San_dOria/npcs/Comittie.lua
13
1146
----------------------------------- -- Area: Port San d'Oria -- NPC: Comittie -- Type: Standard NPC -- @zone: 232 -- @pos -6.570 -9.8 -147.952 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); 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
Kosmos82/kosmosdarkstar
scripts/globals/items/prized_crab_stewpot.lua
18
1979
----------------------------------------- -- ID: 5546 -- Item: Prized Crab Stewpot -- Food Effect: 4 Hrs, All Races ----------------------------------------- -- TODO: Group Effect -- HP +10% Cap 100 -- MP +20 -- Vitality +2 -- Agility +2 -- Mind +4 -- HP Recovered while healing +9 -- MP Recovered while healing +3 -- Defense 20% Cap 100 -- Evasion +7 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,14400,5546); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_FOOD_HPP, 10); target:addMod(MOD_FOOD_HP_CAP, 100); target:addMod(MOD_MP, 20); target:addMod(MOD_VIT, 2); target:addMod(MOD_AGI, 2); target:addMod(MOD_MND, 4); target:addMod(MOD_HPHEAL, 9); target:addMod(MOD_MPHEAL, 3); target:addMod(MOD_FOOD_DEFP, 20); target:addMod(MOD_FOOD_DEF_CAP, 100); target:addMod(MOD_EVA, 7); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_FOOD_HPP, 10); target:delMod(MOD_FOOD_HP_CAP, 100); target:delMod(MOD_MP, 20); target:delMod(MOD_VIT, 2); target:delMod(MOD_AGI, 2); target:delMod(MOD_MND, 4); target:delMod(MOD_HPHEAL, 9); target:delMod(MOD_MPHEAL, 3); target:delMod(MOD_FOOD_DEFP, 20); target:delMod(MOD_FOOD_DEF_CAP, 100); target:delMod(MOD_EVA, 7); end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/globals/items/slice_of_salted_hare.lua
18
1177
----------------------------------------- -- ID: 5737 -- Item: slice_of_salted_hare -- Food Effect: 30Min, All Races ----------------------------------------- -- HP 10 -- Strength 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5737); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 10); target:addMod(MOD_STR, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 10); target:delMod(MOD_STR, 1); end;
gpl-3.0
Basylle/wow-battle-res
BResAssist/StatusWindow.lua
1
5895
--------------------------------------------------------------------- local BREZ, Brez = ... local BrezStatusWindow = Brez:NewModule("BrezStatusWindow", "AceEvent-3.0") local AceGUI = LibStub("AceGUI-3.0") local roleTextures = "Interface\\LFGFrame\\UI-LFG-ICON-PORTRAITROLES" local roleTextureCoordinates = { TANK = {0, 19/64, 22/64, 41/64}, HEALER = {20/64, 39/64, 1/64, 20/64}, DAMAGER = {20/64, 39/64, 22/64, 41/64}, } --------------------------------------------------------------------- function BrezStatusWindow:OnEnable() Brez:Debug("Enable BrezStatusWindow module.", "Notification") self.ui = {} self.deadPlayers = {} self.ui.playerDisplayElements = {} self.ui.playerDisplayElementCount = 0 self.db = Brez.db self:RegisterMessage("Brez_ShowStatusWindow", "ShowWindow") self:RegisterMessage("Brez_CloseStatusWindow", "CloseWindow") self:RegisterMessage("Brez_UpdateCharges", "UpdateCharges") self:RegisterMessage("Brez_UpdateTimeUntilNextCharge", "UpdateCooldown") self:RegisterMessage("Brez_CharacterDead", "CharacterDead") self:RegisterMessage("Brez_CharacterRevived", "CharacterRevived") end --------------------------------------------------------------------- function BrezStatusWindow:ShowWindow(message, force) local profile = self.db.profile if (force or profile.showStatusWindow) and not self.ui.window then local window = AceGUI:Create("Window") window:SetTitle("Battle Res Assist") window:SetWidth(300) window:SetLayout("Flow") window:SetCallback("OnClose", function(widget) Brez:Debug(Brez:Colorize("Window:OnClose", "ff00ff00"), "Notification") AceGUI:Release(widget) BrezStatusWindow.ui.chargesLabel = nil BrezStatusWindow.ui.cooldownLabel = nil BrezStatusWindow.ui.window = nil end) local icon = AceGUI:Create("Icon") icon:SetImageSize(24, 24) icon:SetImage(profile.icon) window:AddChild(icon) local chargesLabel = AceGUI:Create("Label") chargesLabel:SetJustifyV("MIDDLE") chargesLabel:SetFontObject(GameFontHighlightLarge) chargesLabel:SetWidth(50) chargesLabel:SetText("0") window:AddChild(chargesLabel) local cooldownLabel = AceGUI:Create("Label") cooldownLabel:SetJustifyV("MIDDLE") cooldownLabel:SetFontObject(GameFontHighlightLarge) cooldownLabel:SetWidth(100) cooldownLabel:SetText("0:00") window:AddChild(cooldownLabel) self.ui.window = window self.ui.chargesLabel = chargesLabel self.ui.cooldownLabel = cooldownLabel end end function BrezStatusWindow:CloseWindow() if self.ui.window then self.ui.window:Hide() self.ui.chargesLabel = nil self.ui.cooldownLabel = nil self.ui.window = nil end end --------------------------------------------------------------------- function BrezStatusWindow:UpdateCharges(_, value) if self.ui.chargesLabel then if value then self.ui.chargesLabel:SetText(tostring(value)) else self.ui.chargesLabel:SetText("n/a") end end end function BrezStatusWindow:UpdateCooldown(_, value) if self.ui.cooldownLabel then if value then local minutes = math.floor(value / 60) local seconds = value % 60 self.ui.cooldownLabel:SetText(format("%02d:%02d", minutes, seconds)) else self.ui.cooldownLabel:SetText("") end end end --------------------------------------------------------------------- function BrezStatusWindow:CharacterDead(_, id, name, role) Brez:Debug(Brez:Colorize(format("%s, %s, %s", id, name, role), "ffff0000"), "Received Character Dead Message") local playerData = {} playerData.id = id playerData.name = name playerData.role = role self.deadPlayers[name] = playerData self:RefreshDeadPlayers() end function BrezStatusWindow:CharacterRevived(_, id, name) Brez:Debug(Brez:Colorize(format("%s, %s", id, name), "ff00ff00"), "Received Character Revived Message") local playerData = self.deadPlayers[name] if playerData ~= nil then self.deadPlayers[name] = nil end self:RefreshDeadPlayers() end function BrezStatusWindow:RefreshDeadPlayers() local i = 1 for k, v in pairs(self.deadPlayers) do local ui = self:GetUIForDeadPlayer(i) if v.role ~= "NONE" then local coords = roleTextureCoordinates[v.role] ui.roleIcon:SetImage(roleTextures, coords[1], coords[2], coords[3], coords[4]) end ui.label:SetText(v.name) ui.group:DoLayout() i = i + 1 end while i <= self.ui.playerDisplayElementCount do local ui = self:GetUIForDeadPlayer(i) if ui ~= nil then ui.roleIcon:SetImage(nil) ui.label:SetText("") end i = i + 1 end end function BrezStatusWindow:GetUIForDeadPlayer(index) local ui = self.ui.playerDisplayElements[index] if ui == nil then ui = self:CreateUIForDeadPlayer(index) end return ui end function BrezStatusWindow:CreateUIForDeadPlayer(index) local ui = {} ui.group = AceGUI:Create("SimpleGroup") ui.group:SetLayout("Flow") ui.roleIcon = AceGUI:Create("Icon") ui.roleIcon:SetImageSize(24, 24) ui.group:AddChild(ui.roleIcon) ui.label = AceGUI:Create("Label") ui.label:SetJustifyV("TOP") ui.label:SetFontObject(GameFontHighlightLarge) ui.label:SetWidth(150) ui.group:AddChild(ui.label) self.ui.playerDisplayElements[index] = ui self.ui.playerDisplayElementCount = index self.ui.window:AddChild(ui.group) return ui end ---------------------------------------------------------------------
mit
harveyhu2012/luci
modules/base/luasrc/controller/admin/servicectl.lua
76
1376
--[[ 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$ ]]-- module("luci.controller.admin.servicectl", package.seeall) function index() entry({"servicectl"}, alias("servicectl", "status")).sysauth = "root" entry({"servicectl", "status"}, call("action_status")).leaf = true entry({"servicectl", "restart"}, call("action_restart")).leaf = true end function action_status() local data = nixio.fs.readfile("/var/run/luci-reload-status") if data then luci.http.write("/etc/config/") luci.http.write(data) else luci.http.write("finish") end end function action_restart(args) local uci = require "luci.model.uci".cursor() if args then local service local services = { } for service in args:gmatch("[%w_-]+") do services[#services+1] = service end local command = uci:apply(services, true) if nixio.fork() == 0 then local i = nixio.open("/dev/null", "r") local o = nixio.open("/dev/null", "w") nixio.dup(i, nixio.stdin) nixio.dup(o, nixio.stdout) i:close() o:close() nixio.exec("/bin/sh", unpack(command)) else luci.http.write("OK") os.exit(0) end end end
apache-2.0
Kosmos82/kosmosdarkstar
scripts/zones/Aht_Urhgan_Whitegate/npcs/Lageegee.lua
13
3616
----------------------------------- -- Area: Aht Urhgan Whitegate -- NPC: Lageegee -- Type: Assault Mission Giver -- @pos 120.808 0.161 -30.435 ----------------------------------- package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs"); require("scripts/globals/besieged"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local rank = getMercenaryRank(player); local haveimperialIDtag; local assaultPoints = player:getAssaultPoint(PERIQIA_ASSAULT_POINT); if (player:hasKeyItem(IMPERIAL_ARMY_ID_TAG)) then haveimperialIDtag = 1; else haveimperialIDtag = 0; end --[[ if (rank > 0) then player:startEvent(276,rank,haveimperialIDtag,assaultPoints,player:getCurrentAssault()); else]] player:startEvent(282); -- no rank --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 == 276) then local selectiontype = bit.band(option, 0xF); if (selectiontype == 1) then -- taken assault mission player:addAssault(bit.rshift(option,4)); player:delKeyItem(IMPERIAL_ARMY_ID_TAG); player:addKeyItem(PERIQIA_ASSAULT_ORDERS); player:messageSpecial(KEYITEM_OBTAINED,PERIQIA_ASSAULT_ORDERS); elseif (selectiontype == 2) then -- purchased an item local item = bit.rshift(option,14); local itemID = 0; local price = 0; -- Copy/pasted from Famad, TODO: fill in the actual IDs/prices for Lageegee --[[if (item == 1) then itemID = 15972; price = 3000; elseif (item == 2) then itemID = 15777; price = 5000; elseif (item == 3) then itemID = 15523; price = 8000; elseif (item == 4) then itemID = 15886; price = 10000; elseif (item == 5) then itemID = 15492; price = 10000; elseif (item == 6) then itemID = 18583; price = 10000; elseif (item == 7) then itemID = 18388; price = 15000; elseif (item == 8) then itemID = 18417; price = 15000; elseif (item == 9) then itemID = 14940; price = 15000; elseif (item == 10) then itemID = 15690; price = 20000; elseif (item == 11) then itemID = 14525; price = 20000; else return; end player:addItem(itemID); player:messageSpecial(ITEM_OBTAINED,itemID); player:delAssaultPoint(LEBROS_ASSAULT_POINT,price);]] end end end;
gpl-3.0
harveyhu2012/luci
applications/luci-statistics/luasrc/model/cbi/luci_statistics/netlink.lua
78
2765
--[[ Luci configuration model for statistics - collectd netlink plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- require("luci.sys") local devices = luci.sys.net.devices() m = Map("luci_statistics", translate("Netlink Plugin Configuration"), translate( "The netlink plugin collects extended informations like " .. "qdisc-, class- and filter-statistics for selected interfaces." )) -- collectd_netlink config section s = m:section( NamedSection, "collectd_netlink", "luci_statistics" ) -- collectd_netlink.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_netlink.interfaces (Interface) interfaces = s:option( MultiValue, "Interfaces", translate("Basic monitoring") ) interfaces.widget = "select" interfaces.optional = true interfaces.size = #devices + 1 interfaces:depends( "enable", 1 ) interfaces:value("") for i, v in ipairs(devices) do interfaces:value(v) end -- collectd_netlink.verboseinterfaces (VerboseInterface) verboseinterfaces = s:option( MultiValue, "VerboseInterfaces", translate("Verbose monitoring") ) verboseinterfaces.widget = "select" verboseinterfaces.optional = true verboseinterfaces.size = #devices + 1 verboseinterfaces:depends( "enable", 1 ) verboseinterfaces:value("") for i, v in ipairs(devices) do verboseinterfaces:value(v) end -- collectd_netlink.qdiscs (QDisc) qdiscs = s:option( MultiValue, "QDiscs", translate("Qdisc monitoring") ) qdiscs.widget = "select" qdiscs.optional = true qdiscs.size = #devices + 1 qdiscs:depends( "enable", 1 ) qdiscs:value("") for i, v in ipairs(devices) do qdiscs:value(v) end -- collectd_netlink.classes (Class) classes = s:option( MultiValue, "Classes", translate("Shaping class monitoring") ) classes.widget = "select" classes.optional = true classes.size = #devices + 1 classes:depends( "enable", 1 ) classes:value("") for i, v in ipairs(devices) do classes:value(v) end -- collectd_netlink.filters (Filter) filters = s:option( MultiValue, "Filters", translate("Filter class monitoring") ) filters.widget = "select" filters.optional = true filters.size = #devices + 1 filters:depends( "enable", 1 ) filters:value("") for i, v in ipairs(devices) do filters:value(v) end -- collectd_netlink.ignoreselected (IgnoreSelected) ignoreselected = s:option( Flag, "IgnoreSelected", translate("Monitor all except specified") ) ignoreselected.default = 0 ignoreselected:depends( "enable", 1 ) return m
apache-2.0
Kosmos82/kosmosdarkstar
scripts/globals/mobskills/Trinary_Tap.lua
32
2010
--------------------------------------------------- -- Trinary Tap -- Attempts to absorb three buffs from a single target, or otherwise steals HP. -- Type: Magical -- Utsusemi/Blink absorb: Ignores Shadows -- Range: Melee -- Notes: Can be any (positive) buff, including food. Will drain about 100HP if it can't take any buffs --------------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:isMobType(MOBTYPE_NOTORIOUS)) then return 0; end return 1; end; function onMobWeaponSkill(target, mob, skill) -- try to drain buff local effect1 = target:stealStatusEffect(); local effect2 = target:stealStatusEffect(); local effect3 = target:stealStatusEffect(); local dmg = 0; if (effect1 ~= nil) then local count = 1; -- add to myself mob:addStatusEffect(effect1:getType(), effect1:getPower(), effect1:getTickCount(), effect1:getDuration()); if (effect2 ~= nil) then count = count + 1; -- add to myself mob:addStatusEffect(effect2:getType(), effect2:getPower(), effect2:getTickCount(), effect2:getDuration()); end if (effect3 ~= nil) then count = count + 1; -- add to myself mob:addStatusEffect(effect3:getType(), effect3:getPower(), effect3:getTickCount(), effect3:getDuration()); end -- add buff to myself skill:setMsg(MSG_EFFECT_DRAINED); return count; else -- time to drain HP. 150-300 local power = math.random(0, 151) + 150; dmg = MobFinalAdjustments(power,mob,skill,target,MOBSKILL_MAGICAL,MOBPARAM_DARK,MOBPARAM_IGNORE_SHADOWS); skill:setMsg(MobPhysicalDrainMove(mob, target, skill, MOBDRAIN_HP, dmg)); return dmg; end end;
gpl-3.0
Igalia/snabb
lib/ljsyscall/syscall/linux/constants.lua
4
86434
-- tables of constants local require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string = require, error, assert, tonumber, tostring, setmetatable, pairs, ipairs, unpack, rawget, rawset, pcall, type, table, string local abi = require "syscall.abi" local bit = require "syscall.bit" local tobit = bit.tobit local arch = require("syscall.linux." .. abi.arch .. ".constants") -- architecture specific code local h = require "syscall.helpers" local octal, multiflags, charflags, swapflags, strflag, atflag, modeflags = h.octal, h.multiflags, h.charflags, h.swapflags, h.strflag, h.atflag, h.modeflags local function addarch(tb, a, default) local add = a or default for k, v in pairs(add) do tb[k] = v end end local c = {} c.errornames = require "syscall.linux.errors" c.REG = arch.REG -- TODO only define one of these c.STD = strflag { IN_FILENO = 0, OUT_FILENO = 1, ERR_FILENO = 2, IN = 0, OUT = 1, ERR = 2, } -- sizes c.PATH_MAX = 4096 -- open, fcntl TODO not setting largefile if matches exactly in upper case, potentially confusing c.O = multiflags(arch.O or { RDONLY = octal('0000'), WRONLY = octal('0001'), RDWR = octal('0002'), ACCMODE = octal('0003'), CREAT = octal('0100'), EXCL = octal('0200'), NOCTTY = octal('0400'), TRUNC = octal('01000'), APPEND = octal('02000'), NONBLOCK = octal('04000'), DSYNC = octal('010000'), ASYNC = octal('020000'), DIRECT = octal('040000'), DIRECTORY = octal('0200000'), NOFOLLOW = octal('0400000'), NOATIME = octal('01000000'), CLOEXEC = octal('02000000'), SYNC = octal('04010000'), }) c.O.FSYNC = c.O.SYNC c.O.RSYNC = c.O.SYNC c.O.NDELAY = c.O.NONBLOCK if not c.O.LARGEFILE then -- also can be arch dependent if abi.abi32 then c.O.LARGEFILE = octal('0100000') else c.O.LARGEFILE = 0 end end -- just for pipe2 c.OPIPE = multiflags { NONBLOCK = c.O.NONBLOCK, CLOEXEC = c.O.CLOEXEC, DIRECT = c.O.DIRECT, } -- for mq_attr NONBLOCK only flag allowed c.OMQATTR = multiflags { NONBLOCK = c.O.NONBLOCK, } -- modes and file types. note renamed second set from S_ to MODE_ but duplicated in S for stat c.S_I = modeflags { FMT = octal('0170000'), FSOCK = octal('0140000'), FLNK = octal('0120000'), FREG = octal('0100000'), FBLK = octal('0060000'), FDIR = octal('0040000'), FCHR = octal('0020000'), FIFO = octal('0010000'), SUID = octal('0004000'), SGID = octal('0002000'), SVTX = octal('0001000'), RWXU = octal('00700'), RUSR = octal('00400'), WUSR = octal('00200'), XUSR = octal('00100'), RWXG = octal('00070'), RGRP = octal('00040'), WGRP = octal('00020'), XGRP = octal('00010'), RWXO = octal('00007'), ROTH = octal('00004'), WOTH = octal('00002'), XOTH = octal('00001'), } c.MODE = modeflags { SUID = octal('04000'), SGID = octal('02000'), SVTX = octal('01000'), RWXU = octal('00700'), RUSR = octal('00400'), WUSR = octal('00200'), XUSR = octal('00100'), RWXG = octal('00070'), RGRP = octal('00040'), WGRP = octal('00020'), XGRP = octal('00010'), RWXO = octal('00007'), ROTH = octal('00004'), WOTH = octal('00002'), XOTH = octal('00001'), } -- access c.OK = charflags { R = 4, W = 2, X = 1, F = 0, } -- fcntl c.F = strflag(arch.F or { DUPFD = 0, GETFD = 1, SETFD = 2, GETFL = 3, SETFL = 4, GETLK = 5, SETLK = 6, SETLKW = 7, SETOWN = 8, GETOWN = 9, SETSIG = 10, GETSIG = 11, GETLK64 = 12, SETLK64 = 13, SETLKW64 = 14, SETOWN_EX = 15, GETOWN_EX = 16, SETLEASE = 1024, GETLEASE = 1025, NOTIFY = 1026, CANCELLK = 1029, DUPFD_CLOEXEC = 1030, SETPIPE_SZ = 1031, GETPIPE_SZ = 1032, ADD_SEALS = 1033, GET_SEALS = 1034, }) -- messy if abi.abi64 then c.F.GETLK64 = c.F.GETLK c.F.SETLK64 = c.F.SETLK c.F.SETLKW64 = c.F.SETLKW else c.F.GETLK = c.F.GETLK64 c.F.SETLK = c.F.SETLK64 c.F.SETLKW = c.F.SETLKW64 end c.FD = multiflags { CLOEXEC = 1, } -- note changed from F_ to FCNTL_LOCK c.FCNTL_LOCK = strflag { RDLCK = 0, WRLCK = 1, UNLCK = 2, } -- lockf, changed from F_ to LOCKF_ c.LOCKF = strflag { ULOCK = 0, LOCK = 1, TLOCK = 2, TEST = 3, } -- for flock (2) c.LOCK = multiflags { SH = 1, EX = 2, NB = 4, UN = 8, MAND = 32, READ = 64, WRITE = 128, RW = 192, } -- for memfd c.F_SEAL = multiflags { SEAL = 0x0001, SHRINK = 0x0002, GROW = 0x0004, WRITE = 0x0008, } --mmap c.PROT = multiflags { NONE = 0x0, READ = 0x1, WRITE = 0x2, EXEC = 0x4, GROWSDOWN = 0x01000000, GROWSUP = 0x02000000, } addarch(c.PROT, arch.PROT, {}) -- Sharing types c.MAP = multiflags(arch.MAP or { FILE = 0, SHARED = 0x01, PRIVATE = 0x02, TYPE = 0x0f, FIXED = 0x10, ANONYMOUS = 0x20, GROWSDOWN = 0x00100, DENYWRITE = 0x00800, EXECUTABLE = 0x01000, LOCKED = 0x02000, NORESERVE = 0x04000, POPULATE = 0x08000, NONBLOCK = 0x10000, STACK = 0x20000, HUGETLB = 0x40000, }) if abi.abi64 then c.MAP["32BIT"] = 0x40 end c.MAP.ANON = c.MAP.ANONYMOUS -- flags for `mlockall'. c.MCL = strflag (arch.MCL or { CURRENT = 1, FUTURE = 2, }) -- flags for `mremap'. c.MREMAP = multiflags { MAYMOVE = 1, FIXED = 2, } -- madvise advice parameter c.MADV = strflag { NORMAL = 0, RANDOM = 1, SEQUENTIAL = 2, WILLNEED = 3, DONTNEED = 4, REMOVE = 9, DONTFORK = 10, DOFORK = 11, MERGEABLE = 12, UNMERGEABLE = 13, HUGEPAGE = 14, NOHUGEPAGE = 15, HWPOISON = 100, } -- posix fadvise c.POSIX_FADV = strflag { NORMAL = 0, RANDOM = 1, SEQUENTIAL = 2, WILLNEED = 3, DONTNEED = 4, NOREUSE = 5, } -- fallocate c.FALLOC_FL = strflag { KEEP_SIZE = 0x01, PUNCH_HOLE = 0x02, } -- getpriority, setpriority flags c.PRIO = strflag { PROCESS = 0, PGRP = 1, USER = 2, } -- lseek c.SEEK = strflag { SET = 0, CUR = 1, END = 2, DATA = 3, HOLE = 4, } -- exit c.EXIT = strflag { SUCCESS = 0, FAILURE = 1, } -- sigaction, note renamed SIGACT from SIG_ c.SIGACT = strflag { ERR = -1, DFL = 0, IGN = 1, HOLD = 2, } c.SIGEV = strflag { SIGNAL = 0, NONE = 1, THREAD = 2, THREAD_ID = 4, } c.SIG = strflag(arch.SIG or { HUP = 1, INT = 2, QUIT = 3, ILL = 4, TRAP = 5, ABRT = 6, BUS = 7, FPE = 8, KILL = 9, USR1 = 10, SEGV = 11, USR2 = 12, PIPE = 13, ALRM = 14, TERM = 15, STKFLT = 16, CHLD = 17, CONT = 18, STOP = 19, TSTP = 20, TTIN = 21, TTOU = 22, URG = 23, XCPU = 24, XFSZ = 25, VTALRM = 26, PROF = 27, WINCH = 28, IO = 29, PWR = 30, SYS = 31, }) c.SIG.IOT = c.SIG.ABRT --c.SIG.UNUSED = 31 -- TODO this looks arch dependent c.SIG.CLD = c.SIG.CHLD c.SIG.POLL = c.SIG.IO -- sigprocmask note renaming of SIG to SIGPM c.SIGPM = strflag(arch.SIGPM or { BLOCK = 0, UNBLOCK = 1, SETMASK = 2, }) -- signalfd c.SFD = multiflags(arch.SFD or { CLOEXEC = octal('02000000'), NONBLOCK = octal('04000'), }) -- sockets note mix of single and multiple flags TODO code to handle temporarily using multi which is kind of ok c.SOCK = multiflags(arch.SOCK or { STREAM = 1, DGRAM = 2, RAW = 3, RDM = 4, SEQPACKET = 5, DCCP = 6, PACKET = 10, CLOEXEC = octal('02000000'), NONBLOCK = octal('04000'), }) -- misc socket constants c.SCM = strflag { RIGHTS = 0x01, CREDENTIALS = 0x02, TSTAMP_SND = 0, TSTAMP_SCHED = 1, TSTAMP_ACK = 2, TIMESTAMPING_OPT_STATS = 54, } -- setsockopt c.SOL = strflag { IP = 0, IPV6 = 41, ICMPV6 = 58, RAW = 255, DECNET = 261, X25 = 262, PACKET = 263, ATM = 264, AAL = 265, IRDA = 266, XDP = 283 } if arch.SOLSOCKET then c.SOL.SOCKET = arch.SOLSOCKET else c.SOL.SOCKET = 1 end c.SO = strflag(arch.SO or { DEBUG = 1, REUSEADDR = 2, TYPE = 3, ERROR = 4, DONTROUTE = 5, BROADCAST = 6, SNDBUF = 7, RCVBUF = 8, KEEPALIVE = 9, OOBINLINE = 10, NO_CHECK = 11, PRIORITY = 12, LINGER = 13, BSDCOMPAT = 14, REUSEPORT = 15, -- new, may not be defined yet PASSCRED = 16, PEERCRED = 17, RCVLOWAT = 18, SNDLOWAT = 19, RCVTIMEO = 20, SNDTIMEO = 21, SECURITY_AUTHENTICATION = 22, SECURITY_ENCRYPTION_TRANSPORT = 23, SECURITY_ENCRYPTION_NETWORK = 24, BINDTODEVICE = 25, ATTACH_FILTER = 26, DETACH_FILTER = 27, PEERNAME = 28, TIMESTAMP = 29, ACCEPTCONN = 30, PEERSEC = 31, SNDBUFFORCE = 32, RCVBUFFORCE = 33, PASSSEC = 34, TIMESTAMPNS = 35, MARK = 36, TIMESTAMPING = 37, PROTOCOL = 38, DOMAIN = 39, RXQ_OVFL = 40, WIFI_STATUS = 41, PEEK_OFF = 42, NOFCS = 43, LOCK_FILTER = 44, SELECT_ERR_QUEUE = 45, BUSY_POLL = 46, MAX_PACING_RATE = 47, BPF_EXTENSIONS = 48, INCOMING_CPU = 49, ATTACH_BPF = 50, ATTACH_REUSEPORT_CBPF = 51, ATTACH_REUSEPORT_EBPF = 52, XDP_MMAP_OFFSETS = 1, XDP_RX_RING = 2, XDP_TX_RING = 3, XDP_UMEM_REG = 4, XDP_UMEM_FILL_RING = 5, XDP_UMEM_COMPLETION_RING = 6, XDP_STATISTICS = 7, XDP_OPTIONS = 8 }) c.SO.GET_FILTER = c.SO.ATTACH_FILTER c.SO.DETACH_BPF = c.SO.DETACH_FILTER c.SCM.TIMESTAMP = c.SO.TIMESTAMP c.SCM.TIMESTAMPNS = c.SO.TIMESTAMPNS c.SCM.TIMESTAMPING = c.SO.TIMESTAMPING -- Maximum queue length specifiable by listen. c.SOMAXCONN = 128 c.SOF = strflag { TIMESTAMPING_TX_HARDWARE = bit.lshift(1, 0), TIMESTAMPING_TX_SOFTWARE = bit.lshift(1, 1), TIMESTAMPING_RX_HARDWARE = bit.lshift(1, 2), TIMESTAMPING_RX_SOFTWARE = bit.lshift(1, 3), TIMESTAMPING_SOFTWARE = bit.lshift(1, 4), TIMESTAMPING_SYS_HARDWARE = bit.lshift(1, 5), TIMESTAMPING_RAW_HARDWARE = bit.lshift(1, 6), TIMESTAMPING_OPT_ID = bit.lshift(1, 7), TIMESTAMPING_TX_SCHED = bit.lshift(1, 8), TIMESTAMPING_TX_ACK = bit.lshift(1, 9), TIMESTAMPING_OPT_CMSG = bit.lshift(1, 10), TIMESTAMPING_OPT_TSONLY = bit.lshift(1, 11), TIMESTAMPING_OPT_STATS = bit.lshift(1, 12), TIMESTAMPING_OPT_PKTINFO = bit.lshift(1, 13), TIMESTAMPING_OPT_TX_SWHW = bit.lshift(1, 14), } c.SOF.TIMESTAMPING_LAST = c.SOF.TIMESTAMPING_OPT_TX_SWHW c.SOF.TIMESTAMPING_MASK = bit.bor(c.SOF.TIMESTAMPING_LAST - 1, c.SOF.TIMESTAMPING_LAST) -- shutdown c.SHUT = strflag { RD = 0, WR = 1, RDWR = 2, } -- waitpid 3rd arg c.W = multiflags { NOHANG = 1, UNTRACED = 2, EXITED = 4, CONTINUED = 8, NOWAIT = 0x01000000, NOTHREAD = 0x20000000, -- __WNOTHREAD ALL = 0x40000000, -- __WALL CLONE = 0x80000000, -- __WCLONE } c.W.STOPPED = c.W.UNTRACED -- waitid c.P = strflag{ ALL = 0, PID = 1, PGID = 2, } -- struct siginfo, eg waitid c.SI = strflag(arch.SI or { ASYNCNL = -60, TKILL = -6, SIGIO = -5, ASYNCIO = -4, MESGQ = -3, TIMER = -2, QUEUE = -1, USER = 0, KERNEL = 0x80, }) -- note renamed ILL to SIGILL etc as POLL clashes c.SIGILL = strflag { ILLOPC = 1, ILLOPN = 2, ILLADR = 3, ILLTRP = 4, PRVOPC = 5, PRVREG = 6, COPROC = 7, BADSTK = 8, } c.SIGFPE = strflag { INTDIV = 1, INTOVF = 2, FLTDIV = 3, FLTOVF = 4, FLTUND = 5, FLTRES = 6, FLTINV = 7, FLTSUB = 8, } c.SIGSEGV = strflag { MAPERR = 1, ACCERR = 2, } c.SIGBUS = strflag { ADRALN = 1, ADRERR = 2, OBJERR = 3, } c.SIGTRAP = strflag { BRKPT = 1, TRACE = 2, } c.SIGCLD = strflag { EXITED = 1, KILLED = 2, DUMPED = 3, TRAPPED = 4, STOPPED = 5, CONTINUED = 6, } c.SIGPOLL = strflag { IN = 1, OUT = 2, MSG = 3, ERR = 4, PRI = 5, HUP = 6, } -- sigaction -- note not cast to (void *)(int) as we do not know type here c.SA = multiflags(arch.SA or { NOCLDSTOP = 0x00000001, NOCLDWAIT = 0x00000002, SIGINFO = 0x00000004, ONSTACK = 0x08000000, RESTART = 0x10000000, NODEFER = 0x40000000, RESETHAND = 0x80000000, RESTORER = 0x04000000, }) c.SA.NOMASK = c.SA.NODEFER c.SA.ONESHOT = c.SA.RESETHAND -- timers c.ITIMER = strflag { REAL = 0, VIRTUAL = 1, PROF = 2, } -- clocks c.CLOCK = strflag { REALTIME = 0, MONOTONIC = 1, PROCESS_CPUTIME_ID = 2, THREAD_CPUTIME_ID = 3, MONOTONIC_RAW = 4, REALTIME_COARSE = 5, MONOTONIC_COARSE = 6, } c.TIMER = strflag { ABSTIME = 1, } -- adjtimex c.ADJ = multiflags { OFFSET = 0x0001, FREQUENCY = 0x0002, MAXERROR = 0x0004, ESTERROR = 0x0008, STATUS = 0x0010, TIMECONST = 0x0020, TAI = 0x0080, MICRO = 0x1000, NANO = 0x2000, TICK = 0x4000, OFFSET_SINGLESHOT = 0x8001, OFFSET_SS_READ = 0xa001, } c.STA = multiflags { PLL = 0x0001, PPSFREQ = 0x0002, PPSTIME = 0x0004, FLL = 0x0008, INS = 0x0010, DEL = 0x0020, UNSYNC = 0x0040, FREQHOLD = 0x0080, PPSSIGNAL = 0x0100, PPSJITTER = 0x0200, PPSWANDER = 0x0400, PPSERROR = 0x0800, CLOCKERR = 0x1000, NANO = 0x2000, MODE = 0x4000, CLK = 0x8000, } -- return values for adjtimex c.TIME = strflag { OK = 0, INS = 1, DEL = 2, OOP = 3, WAIT = 4, ERROR = 5, } c.TIME.BAD = c.TIME.ERROR -- xattr; defined as multi as 0 is default, even though both flags makes no sense c.XATTR = multiflags { CREATE = 1, REPLACE = 2, } -- utime c.UTIME = strflag { NOW = bit.lshift(1, 30) - 1, OMIT = bit.lshift(1, 30) - 2, } c.AT_FDCWD = atflag { FDCWD = -100, } -- not all combinations valid c.AT = multiflags { SYMLINK_NOFOLLOW = 0x100, REMOVEDIR = 0x200, EACCESS = 0x200, SYMLINK_FOLLOW = 0x400, NO_AUTOMOUNT = 0x800, EMPTY_PATH = 0x1000, } -- send, recv etc c.MSG = multiflags { OOB = 0x01, PEEK = 0x02, DONTROUTE = 0x04, CTRUNC = 0x08, PROXY = 0x10, TRUNC = 0x20, DONTWAIT = 0x40, EOR = 0x80, WAITALL = 0x100, FIN = 0x200, SYN = 0x400, CONFIRM = 0x800, RST = 0x1000, ERRQUEUE = 0x2000, NOSIGNAL = 0x4000, MORE = 0x8000, WAITFORONE = 0x10000, CMSG_CLOEXEC = 0x40000000, } c.MSG.TRYHARD = c.MSG.DONTROUTE -- rlimit c.RLIMIT = strflag(arch.RLIMIT or { CPU = 0, FSIZE = 1, DATA = 2, STACK = 3, CORE = 4, RSS = 5, NPROC = 6, NOFILE = 7, MEMLOCK = 8, AS = 9, LOCKS = 10, SIGPENDING = 11, MSGQUEUE = 12, NICE = 13, RTPRIO = 14, RTTIME = 15, }) c.RLIMIT.OFILE = c.RLIMIT.NOFILE c.RLIM = strflag { INFINITY = h.uint64_max, } -- timerfd c.TFD = multiflags(arch.TFD or { CLOEXEC = octal("02000000"), NONBLOCK = octal("04000"), }) c.TFD_TIMER = strflag { ABSTIME = 1, CANCEL_ON_SET = 2, } -- poll c.POLL = multiflags(arch.POLL or { IN = 0x001, PRI = 0x002, OUT = 0x004, ERR = 0x008, HUP = 0x010, NVAL = 0x020, RDNORM = 0x040, RDBAND = 0x080, WRNORM = 0x100, WRBAND = 0x200, MSG = 0x400, REMOVE = 0x1000, RDHUP = 0x2000, }) -- epoll renamed from EPOLL_ to EPOLLCREATE c.EPOLLCREATE = multiflags { CLOEXEC = octal("02000000"), NONBLOCK = octal("04000"), } c.EPOLL = multiflags { IN = 0x001, PRI = 0x002, OUT = 0x004, RDNORM = 0x040, RDBAND = 0x080, WRNORM = 0x100, WRBAND = 0x200, MSG = 0x400, ERR = 0x008, HUP = 0x010, RDHUP = 0x2000, ONESHOT = bit.lshift(1, 30), ET = bit.lshift(1, 30) * 2, -- 2^31 but making sure no sign issue } c.EPOLL_CTL = strflag { ADD = 1, DEL = 2, MOD = 3, } -- splice etc c.SPLICE_F = multiflags { MOVE = 1, NONBLOCK = 2, MORE = 4, GIFT = 8, } -- aio - see /usr/include/linux/aio_abi.h c.IOCB_CMD = strflag { PREAD = 0, PWRITE = 1, FSYNC = 2, FDSYNC = 3, -- PREADX = 4, -- POLL = 5, NOOP = 6, PREADV = 7, PWRITEV = 8, } c.IOCB_FLAG = strflag { RESFD = 1, } -- file types in directory c.DT = strflag { UNKNOWN = 0, FIFO = 1, CHR = 2, DIR = 4, BLK = 6, REG = 8, LNK = 10, SOCK = 12, WHT = 14, } -- sync file range c.SYNC_FILE_RANGE = multiflags { WAIT_BEFORE = 1, WRITE = 2, WAIT_AFTER = 4, } -- netlink c.NETLINK = strflag { ROUTE = 0, UNUSED = 1, USERSOCK = 2, FIREWALL = 3, INET_DIAG = 4, NFLOG = 5, XFRM = 6, SELINUX = 7, ISCSI = 8, AUDIT = 9, FIB_LOOKUP = 10, CONNECTOR = 11, NETFILTER = 12, IP6_FW = 13, DNRTMSG = 14, KOBJECT_UEVENT= 15, GENERIC = 16, SCSITRANSPORT = 18, ECRYPTFS = 19, } -- see man netlink(7) for details. Note us of flags by context c.NLM_F = multiflags { REQUEST = 1, MULTI = 2, ACK = 4, ECHO = 8, -- for GET ROOT = 0x100, MATCH = 0x200, ATOMIC = 0x400, -- for NEW REPLACE = 0x100, EXCL = 0x200, CREATE = 0x400, APPEND = 0x800, } c.NLM_F.DUMP = bit.bor(c.NLM_F.ROOT, c.NLM_F.MATCH) -- generic types. These are part of same sequence as RTM c.NLMSG = strflag{ NOOP = 0x1, ERROR = 0x2, DONE = 0x3, OVERRUN = 0x4, } -- routing c.RTM = strflag { NEWLINK = 16, DELLINK = 17, GETLINK = 18, SETLINK = 19, NEWADDR = 20, DELADDR = 21, GETADDR = 22, NEWROUTE = 24, DELROUTE = 25, GETROUTE = 26, NEWNEIGH = 28, DELNEIGH = 29, GETNEIGH = 30, NEWRULE = 32, DELRULE = 33, GETRULE = 34, NEWQDISC = 36, DELQDISC = 37, GETQDISC = 38, NEWTCLASS = 40, DELTCLASS = 41, GETTCLASS = 42, NEWTFILTER = 44, DELTFILTER = 45, GETTFILTER = 46, NEWACTION = 48, DELACTION = 49, GETACTION = 50, NEWPREFIX = 52, GETMULTICAST = 58, GETANYCAST = 62, NEWNEIGHTBL = 64, GETNEIGHTBL = 66, SETNEIGHTBL = 67, NEWNDUSEROPT = 68, NEWADDRLABEL = 72, DELADDRLABEL = 73, GETADDRLABEL = 74, GETDCB = 78, SETDCB = 79, } -- linux/if_linc.h c.IFLA = strflag { UNSPEC = 0, ADDRESS = 1, BROADCAST = 2, IFNAME = 3, MTU = 4, LINK = 5, QDISC = 6, STATS = 7, COST = 8, PRIORITY = 9, MASTER = 10, WIRELESS = 11, PROTINFO = 12, TXQLEN = 13, MAP = 14, WEIGHT = 15, OPERSTATE = 16, LINKMODE = 17, LINKINFO = 18, NET_NS_PID= 19, IFALIAS = 20, NUM_VF = 21, VFINFO_LIST = 22, STATS64 = 23, VF_PORTS = 24, PORT_SELF = 25, AF_SPEC = 26, GROUP = 27, NET_NS_FD = 28, } c.IFLA_INET = strflag { UNSPEC = 0, CONF = 1, } c.IFLA_INET6 = strflag { UNSPEC = 0, FLAGS = 1, CONF = 2, STATS = 3, MCAST = 4, CACHEINFO = 5, ICMP6STATS = 6, } c.IFLA_INFO = strflag { UNSPEC = 0, KIND = 1, DATA = 2, XSTATS = 3, } c.IFLA_VLAN = strflag { UNSPEC = 0, ID = 1, FLAGS = 2, EGRESS_QOS = 3, INGRESS_QOS = 4, } c.IFLA_VLAN_QOS = strflag { UNSPEC = 0, MAPPING = 1, } c.IFLA_MACVLAN = strflag { UNSPEC = 0, MODE = 1, } c.MACVLAN_MODE = multiflags { PRIVATE = 1, VEPA = 2, BRIDGE = 4, PASSTHRU = 8, } c.IFLA_VF_INFO = strflag { UNSPEC = 0, INFO = 1, -- note renamed IFLA_VF_INFO to IFLA_VF_INFO.INFO } c.IFLA_VF = strflag { UNSPEC = 0, MAC = 1, VLAN = 2, TX_RATE = 3, SPOOFCHK = 4, } c.IFLA_VF_PORT = strflag { UNSPEC = 0, PORT = 1, -- note renamed from IFLA_VF_PORT to IFLA_VF_PORT.PORT? } c.IFLA_PORT = strflag { UNSPEC = 0, VF = 1, PROFILE = 2, VSI_TYPE = 3, INSTANCE_UUID = 4, HOST_UUID = 5, REQUEST = 6, RESPONSE = 7, } c.VETH_INFO = strflag { UNSPEC = 0, PEER = 1, } c.PORT = strflag { PROFILE_MAX = 40, UUID_MAX = 16, SELF_VF = -1, } c.PORT_REQUEST = strflag { PREASSOCIATE = 0, PREASSOCIATE_RR = 1, ASSOCIATE = 2, DISASSOCIATE = 3, } c.PORT_VDP_RESPONSE = strflag { SUCCESS = 0, INVALID_FORMAT = 1, INSUFFICIENT_RESOURCES = 2, UNUSED_VTID = 3, VTID_VIOLATION = 4, VTID_VERSION_VIOALTION = 5, -- seems to be misspelled in headers TODO fix OUT_OF_SYNC = 6, } c.PORT_PROFILE_RESPONSE = strflag { SUCCESS = 0x100, INPROGRESS = 0x101, INVALID = 0x102, BADSTATE = 0x103, INSUFFICIENT_RESOURCES = 0x104, ERROR = 0x105, } -- from if_addr.h interface address types and flags c.IFA = strflag { UNSPEC = 0, ADDRESS = 1, LOCAL = 2, LABEL = 3, BROADCAST = 4, ANYCAST = 5, CACHEINFO = 6, MULTICAST = 7, } c.IFA_F = multiflags { SECONDARY = 0x01, NODAD = 0x02, OPTIMISTIC = 0x04, DADFAILED = 0x08, HOMEADDRESS = 0x10, DEPRECATED = 0x20, TENTATIVE = 0x40, PERMANENT = 0x80, } c.IFA_F.TEMPORARY = c.IFA_F.SECONDARY -- routing c.RTN = strflag { UNSPEC = 0, UNICAST = 1, LOCAL = 2, BROADCAST = 3, ANYCAST = 4, MULTICAST = 5, BLACKHOLE = 6, UNREACHABLE = 7, PROHIBIT = 8, THROW = 9, NAT = 10, XRESOLVE = 11, } c.RTPROT = strflag { UNSPEC = 0, REDIRECT = 1, KERNEL = 2, BOOT = 3, STATIC = 4, GATED = 8, RA = 9, MRT = 10, ZEBRA = 11, BIRD = 12, DNROUTED = 13, XORP = 14, NTK = 15, DHCP = 16, } c.RT_SCOPE = strflag { UNIVERSE = 0, SITE = 200, LINK = 253, HOST = 254, NOWHERE = 255, } c.RTM_F = multiflags { NOTIFY = 0x100, CLONED = 0x200, EQUALIZE = 0x400, PREFIX = 0x800, } c.RT_TABLE = strflag { UNSPEC = 0, COMPAT = 252, DEFAULT = 253, MAIN = 254, LOCAL = 255, MAX = 0xFFFFFFFF, } c.RTA = strflag { UNSPEC = 0, DST = 1, SRC = 2, IIF = 3, OIF = 4, GATEWAY = 5, PRIORITY = 6, PREFSRC = 7, METRICS = 8, MULTIPATH = 9, PROTOINFO = 10, FLOW = 11, CACHEINFO = 12, SESSION = 13, MP_ALGO = 14, TABLE = 15, MARK = 16, MFC_STATS = 17, VIA = 18, NEWDST = 19, PREF = 20, } -- route flags c.RTF = multiflags { UP = 0x0001, GATEWAY = 0x0002, HOST = 0x0004, REINSTATE = 0x0008, DYNAMIC = 0x0010, MODIFIED = 0x0020, MTU = 0x0040, WINDOW = 0x0080, IRTT = 0x0100, REJECT = 0x0200, -- ipv6 route flags DEFAULT = 0x00010000, ALLONLINK = 0x00020000, ADDRCONF = 0x00040000, PREFIX_RT = 0x00080000, ANYCAST = 0x00100000, NONEXTHOP = 0x00200000, EXPIRES = 0x00400000, ROUTEINFO = 0x00800000, CACHE = 0x01000000, FLOW = 0x02000000, POLICY = 0x04000000, LOCAL = 0x80000000, } c.RTF.MSS = c.RTF.MTU --#define RTF_PREF(pref) ((pref) << 27) --#define RTF_PREF_MASK 0x18000000 -- interface flags c.IFF = multiflags { UP = 0x1, BROADCAST = 0x2, DEBUG = 0x4, LOOPBACK = 0x8, POINTOPOINT= 0x10, NOTRAILERS = 0x20, RUNNING = 0x40, NOARP = 0x80, PROMISC = 0x100, ALLMULTI = 0x200, MASTER = 0x400, SLAVE = 0x800, MULTICAST = 0x1000, PORTSEL = 0x2000, AUTOMEDIA = 0x4000, DYNAMIC = 0x8000, LOWER_UP = 0x10000, DORMANT = 0x20000, ECHO = 0x40000, } c.IFF.ALL = 0xffffffff c.IFF.NONE = bit.bnot(0x7ffff) -- this is a bit of a fudge as zero should work, but does not for historical reasons see net/core/rtnetlinc.c c.IFF.VOLATILE = c.IFF.LOOPBACK + c.IFF.POINTOPOINT + c.IFF.BROADCAST + c.IFF.ECHO + c.IFF.MASTER + c.IFF.SLAVE + c.IFF.RUNNING + c.IFF.LOWER_UP + c.IFF.DORMANT -- netlink multicast groups -- legacy names, which are masks. c.RTMGRP = multiflags { LINK = 1, NOTIFY = 2, NEIGH = 4, TC = 8, IPV4_IFADDR = 0x10, IPV4_MROUTE = 0x20, IPV4_ROUTE = 0x40, IPV4_RULE = 0x80, IPV6_IFADDR = 0x100, IPV6_MROUTE = 0x200, IPV6_ROUTE = 0x400, IPV6_IFINFO = 0x800, --DECNET_IFADDR = 0x1000, --DECNET_ROUTE = 0x4000, IPV6_PREFIX = 0x20000, } -- rtnetlink multicast groups (bit numbers not masks) c.RTNLGRP = strflag { NONE = 0, LINK = 1, NOTIFY = 2, NEIGH = 3, TC = 4, IPV4_IFADDR = 5, IPV4_MROUTE = 6, IPV4_ROUTE = 7, IPV4_RULE = 8, IPV6_IFADDR = 9, IPV6_MROUTE = 10, IPV6_ROUTE = 11, IPV6_IFINFO = 12, -- DECNET_IFADDR = 13, NOP2 = 14, -- DECNET_ROUTE = 15, -- DECNET_RULE = 16, NOP4 = 17, IPV6_PREFIX = 18, IPV6_RULE = 19, ND_USEROPT = 20, PHONET_IFADDR = 21, PHONET_ROUTE = 22, DCB = 23, } -- netlink neighbours (arp) c.NDA = strflag { UNSPEC = 0, DST = 1, LLADDR = 2, CACHEINFO = 3, PROBES = 4, } c.NTF = multiflags { USE = 0x01, PROXY = 0x08, ROUTER = 0x80, SELF = 0x02, MASTER = 0x04, } c.NUD = multiflags { INCOMPLETE = 0x01, REACHABLE = 0x02, STALE = 0x04, DELAY = 0x08, PROBE = 0x10, FAILED = 0x20, NOARP = 0x40, PERMANENT = 0x80, NONE = 0x00, } c.NDTPA = strflag { UNSPEC = 0, IFINDEX = 1, REFCNT = 2, REACHABLE_TIME = 3, BASE_REACHABLE_TIME = 4, RETRANS_TIME = 5, GC_STALETIME = 6, DELAY_PROBE_TIME = 7, QUEUE_LEN = 8, APP_PROBES = 9, UCAST_PROBES = 10, MCAST_PROBES = 11, ANYCAST_DELAY = 12, PROXY_DELAY = 13, PROXY_QLEN = 14, LOCKTIME = 15, QUEUE_LENBYTES = 16, } c.NDTA = strflag { UNSPEC = 0, NAME = 1, THRESH1 = 2, THRESH2 = 3, THRESH3 = 4, CONFIG = 5, PARMS = 6, STATS = 7, GC_INTERVAL = 8, } -- address families c.AF = strflag { UNSPEC = 0, LOCAL = 1, INET = 2, AX25 = 3, IPX = 4, APPLETALK = 5, NETROM = 6, BRIDGE = 7, ATMPVC = 8, X25 = 9, INET6 = 10, ROSE = 11, DECNET = 12, NETBEUI = 13, SECURITY = 14, KEY = 15, NETLINK = 16, PACKET = 17, ASH = 18, ECONET = 19, ATMSVC = 20, RDS = 21, SNA = 22, IRDA = 23, PPPOX = 24, WANPIPE = 25, LLC = 26, CAN = 29, TIPC = 30, BLUETOOTH = 31, IUCV = 32, RXRPC = 33, ISDN = 34, PHONET = 35, IEEE802154 = 36, CAIF = 37, ALG = 38, NFC = 39, XDP = 44 } c.AF.UNIX = c.AF.LOCAL c.AF.FILE = c.AF.LOCAL c.AF.ROUTE = c.AF.NETLINK -- arp types, which are also interface types for ifi_type c.ARPHRD = strflag { NETROM = 0, ETHER = 1, EETHER = 2, AX25 = 3, PRONET = 4, CHAOS = 5, IEEE802 = 6, ARCNET = 7, APPLETLK = 8, DLCI = 15, ATM = 19, METRICOM = 23, IEEE1394 = 24, EUI64 = 27, INFINIBAND = 32, SLIP = 256, CSLIP = 257, SLIP6 = 258, CSLIP6 = 259, RSRVD = 260, ADAPT = 264, ROSE = 270, X25 = 271, HWX25 = 272, CAN = 280, PPP = 512, CISCO = 513, LAPB = 516, DDCMP = 517, RAWHDLC = 518, TUNNEL = 768, TUNNEL6 = 769, FRAD = 770, SKIP = 771, LOOPBACK = 772, LOCALTLK = 773, FDDI = 774, BIF = 775, SIT = 776, IPDDP = 777, IPGRE = 778, PIMREG = 779, HIPPI = 780, ASH = 781, ECONET = 782, IRDA = 783, FCPP = 784, FCAL = 785, FCPL = 786, FCFABRIC = 787, IEEE802_TR = 800, IEEE80211 = 801, IEEE80211_PRISM = 802, IEEE80211_RADIOTAP = 803, IEEE802154 = 804, PHONET = 820, PHONET_PIPE = 821, CAIF = 822, VOID = 0xFFFF, NONE = 0xFFFE, } c.ARPHRD.HDLC = c.ARPHRD.CISCO -- IP c.IPPROTO = strflag { IP = 0, ICMP = 1, IGMP = 2, IPIP = 4, TCP = 6, EGP = 8, PUP = 12, UDP = 17, IDP = 22, TP = 29, DCCP = 33, IPV6 = 41, ROUTING = 43, FRAGMENT = 44, RSVP = 46, GRE = 47, ESP = 50, AH = 51, ICMPV6 = 58, NONE = 59, DSTOPTS = 60, MTP = 92, ENCAP = 98, PIM = 103, COMP = 108, SCTP = 132, UDPLITE = 136, RAW = 255, } c.IP = strflag { TOS = 1, TTL = 2, HDRINCL = 3, OPTIONS = 4, ROUTER_ALERT = 5, RECVOPTS = 6, RETOPTS = 7, PKTINFO = 8, PKTOPTIONS = 9, MTU_DISCOVER = 10, RECVERR = 11, RECVTTL = 12, RECVTOS = 13, MTU = 14, FREEBIND = 15, IPSEC_POLICY = 16, XFRM_POLICY = 17, PASSSEC = 18, TRANSPARENT = 19, ORIGDSTADDR = 20, MINTTL = 21, NODEFRAG = 22, MULTICAST_IF = 32, MULTICAST_TTL = 33, MULTICAST_LOOP = 34, ADD_MEMBERSHIP = 35, DROP_MEMBERSHIP = 36, UNBLOCK_SOURCE = 37, BLOCK_SOURCE = 38, ADD_SOURCE_MEMBERSHIP = 39, DROP_SOURCE_MEMBERSHIP = 40, MSFILTER = 41, MULTICAST_ALL = 49, UNICAST_IF = 50, } c.ETH_P = strflag { LOOP = 0x0060, PUP = 0x0200, PUPAT = 0x0201, IP = 0x0800, X25 = 0x0805, ARP = 0x0806, BPQ = 0x08FF, IEEEPUP = 0x0a00, IEEEPUPAT = 0x0a01, DEC = 0x6000, DNA_DL = 0x6001, DNA_RC = 0x6002, DNA_RT = 0x6003, LAT = 0x6004, DIAG = 0x6005, CUST = 0x6006, SCA = 0x6007, TEB = 0x6558, RARP = 0x8035, ATALK = 0x809B, AARP = 0x80F3, ["8021Q"] = 0x8100, IPX = 0x8137, IPV6 = 0x86DD, PAUSE = 0x8808, SLOW = 0x8809, WCCP = 0x883E, PPP_DISC = 0x8863, PPP_SES = 0x8864, MPLS_UC = 0x8847, MPLS_MC = 0x8848, ATMMPOA = 0x884c, LINK_CTL = 0x886c, ATMFATE = 0x8884, PAE = 0x888E, AOE = 0x88A2, ["8021AD"]= 0x88A8, ["802_EX1"]= 0x88B5, TIPC = 0x88CA, ["8021AH"]= 0x88E7, ["1588"] = 0x88F7, FCOE = 0x8906, TDLS = 0x890D, FIP = 0x8914, QINQ1 = 0x9100, QINQ2 = 0x9200, QINQ3 = 0x9300, EDSA = 0xDADA, AF_IUCV = 0xFBFB, ["802_3"] = 0x0001, AX25 = 0x0002, ALL = 0x0003, ["802_2"] = 0x0004, SNAP = 0x0005, DDCMP = 0x0006, WAN_PPP = 0x0007, PPP_MP = 0x0008, LOCALTALK = 0x0009, CAN = 0x000C, PPPTALK = 0x0010, TR_802_2 = 0x0011, MOBITEX = 0x0015, CONTROL = 0x0016, IRDA = 0x0017, ECONET = 0x0018, HDLC = 0x0019, ARCNET = 0x001A, DSA = 0x001B, TRAILER = 0x001C, PHONET = 0x00F5, IEEE802154= 0x00F6, CAIF = 0x00F7, } c.ETHERTYPE = strflag { PUP = 0x0200, SPRITE = 0x0500, IP = 0x0800, ARP = 0x0806, REVARP = 0x8035, AT = 0x809B, AARP = 0x80F3, VLAN = 0x8100, IPX = 0x8137, IPV6 = 0x86dd, LOOPBACK = 0x9000, TRAIL = 0x1000, } -- eventfd c.EFD = multiflags { SEMAPHORE = 1, CLOEXEC = c.O.CLOEXEC, NONBLOCK = c.O.NONBLOCK, } -- mount c.MS = multiflags { RDONLY = 1, NOSUID = 2, NODEV = 4, NOEXEC = 8, SYNCHRONOUS = 16, REMOUNT = 32, MANDLOCK = 64, DIRSYNC = 128, NOATIME = 1024, NODIRATIME = 2048, BIND = 4096, MOVE = 8192, REC = 16384, SILENT = 32768, POSIXACL = bit.lshift(1, 16), UNBINDABLE = bit.lshift(1, 17), PRIVATE = bit.lshift(1, 18), SLAVE = bit.lshift(1, 19), SHARED = bit.lshift(1, 20), RELATIME = bit.lshift(1, 21), KERNMOUNT = bit.lshift(1, 22), I_VERSION = bit.lshift(1, 23), STRICTATIME = bit.lshift(1, 24), ACTIVE = bit.lshift(1, 30), NOUSER = bit.lshift(1, 31), } -- fake flags c.MS.RO = c.MS.RDONLY -- allow use of "ro" as flag as that is what /proc/mounts uses c.MS.RW = 0 -- allow use of "rw" as flag as appears in /proc/mounts c.MS.SECLABEL = 0 -- appears in /proc/mounts in some distros, ignore -- flags to `msync'. - note was MS_ renamed to MSYNC_ c.MSYNC = multiflags { ASYNC = 1, INVALIDATE = 2, SYNC = 4, } -- one table for umount as it uses MNT_ and UMOUNT_ options c.UMOUNT = multiflags { FORCE = 1, DETACH = 2, EXPIRE = 4, NOFOLLOW = 8, } -- reboot c.LINUX_REBOOT_CMD = strflag { RESTART = 0x01234567, HALT = 0xCDEF0123, CAD_ON = 0x89ABCDEF, CAD_OFF = 0x00000000, POWER_OFF = 0x4321FEDC, RESTART2 = 0xA1B2C3D4, SW_SUSPEND = 0xD000FCE2, KEXEC = 0x45584543, } -- clone c.CLONE = multiflags { VM = 0x00000100, FS = 0x00000200, FILES = 0x00000400, SIGHAND = 0x00000800, PTRACE = 0x00002000, VFORK = 0x00004000, PARENT = 0x00008000, THREAD = 0x00010000, NEWNS = 0x00020000, SYSVSEM = 0x00040000, SETTLS = 0x00080000, PARENT_SETTID = 0x00100000, CHILD_CLEARTID = 0x00200000, DETACHED = 0x00400000, UNTRACED = 0x00800000, CHILD_SETTID = 0x01000000, NEWUTS = 0x04000000, NEWIPC = 0x08000000, NEWUSER = 0x10000000, NEWPID = 0x20000000, NEWNET = 0x40000000, IO = 0x80000000, } -- inotify -- flags note rename from IN_ to IN_INIT c.IN_INIT = multiflags(arch.IN_INIT or { CLOEXEC = octal("02000000"), NONBLOCK = octal("04000"), }) -- events c.IN = multiflags { ACCESS = 0x00000001, MODIFY = 0x00000002, ATTRIB = 0x00000004, CLOSE_WRITE = 0x00000008, CLOSE_NOWRITE = 0x00000010, OPEN = 0x00000020, MOVED_FROM = 0x00000040, MOVED_TO = 0x00000080, CREATE = 0x00000100, DELETE = 0x00000200, DELETE_SELF = 0x00000400, MOVE_SELF = 0x00000800, UNMOUNT = 0x00002000, Q_OVERFLOW = 0x00004000, IGNORED = 0x00008000, ONLYDIR = 0x01000000, DONT_FOLLOW = 0x02000000, EXCL_UNLINK = 0x04000000, MASK_ADD = 0x20000000, ISDIR = 0x40000000, ONESHOT = 0x80000000, } c.IN.CLOSE = c.IN.CLOSE_WRITE + c.IN.CLOSE_NOWRITE c.IN.MOVE = c.IN.MOVED_FROM + c.IN.MOVED_TO c.IN.ALL_EVENTS = c.IN.ACCESS + c.IN.MODIFY + c.IN.ATTRIB + c.IN.CLOSE_WRITE + c.IN.CLOSE_NOWRITE + c.IN.OPEN + c.IN.MOVED_FROM + c.IN.MOVED_TO + c.IN.CREATE + c.IN.DELETE + c.IN.DELETE_SELF + c.IN.MOVE_SELF --prctl c.PR = strflag { SET_PDEATHSIG = 1, GET_PDEATHSIG = 2, GET_DUMPABLE = 3, SET_DUMPABLE = 4, GET_UNALIGN = 5, SET_UNALIGN = 6, GET_KEEPCAPS = 7, SET_KEEPCAPS = 8, GET_FPEMU = 9, SET_FPEMU = 10, GET_FPEXC = 11, SET_FPEXC = 12, GET_TIMING = 13, SET_TIMING = 14, SET_NAME = 15, GET_NAME = 16, GET_ENDIAN = 19, SET_ENDIAN = 20, GET_SECCOMP = 21, SET_SECCOMP = 22, CAPBSET_READ = 23, CAPBSET_DROP = 24, GET_TSC = 25, SET_TSC = 26, GET_SECUREBITS= 27, SET_SECUREBITS= 28, SET_TIMERSLACK= 29, GET_TIMERSLACK= 30, TASK_PERF_EVENTS_DISABLE=31, TASK_PERF_EVENTS_ENABLE=32, MCE_KILL = 33, MCE_KILL_GET = 34, SET_NO_NEW_PRIVS = 38, GET_NO_NEW_PRIVS = 39, GET_TID_ADDRESS = 40, } -- for PR get/set unalign c.PR_UNALIGN = strflag { NOPRINT = 1, SIGBUS = 2, } -- for PR fpemu c.PR_FPEMU = strflag { NOPRINT = 1, SIGFPE = 2, } -- for PR fpexc -- TODO should be a combo of stringflag and flags c.PR_FP_EXC = multiflags { SW_ENABLE = 0x80, DIV = 0x010000, OVF = 0x020000, UND = 0x040000, RES = 0x080000, INV = 0x100000, DISABLED = 0, NONRECOV = 1, ASYNC = 2, PRECISE = 3, } -- PR get set timing c.PR_TIMING = strflag { STATISTICAL= 0, TIMESTAMP = 1, } -- PR set endian c.PR_ENDIAN = strflag { BIG = 0, LITTLE = 1, PPC_LITTLE = 2, } -- PR TSC c.PR_TSC = strflag { ENABLE = 1, SIGSEGV = 2, } -- somewhat confusing as there are some in PR too. c.PR_MCE_KILL = strflag { CLEAR = 0, SET = 1, } -- note rename, this is extra option see prctl code c.PR_MCE_KILL_OPT = strflag { LATE = 0, EARLY = 1, DEFAULT = 2, } c.LINUX_CAPABILITY_VERSION = {0x19980330, 0x20071026, 0x20080522} c.LINUX_CAPABILITY_U32S = {1, 2, 2} -- capabilities NB these are bit shifts c.CAP = strflag { CHOWN = 0, DAC_OVERRIDE = 1, DAC_READ_SEARCH = 2, FOWNER = 3, FSETID = 4, KILL = 5, SETGID = 6, SETUID = 7, SETPCAP = 8, LINUX_IMMUTABLE = 9, NET_BIND_SERVICE = 10, NET_BROADCAST = 11, NET_ADMIN = 12, NET_RAW = 13, IPC_LOCK = 14, IPC_OWNER = 15, SYS_MODULE = 16, SYS_RAWIO = 17, SYS_CHROOT = 18, SYS_PTRACE = 19, SYS_PACCT = 20, SYS_ADMIN = 21, SYS_BOOT = 22, SYS_NICE = 23, SYS_RESOURCE = 24, SYS_TIME = 25, SYS_TTY_CONFIG = 26, MKNOD = 27, LEASE = 28, AUDIT_WRITE = 29, AUDIT_CONTROL = 30, SETFCAP = 31, MAC_OVERRIDE = 32, MAC_ADMIN = 33, SYSLOG = 34, WAKE_ALARM = 35, } -- capabilities as stored on file system in xattr c.VFS_CAP = strflag { REVISION_MASK = 0xFF000000, REVISION_SHIFT = 24, REVISION_1 = 0x01000000, U32_1 = 1, REVISION_2 = 0x02000000, U32_2 = 2, } c.VFS_CAP.FLAGS_MASK = bit.bnot(c.VFS_CAP.REVISION_MASK) c.VFS_CAP.U32 = c.VFS_CAP.U32_2 c.VFS_CAP.REVISION = c.VFS_CAP.REVISION_2 c.VFS_CAP_FLAGS = strflag { EFFECTIVE = 0x000001, } c.XATTR_CAPS = strflag { SZ_1 = 4 * (1 + 2 * c.VFS_CAP.U32_1), SZ_2 = 4 * (1 + 2 * c.VFS_CAP.U32_2), } c.XATTR_CAPS.SZ = c.XATTR_CAPS.SZ_2 -- new SECCOMP modes, now there is filter as well as strict c.SECCOMP_MODE = strflag { DISABLED = 0, STRICT = 1, FILTER = 2, } c.SECCOMP_RET = multiflags { KILL = 0x00000000, TRAP = 0x00030000, ERRNO = 0x00050000, TRACE = 0x7ff00000, ALLOW = 0x7fff0000, ACTION = 0x7fff0000, -- mask DATA = 0x0000ffff, -- mask } -- Elf machine flags c.EM = strflag { NONE = 0, M32 = 1, SPARC = 2, ["386"] = 3, ["68K"] = 4, ["88K"] = 5, ["860"] = 7, MIPS = 8, MIPS_RS3_LE = 10, MIPS_RS4_BE = 10, PARISC = 15, SPARC32PLUS = 18, PPC = 20, PPC64 = 21, S390 = 22, SPU = 23, ARM = 40, SH = 42, SPARCV9 = 43, H8_300 = 46, IA_64 = 50, X86_64 = 62, CRIS = 76, V850 = 87, M32R = 88, MN10300 = 89, BLACKFIN = 106, TI_C6000 = 140, AARCH64 = 183, FRV = 0x5441, AVR32 = 0x18ad, ALPHA = 0x9026, CYGNUS_V850 = 0x9080, CYGNUS_M32R = 0x9041, S390_OLD = 0xA390, CYGNUS_MN10300 = 0xbeef, } -- audit flags (lots missing from linux/audit.h) -- I don't think we need to export these local __AUDIT_ARCH_64BIT = 0x80000000 local __AUDIT_ARCH_LE = 0x40000000 c.AUDIT_ARCH = strflag { AARCH64 = c.EM.AARCH64 + __AUDIT_ARCH_64BIT + __AUDIT_ARCH_LE, ALPHA = c.EM.ALPHA + __AUDIT_ARCH_64BIT + __AUDIT_ARCH_LE, ARM = c.EM.ARM + __AUDIT_ARCH_LE, ARMEB = c.EM.ARM, CRIS = c.EM.CRIS + __AUDIT_ARCH_LE, FRV = c.EM.FRV, H8300 = c.EM.H8_300, I386 = c.EM["386"] + __AUDIT_ARCH_LE, IA64 = c.EM.IA_64 + __AUDIT_ARCH_64BIT + __AUDIT_ARCH_LE, M32R = c.EM.M32R, M68K = c.EM["68K"], MIPS = c.EM.MIPS, MIPSEL = c.EM.MIPS + __AUDIT_ARCH_LE, MIPS64 = c.EM.MIPS + __AUDIT_ARCH_64BIT, MIPSEL64 = c.EM.MIPS + __AUDIT_ARCH_64BIT + __AUDIT_ARCH_LE, PARISC = c.EM.PARISC, PARISC64 = c.EM.PARISC + __AUDIT_ARCH_64BIT, PPC = c.EM.PPC, PPC64 = c.EM.PPC64 + __AUDIT_ARCH_64BIT, S390 = c.EM.S390, S390X = c.EM.S390 + __AUDIT_ARCH_64BIT, SH = c.EM.SH, SHEL = c.EM.SH + __AUDIT_ARCH_LE, SH64 = c.EM.SH + __AUDIT_ARCH_64BIT, SHEL64 =c.EM.SH + __AUDIT_ARCH_64BIT + __AUDIT_ARCH_LE, SPARC =c.EM.SPARC, SPARC64 =c.EM.SPARCV9 + __AUDIT_ARCH_64BIT, X86_64 = c.EM.X86_64 + __AUDIT_ARCH_64BIT + __AUDIT_ARCH_LE, } -- BPF socket filter c.BPF = multiflags { -- class LD = 0x00, LDX = 0x01, ST = 0x02, STX = 0x03, ALU = 0x04, ALU64 = 0x07, JMP = 0x05, RET = 0x06, MISC = 0x07, -- size W = 0x00, H = 0x08, B = 0x10, DW = 0x18, -- mode IMM = 0x00, ABS = 0x20, IND = 0x40, MEM = 0x60, LEN = 0x80, MSH = 0xa0, -- op ADD = 0x00, SUB = 0x10, MUL = 0x20, DIV = 0x30, OR = 0x40, AND = 0x50, LSH = 0x60, RSH = 0x70, ARSH = 0xc0, NEG = 0x80, MOD = 0x90, XOR = 0xa0, MOV = 0xb0, XADD = 0xc0, END = 0xd0, JA = 0x00, JEQ = 0x10, JGT = 0x20, JGE = 0x30, JSET = 0x40, JNE = 0x50, JSGT = 0x60, JSGE = 0x70, CALL = 0x80, EXIT = 0x90, -- src K = 0x00, X = 0x08, -- rval A = 0x10, -- miscop TAX = 0x00, TXA = 0x80, TO_LE = 0x00, TO_BE = 0x08, -- flags ANY = 0, NOEXIST = 1, EXIST = 2, } -- BPF map type c.BPF_MAP = strflag { UNSPEC = 0, HASH = 1, ARRAY = 2, PROG_ARRAY = 3, PERF_EVENT_ARRAY = 4, PERCPU_HASH = 5, PERCPU_ARRAY = 6, STACK_TRACE = 7, CGROUP_ARRAY = 8, LRU_HASH = 9, LRU_PERCPU_HASH = 10, LPM_TRIE = 11, ARRAY_OF_MAPS = 12, HASH_OF_MAPS = 13, DEVMAP = 14, SOCKMAP = 15, CPUMAP = 16, XSKMAP = 17 } -- BPF syscall commands c.BPF_CMD = strflag { MAP_CREATE = 0, MAP_LOOKUP_ELEM = 1, MAP_UPDATE_ELEM = 2, MAP_DELETE_ELEM = 3, MAP_GET_NEXT_KEY = 4, PROG_LOAD = 5, OBJ_PIN = 6, OBJ_GET = 7, PROG_ATTACH = 8, PROG_DETACH = 9, PROG_TEST_RUN = 10, PROG_GET_NEXT_ID = 11, MAP_GET_NEXT_ID = 12, PROG_GET_FD_BY_ID = 13, MAP_GET_FD_BY_ID = 14, OBJ_GET_INFO_BY_FD = 15, PROG_QUERY = 16, RAW_TRACEPOINT_OPEN = 17, } -- BPF program types c.BPF_PROG = strflag { UNSPEC = 0, SOCKET_FILTER = 1, KPROBE = 2, SCHED_CLS = 3, SCHED_ACT = 4, TRACEPOINT = 5, XDP = 6, PERF_EVENT = 7, CGROUP_SKB = 8, CGROUP_SOCK = 9, LWT_IN = 10, LWT_OUT = 11, LWT_XMIT = 12, SOCK_OPS = 13, SK_SKB = 14, CGROUP_DEVICE = 15, SK_MSG = 16, RAW_TRACEPOINT = 17, CGROUP_SOCK_ADDR = 18, } -- BPF attach type c.BPF_ATTACH_TYPE = strflag { CGROUP_INET_INGRESS = 0, CGROUP_INET_EGRESS = 1, CGROUP_INET_SOCK_CREATE = 2, CGROUP_SOCK_OPS = 3, SK_SKB_STREAM_PARSER = 4, SK_SKB_STREAM_VERDICT = 5, CGROUP_DEVICE = 6, SK_MSG_VERDICT = 7, CGROUP_INET4_BIND = 8, CGROUP_INET6_BIND = 9, CGROUP_INET4_CONNECT = 10, CGROUP_INET6_CONNECT = 11, CGROUP_INET4_POST_BIND = 12, CGROUP_INET6_POST_BIND = 13, } -- Linux performance monitoring -- perf_event_attr.type c.PERF_TYPE = strflag { HARDWARE = 0, SOFTWARE = 1, TRACEPOINT = 2, HW_CACHE = 3, RAW = 4, BREAKPOINT = 5, } -- perf_event_attr.event_id c.PERF_COUNT = strflag { -- Generalized performance event event_id types HW_CPU_CYCLES = 0, HW_INSTRUCTIONS = 1, HW_CACHE_REFERENCES = 2, HW_CACHE_MISSES = 3, HW_BRANCH_INSTRUCTIONS = 4, HW_BRANCH_MISSES = 5, HW_BUS_CYCLES = 6, HW_STALLED_CYCLES_FRONTEND = 7, HW_STALLED_CYCLES_BACKEND = 8, HW_REF_CPU_CYCLES = 9, -- Generalized hardware cache events HW_CACHE_L1D = 0, HW_CACHE_L1I = 1, HW_CACHE_LL = 2, HW_CACHE_DTLB = 3, HW_CACHE_ITLB = 4, HW_CACHE_BPU = 5, HW_CACHE_NODE = 6, HW_CACHE_OP_READ = 0, HW_CACHE_OP_WRITE = 1, HW_CACHE_OP_PREFETCH = 2, HW_CACHE_RESULT_ACCESS = 0, HW_CACHE_RESULT_MISS = 1, -- Special "software" events provided by the kernel SW_CPU_CLOCK = 0, SW_TASK_CLOCK = 1, SW_PAGE_FAULTS = 2, SW_CONTEXT_SWITCHES = 3, SW_CPU_MIGRATIONS = 4, SW_PAGE_FAULTS_MIN = 5, SW_PAGE_FAULTS_MAJ = 6, SW_ALIGNMENT_FAULTS = 7, SW_EMULATION_FAULTS = 8, SW_DUMMY = 9, SW_BPF_OUTPUT = 10, } -- Bits that can be set in perf_event_attr.sample_type to request information c.PERF_SAMPLE = multiflags { IP = bit.lshift(1, 0), TID = bit.lshift(1, 1), TIME = bit.lshift(1, 2), ADDR = bit.lshift(1, 3), READ = bit.lshift(1, 4), CALLCHAIN = bit.lshift(1, 5), ID = bit.lshift(1, 6), CPU = bit.lshift(1, 7), PERIOD = bit.lshift(1, 8), STREAM_ID = bit.lshift(1, 9), RAW = bit.lshift(1, 10), BRANCH_STACK = bit.lshift(1, 11), REGS_USER = bit.lshift(1, 12), STACK_USER = bit.lshift(1, 13), WEIGHT = bit.lshift(1, 14), DATA_SRC = bit.lshift(1, 15), IDENTIFIER = bit.lshift(1, 16), TRANSACTION = bit.lshift(1, 17), REGS_INTR = bit.lshift(1, 18), } -- values to program into perf_event_attr.branch_sample_type when PERF_SAMPLE_BRANCH is set c.PERF_SAMPLE_BRANCH = multiflags { USER_SHIFT = 0, KERNEL_SHIFT = 1, HV_SHIFT = 2, ANY_SHIFT = 3, ANY_CALL_SHIFT = 4, ANY_RETURN_SHIFT = 5, IND_CALL_SHIFT = 6, ABORT_TX_SHIFT = 7, IN_TX_SHIFT = 8, NO_TX_SHIFT = 9, COND_SHIFT = 10, CALL_STACK_SHIFT = 11, IND_JUMP_SHIFT = 12, CALL_SHIFT = 13, NO_FLAGS_SHIFT = 14, NO_CYCLES_SHIFT = 15, } c.PERF_SAMPLE_BRANCH.USER = bit.lshift(1, c.PERF_SAMPLE_BRANCH.USER_SHIFT) c.PERF_SAMPLE_BRANCH.KERNEL = bit.lshift(1, c.PERF_SAMPLE_BRANCH.KERNEL_SHIFT) c.PERF_SAMPLE_BRANCH.HV = bit.lshift(1, c.PERF_SAMPLE_BRANCH.HV_SHIFT) c.PERF_SAMPLE_BRANCH.ANY = bit.lshift(1, c.PERF_SAMPLE_BRANCH.ANY_SHIFT) c.PERF_SAMPLE_BRANCH.ANY_CALL = bit.lshift(1, c.PERF_SAMPLE_BRANCH.ANY_CALL_SHIFT) c.PERF_SAMPLE_BRANCH.ANY_RETURN = bit.lshift(1, c.PERF_SAMPLE_BRANCH.ANY_RETURN_SHIFT) c.PERF_SAMPLE_BRANCH.IND_CALL = bit.lshift(1, c.PERF_SAMPLE_BRANCH.IND_CALL_SHIFT) c.PERF_SAMPLE_BRANCH.ABORT_TX = bit.lshift(1, c.PERF_SAMPLE_BRANCH.ABORT_TX_SHIFT) c.PERF_SAMPLE_BRANCH.IN_TX = bit.lshift(1, c.PERF_SAMPLE_BRANCH.IN_TX_SHIFT) c.PERF_SAMPLE_BRANCH.NO_TX = bit.lshift(1, c.PERF_SAMPLE_BRANCH.NO_TX_SHIFT) c.PERF_SAMPLE_BRANCH.COND = bit.lshift(1, c.PERF_SAMPLE_BRANCH.COND_SHIFT) c.PERF_SAMPLE_BRANCH.CALL_STACK = bit.lshift(1, c.PERF_SAMPLE_BRANCH.CALL_STACK_SHIFT) c.PERF_SAMPLE_BRANCH.IND_JUMP = bit.lshift(1, c.PERF_SAMPLE_BRANCH.IND_JUMP_SHIFT) c.PERF_SAMPLE_BRANCH.CALL = bit.lshift(1, c.PERF_SAMPLE_BRANCH.CALL_SHIFT) c.PERF_SAMPLE_BRANCH.NO_FLAGS = bit.lshift(1, c.PERF_SAMPLE_BRANCH.NO_FLAGS_SHIFT) c.PERF_SAMPLE_BRANCH.NO_CYCLES = bit.lshift(1, c.PERF_SAMPLE_BRANCH.NO_CYCLES_SHIFT) -- Flags for perf_attr.read_format c.PERF_READ_FORMAT = multiflags { TOTAL_TIME_ENABLED = bit.lshift(1, 0), TOTAL_TIME_RUNNING = bit.lshift(1, 1), ID = bit.lshift(1, 2), GROUP = bit.lshift(1, 3), } -- Flags for perf_event_open c.PERF_FLAG = multiflags { FD_NO_GROUP = bit.lshift(1, 0), FD_OUTPUT = bit.lshift(1, 1), PID_CGROUP = bit.lshift(1, 2), FD_CLOEXEC = bit.lshift(1, 3), } -- If perf_event_attr.sample_id_all is set then all event types will -- have the sample_type selected fields related to where/when -- (identity) an event took place (TID, TIME, ID, STREAM_ID, CPU, IDENTIFIER) c.PERF_RECORD = strflag { MMAP = 1, LOST = 2, COMM = 3, EXIT = 4, THROTTLE = 5, UNTHROTTLE = 6, FORK = 7, READ = 8, SAMPLE = 9, MMAP2 = 10, AUX = 11, ITRACE_START = 12, LOST_SAMPLES = 13, SWITCH = 14, SWITCH_CPU_WIDE= 15, } -- termios - c_cc characters c.CC = strflag(arch.CC or { VINTR = 0, VQUIT = 1, VERASE = 2, VKILL = 3, VEOF = 4, VTIME = 5, VMIN = 6, VSWTC = 7, VSTART = 8, VSTOP = 9, VSUSP = 10, VEOL = 11, VREPRINT = 12, VDISCARD = 13, VWERASE = 14, VLNEXT = 15, VEOL2 = 16, }) -- termios - c_iflag bits c.IFLAG = multiflags(arch.IFLAG or { IGNBRK = octal('0000001'), BRKINT = octal('0000002'), IGNPAR = octal('0000004'), PARMRK = octal('0000010'), INPCK = octal('0000020'), ISTRIP = octal('0000040'), INLCR = octal('0000100'), IGNCR = octal('0000200'), ICRNL = octal('0000400'), IUCLC = octal('0001000'), IXON = octal('0002000'), IXANY = octal('0004000'), IXOFF = octal('0010000'), IMAXBEL = octal('0020000'), IUTF8 = octal('0040000'), }) -- termios - c_oflag bits c.OFLAG = multiflags(arch.OFLAG or { OPOST = octal('0000001'), OLCUC = octal('0000002'), ONLCR = octal('0000004'), OCRNL = octal('0000010'), ONOCR = octal('0000020'), ONLRET = octal('0000040'), OFILL = octal('0000100'), OFDEL = octal('0000200'), NLDLY = octal('0000400'), NL0 = octal('0000000'), NL1 = octal('0000400'), CRDLY = octal('0003000'), CR0 = octal('0000000'), CR1 = octal('0001000'), CR2 = octal('0002000'), CR3 = octal('0003000'), TABDLY = octal('0014000'), TAB0 = octal('0000000'), TAB1 = octal('0004000'), TAB2 = octal('0010000'), TAB3 = octal('0014000'), BSDLY = octal('0020000'), BS0 = octal('0000000'), BS1 = octal('0020000'), FFDLY = octal('0100000'), FF0 = octal('0000000'), FF1 = octal('0100000'), VTDLY = octal('0040000'), VT0 = octal('0000000'), VT1 = octal('0040000'), XTABS = octal('0014000'), }) -- using string keys as sparse array uses a lot of memory c.B = setmetatable(arch.B or { ['0'] = octal('0000000'), ['50'] = octal('0000001'), ['75'] = octal('0000002'), ['110'] = octal('0000003'), ['134'] = octal('0000004'), ['150'] = octal('0000005'), ['200'] = octal('0000006'), ['300'] = octal('0000007'), ['600'] = octal('0000010'), ['1200'] = octal('0000011'), ['1800'] = octal('0000012'), ['2400'] = octal('0000013'), ['4800'] = octal('0000014'), ['9600'] = octal('0000015'), ['19200'] = octal('0000016'), ['38400'] = octal('0000017'), ['57600'] = octal('0010001'), ['115200'] = octal('0010002'), ['230400'] = octal('0010003'), ['460800'] = octal('0010004'), ['500000'] = octal('0010005'), ['576000'] = octal('0010006'), ['921600'] = octal('0010007'), ['1000000'] = octal('0010010'), ['1152000'] = octal('0010011'), ['1500000'] = octal('0010012'), ['2000000'] = octal('0010013'), ['2500000'] = octal('0010014'), ['3000000'] = octal('0010015'), ['3500000'] = octal('0010016'), ['4000000'] = octal('0010017'), }, { __index = function(b, k) return b[tostring(k)] end, }) --[[ c.__MAX_BAUD = c.B4000000 c.EXTA = c.B19200 c.EXTB = c.B38400 ]] -- TODO clean up how to handle these (used for custom speeds) c.CBAUD = arch.CBAUD or octal('0010017') c.CBAUDEX = arch.CBAUDEX or octal('0010000') c.CIBAUD = arch.CIBAUD or octal('002003600000') -- input baud rate (not used) c.CMSPAR = octal('010000000000') -- mark or space (stick) parity c.CRTSCTS = octal('020000000000') -- flow control -- termios - c_cflag bits c.CFLAG = multiflags(arch.CFLAG or { CSIZE = octal('0000060'), CS5 = octal('0000000'), CS6 = octal('0000020'), CS7 = octal('0000040'), CS8 = octal('0000060'), CSTOPB = octal('0000100'), CREAD = octal('0000200'), PARENB = octal('0000400'), PARODD = octal('0001000'), HUPCL = octal('0002000'), CLOCAL = octal('0004000'), }) -- termios - c_lflag bits c.LFLAG = multiflags(arch.LFLAG or { ISIG = octal('0000001'), ICANON = octal('0000002'), XCASE = octal('0000004'), ECHO = octal('0000010'), ECHOE = octal('0000020'), ECHOK = octal('0000040'), ECHONL = octal('0000100'), NOFLSH = octal('0000200'), TOSTOP = octal('0000400'), ECHOCTL = octal('0001000'), ECHOPRT = octal('0002000'), ECHOKE = octal('0004000'), FLUSHO = octal('0010000'), PENDIN = octal('0040000'), IEXTEN = octal('0100000'), EXTPROC = octal('0200000'), }) -- termios - tcflow() and TCXONC use these. renamed from TC to TCFLOW c.TCFLOW = strflag { OOFF = 0, OON = 1, IOFF = 2, ION = 3, } -- termios - tcflush() and TCFLSH use these. renamed from TC to TCFLUSH c.TCFLUSH = strflag { IFLUSH = 0, OFLUSH = 1, IOFLUSH = 2, } -- termios - tcsetattr uses these c.TCSA = strflag { NOW = 0, DRAIN = 1, FLUSH = 2, } -- TIOCM c.TIOCM = multiflags(arch.TIOCM or { LE = 0x001, DTR = 0x002, RTS = 0x004, ST = 0x008, SR = 0x010, CTS = 0x020, CAR = 0x040, RNG = 0x080, DSR = 0x100, }) c.TIOCM.CD = c.TIOCM.CAR c.TIOCM.RI = c.TIOCM.RNG -- sysfs values c.SYSFS_BRIDGE_ATTR = "bridge" c.SYSFS_BRIDGE_FDB = "brforward" c.SYSFS_BRIDGE_PORT_SUBDIR = "brif" c.SYSFS_BRIDGE_PORT_ATTR = "brport" c.SYSFS_BRIDGE_PORT_LINK = "bridge" -- sizes -- TODO in tables? c.HOST_NAME_MAX = 64 c.IFNAMSIZ = 16 c.IFHWADDRLEN = 6 -- input subsystem. TODO split into another file as a lot of them c.INPUT_PROP = strflag { POINTER = 0x00, DIRECT = 0x01, BUTTONPAD = 0x02, SEMI_MT = 0x03, } c.EV = strflag { SYN = 0x00, KEY = 0x01, REL = 0x02, ABS = 0x03, MSC = 0x04, SW = 0x05, LED = 0x11, SND = 0x12, REP = 0x14, FF = 0x15, PWR = 0x16, FF_STATUS = 0x17, MAX = 0x1f, } c.SYN = strflag { REPORT = 0, CONFIG = 1, MT_REPORT = 2, DROPPED = 3, } -- TODO odd namespacing issue with KEY and BTN, not sure best resolution, maybe have KEYBTN table with both c.KEY = strflag { RESERVED = 0, ESC = 1, ["1"] = 2, ["2"] = 3, ["3"] = 4, ["4"] = 5, ["5"] = 6, ["6"] = 7, ["7"] = 8, ["8"] = 9, ["9"] = 10, ["0"] = 11, MINUS = 12, EQUAL = 13, BACKSPACE = 14, TAB = 15, Q = 16, W = 17, E = 18, R = 19, T = 20, Y = 21, U = 22, I = 23, O = 24, P = 25, LEFTBRACE = 26, RIGHTBRACE = 27, ENTER = 28, LEFTCTRL = 29, A = 30, S = 31, D = 32, F = 33, G = 34, H = 35, J = 36, K = 37, L = 38, SEMICOLON = 39, APOSTROPHE = 40, GRAVE = 41, LEFTSHIFT = 42, BACKSLASH = 43, Z = 44, X = 45, C = 46, V = 47, B = 48, N = 49, M = 50, COMMA = 51, DOT = 52, SLASH = 53, RIGHTSHIFT = 54, KPASTERISK = 55, LEFTALT = 56, SPACE = 57, CAPSLOCK = 58, F1 = 59, F2 = 60, F3 = 61, F4 = 62, F5 = 63, F6 = 64, F7 = 65, F8 = 66, F9 = 67, F10 = 68, NUMLOCK = 69, SCROLLLOCK = 70, KP7 = 71, KP8 = 72, KP9 = 73, KPMINUS = 74, KP4 = 75, KP5 = 76, KP6 = 77, KPPLUS = 78, KP1 = 79, KP2 = 80, KP3 = 81, KP0 = 82, KPDOT = 83, ZENKAKUHANKAKU = 85, ["102ND"] = 86, F11 = 87, F12 = 88, RO = 89, KATAKANA = 90, HIRAGANA = 91, HENKAN = 92, KATAKANAHIRAGANA = 93, MUHENKAN = 94, KPJPCOMMA = 95, KPENTER = 96, RIGHTCTRL = 97, KPSLASH = 98, SYSRQ = 99, RIGHTALT = 100, LINEFEED = 101, HOME = 102, UP = 103, PAGEUP = 104, LEFT = 105, RIGHT = 106, END = 107, DOWN = 108, PAGEDOWN = 109, INSERT = 110, DELETE = 111, MACRO = 112, MUTE = 113, VOLUMEDOWN = 114, VOLUMEUP = 115, POWER = 116, KPEQUAL = 117, KPPLUSMINUS = 118, PAUSE = 119, SCALE = 120, KPCOMMA = 121, HANGEUL = 122, HANJA = 123, YEN = 124, LEFTMETA = 125, RIGHTMETA = 126, COMPOSE = 127, STOP = 128, AGAIN = 129, PROPS = 130, UNDO = 131, FRONT = 132, COPY = 133, OPEN = 134, PASTE = 135, FIND = 136, CUT = 137, HELP = 138, MENU = 139, CALC = 140, SETUP = 141, SLEEP = 142, WAKEUP = 143, FILE = 144, SENDFILE = 145, DELETEFILE = 146, XFER = 147, PROG1 = 148, PROG2 = 149, WWW = 150, MSDOS = 151, COFFEE = 152, DIRECTION = 153, CYCLEWINDOWS = 154, MAIL = 155, BOOKMARKS = 156, COMPUTER = 157, BACK = 158, FORWARD = 159, CLOSECD = 160, EJECTCD = 161, EJECTCLOSECD = 162, NEXTSONG = 163, PLAYPAUSE = 164, PREVIOUSSONG = 165, STOPCD = 166, RECORD = 167, REWIND = 168, PHONE = 169, ISO = 170, CONFIG = 171, HOMEPAGE = 172, REFRESH = 173, EXIT = 174, MOVE = 175, EDIT = 176, SCROLLUP = 177, SCROLLDOWN = 178, KPLEFTPAREN = 179, KPRIGHTPAREN = 180, NEW = 181, REDO = 182, F13 = 183, F14 = 184, F15 = 185, F16 = 186, F17 = 187, F18 = 188, F19 = 189, F20 = 190, F21 = 191, F22 = 192, F23 = 193, F24 = 194, PLAYCD = 200, PAUSECD = 201, PROG3 = 202, PROG4 = 203, DASHBOARD = 204, SUSPEND = 205, CLOSE = 206, PLAY = 207, FASTFORWARD = 208, BASSBOOST = 209, PRINT = 210, HP = 211, CAMERA = 212, SOUND = 213, QUESTION = 214, EMAIL = 215, CHAT = 216, SEARCH = 217, CONNECT = 218, FINANCE = 219, SPORT = 220, SHOP = 221, ALTERASE = 222, CANCEL = 223, BRIGHTNESSDOWN = 224, BRIGHTNESSUP = 225, MEDIA = 226, SWITCHVIDEOMODE = 227, KBDILLUMTOGGLE = 228, KBDILLUMDOWN = 229, KBDILLUMUP = 230, SEND = 231, REPLY = 232, FORWARDMAIL = 233, SAVE = 234, DOCUMENTS = 235, BATTERY = 236, BLUETOOTH = 237, WLAN = 238, UWB = 239, UNKNOWN = 240, VIDEO_NEXT = 241, VIDEO_PREV = 242, BRIGHTNESS_CYCLE = 243, BRIGHTNESS_ZERO = 244, DISPLAY_OFF = 245, WIMAX = 246, RFKILL = 247, MICMUTE = 248, -- BTN values go in here OK = 0x160, SELECT = 0x161, GOTO = 0x162, CLEAR = 0x163, POWER2 = 0x164, OPTION = 0x165, INFO = 0x166, TIME = 0x167, VENDOR = 0x168, ARCHIVE = 0x169, PROGRAM = 0x16a, CHANNEL = 0x16b, FAVORITES = 0x16c, EPG = 0x16d, PVR = 0x16e, MHP = 0x16f, LANGUAGE = 0x170, TITLE = 0x171, SUBTITLE = 0x172, ANGLE = 0x173, ZOOM = 0x174, MODE = 0x175, KEYBOARD = 0x176, SCREEN = 0x177, PC = 0x178, TV = 0x179, TV2 = 0x17a, VCR = 0x17b, VCR2 = 0x17c, SAT = 0x17d, SAT2 = 0x17e, CD = 0x17f, TAPE = 0x180, RADIO = 0x181, TUNER = 0x182, PLAYER = 0x183, TEXT = 0x184, DVD = 0x185, AUX = 0x186, MP3 = 0x187, AUDIO = 0x188, VIDEO = 0x189, DIRECTORY = 0x18a, LIST = 0x18b, MEMO = 0x18c, CALENDAR = 0x18d, RED = 0x18e, GREEN = 0x18f, YELLOW = 0x190, BLUE = 0x191, CHANNELUP = 0x192, CHANNELDOWN = 0x193, FIRST = 0x194, LAST = 0x195, AB = 0x196, NEXT = 0x197, RESTART = 0x198, SLOW = 0x199, SHUFFLE = 0x19a, BREAK = 0x19b, PREVIOUS = 0x19c, DIGITS = 0x19d, TEEN = 0x19e, TWEN = 0x19f, VIDEOPHONE = 0x1a0, GAMES = 0x1a1, ZOOMIN = 0x1a2, ZOOMOUT = 0x1a3, ZOOMRESET = 0x1a4, WORDPROCESSOR = 0x1a5, EDITOR = 0x1a6, SPREADSHEET = 0x1a7, GRAPHICSEDITOR = 0x1a8, PRESENTATION = 0x1a9, DATABASE = 0x1aa, NEWS = 0x1ab, VOICEMAIL = 0x1ac, ADDRESSBOOK = 0x1ad, MESSENGER = 0x1ae, DISPLAYTOGGLE = 0x1af, SPELLCHECK = 0x1b0, LOGOFF = 0x1b1, DOLLAR = 0x1b2, EURO = 0x1b3, FRAMEBACK = 0x1b4, FRAMEFORWARD = 0x1b5, CONTEXT_MENU = 0x1b6, MEDIA_REPEAT = 0x1b7, ["10CHANNELSUP"] = 0x1b8, ["10CHANNELSDOWN"] = 0x1b9, IMAGES = 0x1ba, DEL_EOL = 0x1c0, DEL_EOS = 0x1c1, INS_LINE = 0x1c2, DEL_LINE = 0x1c3, FN = 0x1d0, FN_ESC = 0x1d1, FN_F1 = 0x1d2, FN_F2 = 0x1d3, FN_F3 = 0x1d4, FN_F4 = 0x1d5, FN_F5 = 0x1d6, FN_F6 = 0x1d7, FN_F7 = 0x1d8, FN_F8 = 0x1d9, FN_F9 = 0x1da, FN_F10 = 0x1db, FN_F11 = 0x1dc, FN_F12 = 0x1dd, FN_1 = 0x1de, FN_2 = 0x1df, FN_D = 0x1e0, FN_E = 0x1e1, FN_F = 0x1e2, FN_S = 0x1e3, FN_B = 0x1e4, BRL_DOT1 = 0x1f1, BRL_DOT2 = 0x1f2, BRL_DOT3 = 0x1f3, BRL_DOT4 = 0x1f4, BRL_DOT5 = 0x1f5, BRL_DOT6 = 0x1f6, BRL_DOT7 = 0x1f7, BRL_DOT8 = 0x1f8, BRL_DOT9 = 0x1f9, BRL_DOT10 = 0x1fa, NUMERIC_0 = 0x200, NUMERIC_1 = 0x201, NUMERIC_2 = 0x202, NUMERIC_3 = 0x203, NUMERIC_4 = 0x204, NUMERIC_5 = 0x205, NUMERIC_6 = 0x206, NUMERIC_7 = 0x207, NUMERIC_8 = 0x208, NUMERIC_9 = 0x209, NUMERIC_STAR = 0x20a, NUMERIC_POUND = 0x20b, CAMERA_FOCUS = 0x210, WPS_BUTTON = 0x211, TOUCHPAD_TOGGLE = 0x212, TOUCHPAD_ON = 0x213, TOUCHPAD_OFF = 0x214, CAMERA_ZOOMIN = 0x215, CAMERA_ZOOMOUT = 0x216, CAMERA_UP = 0x217, CAMERA_DOWN = 0x218, CAMERA_LEFT = 0x219, CAMERA_RIGHT = 0x21a, } c.KEY.SCREENLOCK = c.KEY.COFFEE c.KEY.HANGUEL = c.KEY.HANGEUL c.BTN = strflag { MISC = 0x100, ["0"] = 0x100, ["1"] = 0x101, ["2"] = 0x102, ["3"] = 0x103, ["4"] = 0x104, ["5"] = 0x105, ["6"] = 0x106, ["7"] = 0x107, ["8"] = 0x108, ["9"] = 0x109, MOUSE = 0x110, LEFT = 0x110, RIGHT = 0x111, MIDDLE = 0x112, SIDE = 0x113, EXTRA = 0x114, FORWARD = 0x115, BACK = 0x116, TASK = 0x117, JOYSTICK = 0x120, TRIGGER = 0x120, THUMB = 0x121, THUMB2 = 0x122, TOP = 0x123, TOP2 = 0x124, PINKIE = 0x125, BASE = 0x126, BASE2 = 0x127, BASE3 = 0x128, BASE4 = 0x129, BASE5 = 0x12a, BASE6 = 0x12b, DEAD = 0x12f, GAMEPAD = 0x130, A = 0x130, B = 0x131, C = 0x132, X = 0x133, Y = 0x134, Z = 0x135, TL = 0x136, TR = 0x137, TL2 = 0x138, TR2 = 0x139, SELECT = 0x13a, START = 0x13b, MODE = 0x13c, THUMBL = 0x13d, THUMBR = 0x13e, DIGI = 0x140, TOOL_PEN = 0x140, TOOL_RUBBER = 0x141, TOOL_BRUSH = 0x142, TOOL_PENCIL = 0x143, TOOL_AIRBRUSH = 0x144, TOOL_FINGER = 0x145, TOOL_MOUSE = 0x146, TOOL_LENS = 0x147, TOOL_QUINTTAP = 0x148, TOUCH = 0x14a, STYLUS = 0x14b, STYLUS2 = 0x14c, TOOL_DOUBLETAP = 0x14d, TOOL_TRIPLETAP = 0x14e, TOOL_QUADTAP = 0x14f, WHEEL = 0x150, GEAR_DOWN = 0x150, GEAR_UP = 0x151, TRIGGER_HAPPY = 0x2c0, TRIGGER_HAPPY1 = 0x2c0, TRIGGER_HAPPY2 = 0x2c1, TRIGGER_HAPPY3 = 0x2c2, TRIGGER_HAPPY4 = 0x2c3, TRIGGER_HAPPY5 = 0x2c4, TRIGGER_HAPPY6 = 0x2c5, TRIGGER_HAPPY7 = 0x2c6, TRIGGER_HAPPY8 = 0x2c7, TRIGGER_HAPPY9 = 0x2c8, TRIGGER_HAPPY10 = 0x2c9, TRIGGER_HAPPY11 = 0x2ca, TRIGGER_HAPPY12 = 0x2cb, TRIGGER_HAPPY13 = 0x2cc, TRIGGER_HAPPY14 = 0x2cd, TRIGGER_HAPPY15 = 0x2ce, TRIGGER_HAPPY16 = 0x2cf, TRIGGER_HAPPY17 = 0x2d0, TRIGGER_HAPPY18 = 0x2d1, TRIGGER_HAPPY19 = 0x2d2, TRIGGER_HAPPY20 = 0x2d3, TRIGGER_HAPPY21 = 0x2d4, TRIGGER_HAPPY22 = 0x2d5, TRIGGER_HAPPY23 = 0x2d6, TRIGGER_HAPPY24 = 0x2d7, TRIGGER_HAPPY25 = 0x2d8, TRIGGER_HAPPY26 = 0x2d9, TRIGGER_HAPPY27 = 0x2da, TRIGGER_HAPPY28 = 0x2db, TRIGGER_HAPPY29 = 0x2dc, TRIGGER_HAPPY30 = 0x2dd, TRIGGER_HAPPY31 = 0x2de, TRIGGER_HAPPY32 = 0x2df, TRIGGER_HAPPY33 = 0x2e0, TRIGGER_HAPPY34 = 0x2e1, TRIGGER_HAPPY35 = 0x2e2, TRIGGER_HAPPY36 = 0x2e3, TRIGGER_HAPPY37 = 0x2e4, TRIGGER_HAPPY38 = 0x2e5, TRIGGER_HAPPY39 = 0x2e6, TRIGGER_HAPPY40 = 0x2e7, } c.REL = strflag { X = 0x00, Y = 0x01, Z = 0x02, RX = 0x03, RY = 0x04, RZ = 0x05, HWHEEL = 0x06, DIAL = 0x07, WHEEL = 0x08, MISC = 0x09, MAX = 0x0f, } c.ABS = strflag { X = 0x00, Y = 0x01, Z = 0x02, RX = 0x03, RY = 0x04, RZ = 0x05, THROTTLE = 0x06, RUDDER = 0x07, WHEEL = 0x08, GAS = 0x09, BRAKE = 0x0a, HAT0X = 0x10, HAT0Y = 0x11, HAT1X = 0x12, HAT1Y = 0x13, HAT2X = 0x14, HAT2Y = 0x15, HAT3X = 0x16, HAT3Y = 0x17, PRESSURE = 0x18, DISTANCE = 0x19, TILT_X = 0x1a, TILT_Y = 0x1b, TOOL_WIDTH = 0x1c, VOLUME = 0x20, MISC = 0x28, MT_SLOT = 0x2f, MT_TOUCH_MAJOR = 0x30, MT_TOUCH_MINOR = 0x31, MT_WIDTH_MAJOR = 0x32, MT_WIDTH_MINOR = 0x33, MT_ORIENTATION = 0x34, MT_POSITION_X = 0x35, MT_POSITION_Y = 0x36, MT_TOOL_TYPE = 0x37, MT_BLOB_ID = 0x38, MT_TRACKING_ID = 0x39, MT_PRESSURE = 0x3a, MT_DISTANCE = 0x3b, MAX = 0x3f, } c.MSC = strflag { SERIAL = 0x00, PULSELED = 0x01, GESTURE = 0x02, RAW = 0x03, SCAN = 0x04, MAX = 0x07, } c.LED = strflag { NUML = 0x00, CAPSL = 0x01, SCROLLL = 0x02, COMPOSE = 0x03, KANA = 0x04, SLEEP = 0x05, SUSPEND = 0x06, MUTE = 0x07, MISC = 0x08, MAIL = 0x09, CHARGING = 0x0a, MAX = 0x0f, } c.REP = strflag { DELAY = 0x00, PERIOD = 0x01, MAX = 0x01, } c.SND = strflag { CLICK = 0x00, BELL = 0x01, TONE = 0x02, MAX = 0x07, } c.ID = strflag { BUS = 0, VENDOR = 1, PRODUCT = 2, VERSION = 3, } c.BUS = strflag { PCI = 0x01, ISAPNP = 0x02, USB = 0x03, HIL = 0x04, BLUETOOTH = 0x05, VIRTUAL = 0x06, ISA = 0x10, I8042 = 0x11, XTKBD = 0x12, RS232 = 0x13, GAMEPORT = 0x14, PARPORT = 0x15, AMIGA = 0x16, ADB = 0x17, I2C = 0x18, HOST = 0x19, GSC = 0x1A, ATARI = 0x1B, SPI = 0x1C, } c.MT_TOOL = strflag { FINGER = 0, PEN = 1, MAX = 1, } c.FF_STATUS = strflag { STOPPED = 0x00, PLAYING = 0x01, MAX = 0x01, } -- TODO note these are split into different categories eg EFFECT, WAVEFORM unclear how best to handle (FF_STATUS too?) c.FF = strflag { -- EFFECT RUMBLE = 0x50, PERIODIC = 0x51, CONSTANT = 0x52, SPRING = 0x53, FRICTION = 0x54, DAMPER = 0x55, INERTIA = 0x56, RAMP = 0x57, -- WAVEFORM SQUARE = 0x58, TRIANGLE = 0x59, SINE = 0x5a, SAW_UP = 0x5b, SAW_DOWN = 0x5c, CUSTOM = 0x5d, -- dev props GAIN = 0x60, AUTOCENTER = 0x61, } -- errors c.E = strflag(arch.E or { PERM = 1, NOENT = 2, SRCH = 3, INTR = 4, IO = 5, NXIO = 6, ["2BIG"] = 7, NOEXEC = 8, BADF = 9, CHILD = 10, AGAIN = 11, NOMEM = 12, ACCES = 13, FAULT = 14, NOTBLK = 15, BUSY = 16, EXIST = 17, XDEV = 18, NODEV = 19, NOTDIR = 20, ISDIR = 21, INVAL = 22, NFILE = 23, MFILE = 24, NOTTY = 25, TXTBSY = 26, FBIG = 27, NOSPC = 28, SPIPE = 29, ROFS = 30, MLINK = 31, PIPE = 32, DOM = 33, RANGE = 34, DEADLK = 35, NAMETOOLONG = 36, NOLCK = 37, NOSYS = 38, NOTEMPTY = 39, LOOP = 40, NOMSG = 42, IDRM = 43, CHRNG = 44, L2NSYNC = 45, L3HLT = 46, L3RST = 47, LNRNG = 48, UNATCH = 49, NOCSI = 50, L2HLT = 51, BADE = 52, BADR = 53, XFULL = 54, NOANO = 55, BADRQC = 56, BADSLT = 57, BFONT = 59, NOSTR = 60, NODATA = 61, TIME = 62, NOSR = 63, NONET = 64, NOPKG = 65, REMOTE = 66, NOLINK = 67, ADV = 68, SRMNT = 69, COMM = 70, PROTO = 71, MULTIHOP = 72, DOTDOT = 73, BADMSG = 74, OVERFLOW = 75, NOTUNIQ = 76, BADFD = 77, REMCHG = 78, LIBACC = 79, LIBBAD = 80, LIBSCN = 81, LIBMAX = 82, LIBEXEC = 83, ILSEQ = 84, RESTART = 85, STRPIPE = 86, USERS = 87, NOTSOCK = 88, DESTADDRREQ = 89, MSGSIZE = 90, PROTOTYPE = 91, NOPROTOOPT = 92, PROTONOSUPPORT= 93, SOCKTNOSUPPORT= 94, OPNOTSUPP = 95, PFNOSUPPORT = 96, AFNOSUPPORT = 97, ADDRINUSE = 98, ADDRNOTAVAIL = 99, NETDOWN = 100, NETUNREACH = 101, NETRESET = 102, CONNABORTED = 103, CONNRESET = 104, NOBUFS = 105, ISCONN = 106, NOTCONN = 107, SHUTDOWN = 108, TOOMANYREFS = 109, TIMEDOUT = 110, CONNREFUSED = 111, HOSTDOWN = 112, HOSTUNREACH = 113, ALREADY = 114, INPROGRESS = 115, STALE = 116, UCLEAN = 117, NOTNAM = 118, NAVAIL = 119, ISNAM = 120, REMOTEIO = 121, DQUOT = 122, NOMEDIUM = 123, MEDIUMTYPE = 124, CANCELED = 125, NOKEY = 126, KEYEXPIRED = 127, KEYREVOKED = 128, KEYREJECTED = 129, OWNERDEAD = 130, NOTRECOVERABLE= 131, RFKILL = 132, }) -- ppc only redefines DEADLOCK, mips redefines all if arch.EDEADLOCK then c.E.DEADLOCK = arch.EDEADLOCK end -- alternate names c.EALIAS = { WOULDBLOCK = c.E.AGAIN, NOATTR = c.E.NODATA, NOTSUP = c.E.OPNOTSUPP, } -- for most architectures this is an alias, but not ppc, mips if not c.E.DEADLOCK then c.EALIAS.DEADLOCK = c.E.DEADLK end c.SWAP_FLAG = swapflags { PREFER = 0x8000, PRIO_MASK = 0x7fff, PRIO_SHIFT = 0, DISCARD = 0x10000, } --c.FUTEX = -- iptables/xtables c.NF = strflag { DROP = 0, ACCEPT = 1, STOLEN = 2, QUEUE = 3, REPEAT = 4, STOP = 5, } -- misc values, just gathered in a table as better namespacing c.XT = strflag { FUNCTION_MAXNAMELEN = 30, EXTENSION_MAXNAMELEN = 29, TABLE_MAXNAMELEN = 32, } local IPT_BASE_CTL = 64 c.IPT_SO_SET = strflag { REPLACE = IPT_BASE_CTL, ADD_COUNTERS = IPT_BASE_CTL + 1, } c.IPT_SO_GET = strflag { INFO = IPT_BASE_CTL, ENTRIES = IPT_BASE_CTL + 1, REVISION_MATCH = IPT_BASE_CTL + 2, REVISION_TARGET = IPT_BASE_CTL + 3, } c.MPOL_MODE = multiflags { DEFAULT = 0, PREFERRED = 1, BIND = 2, INTERLEAVE = 3, LOCAL = 4, -- TODO: Only the following two flags can be ORed. STATIC_NODES = 0x80000000, RELATIVE_NODES = 0x40000000, } c.MPOL_FLAG = multiflags { NODE = 1, ADDR = 2, MEMS_ALLOWED = 4 } c.SCHED = multiflags { NORMAL = 0, OTHER = 0, FIFO = 1, RR = 2, BATCH = 3, -- ISO IDLE = 5, RESET_ON_FORK = 0x40000000, -- TODO only this flag can be ORed } c.TUN_READQ = strflag { SIZE = 500, } c.TUN = multiflags { TUN_DEV = 0x0001, TAP_DEV = 0x0002, TYPE_MASK = 0x000f, FASYNC = 0x0010, NOCHECKSUM = 0x0020, NO_PI = 0x0040, ONE_QUEUE = 0x0080, PERSIST = 0x0100, VNET_HDR = 0x0200, TAP_MQ = 0x0400, } -- note that these are IFF_ but that is a duplicated prefix so using this. -- These are valid options for struct ifreq flags, while the other IFF_ are for ifinfo c.IFREQ = multiflags { -- for tun tap interfaces TUN = 0x0001, TAP = 0x0002, NO_PI = 0x1000, ONE_QUEUE = 0x2000, VNET_HDR = 0x4000, TUN_EXCL = 0x8000, MULTI_QUEUE = 0x0100, ATTACH_QUEUE = 0x0200, DETACH_QUEUE = 0x0400, -- for bridge interfaces SLAVE_NEEDARP = 0x40, ISATAP = 0x80, MASTER_ARPMON = 0x100, WAN_HDLC = 0x200, XMIT_DST_RELEASE = 0x400, DONT_BRIDGE = 0x800, DISABLE_NETPOLL = 0x1000, MACVLAN_PORT = 0x2000, BRIDGE_PORT = 0x4000, OVS_DATAPATH = 0x8000, TX_SKB_SHARING = 0x10000, UNICAST_FLT = 0x20000, } c.TUN_F = multiflags { CSUM = 0x01, TSO4 = 0x02, TSO6 = 0x04, TSO_ECN = 0x08, UFO = 0x10, } c.TUN_PKT = strflag { STRIP = 0x0001, } c.TUN_FLT = strflag { ALLMULTI = 0x0001, } c.PC = strflag { LINK_MAX = 0, MAX_CANON = 1, MAX_INPUT = 2, NAME_MAX = 3, PATH_MAX = 4, PIPE_BUF = 5, CHOWN_RESTRICTED = 6, NO_TRUNC = 7, VDISABLE = 8, SYNC_IO = 9, ASYNC_IO = 10, PRIO_IO = 11, SOCK_MAXBUF = 12, FILESIZEBITS = 13, REC_INCR_XFER_SIZE= 14, REC_MAX_XFER_SIZE = 15, REC_MIN_XFER_SIZE = 16, REC_XFER_ALIGN = 17, ALLOC_SIZE_MIN = 18, SYMLINK_MAX = 19, ["2_SYMLINKS"] = 20, } c.RUSAGE = strflag { SELF = 0, CHILDREN = -1, BOTH = -2, THREAD = 1, } -- waitpid and wait4 pid c.WAIT = strflag { ANY = -1, MYPGRP = 0, } -- virtio functions c.VIRTIO = strflag { PCI_HOST_FEATURES = 0, PCI_GUEST_FEATURES = 4, PCI_QUEUE_PFN = 8, PCI_QUEUE_NUM = 12, PCI_QUEUE_SEL = 14, PCI_QUEUE_NOTIFY = 16, PCI_STATUS = 18, PCI_ISR = 19, PCI_ISR_CONFIG = 0x2, MSI_CONFIG_VECTOR = 20, MSI_QUEUE_VECTOR = 22, MSI_NO_VECTOR = 0xffff, PCI_ABI_VERSION = 0, PCI_QUEUE_ADDR_SHIFT = 12, PCI_VRING_ALIGN = 4096, -- TODO VIRTIO_PCI_CONFIG_OFF(msix_enabled) ((msix_enabled) ? 24 : 20) } -- from linux/pci_regs.h c.PCI = strflag { VENDOR_ID = 0x00, DEVICE_ID = 0x02, COMMAND = 0x04, STATUS = 0x06, CLASS_REVISION = 0x08, REVISION_ID = 0x08, CLASS_PROG = 0x09, CLASS_DEVICE = 0x0a, CACHE_LINE_SIZE = 0x0c, LATENCY_TIMER = 0x0d, HEADER_TYPE = 0x0e, CACHE_LINE_SIZE = 0x0c, LATENCY_TIMER = 0x0d, HEADER_TYPE = 0x0e, BIST = 0x0f, BASE_ADDRESS_0 = 0x10, BASE_ADDRESS_1 = 0x14, BASE_ADDRESS_2 = 0x18, BASE_ADDRESS_3 = 0x1c, BASE_ADDRESS_4 = 0x20, BASE_ADDRESS_5 = 0x24, -- Header type 0 (Normal) CARDBUS_CIS = 0x28, SUBSYSTEM_VENDOR_ID= 0x2c, SUBSYSTEM_ID = 0x2e, ROM_ADDRESS = 0x30, CAPABILITY_LIST = 0x34, INTERRUPT_LINE = 0x3c, INTERRUPT_PIN = 0x3d, MIN_GNT = 0x3e, MAX_LAT = 0x3f, -- Header type 1 (PCI-to-PCI bridges) PRIMARY_BUS = 0x18, SECONDARY_BUS = 0x19, SUBORDINATE_BUS = 0x1a, SEC_LATENCY_TIMER = 0x1b, IO_BASE = 0x1c, IO_LIMIT = 0x1d, SEC_STATUS = 0x1e, MEMORY_BASE = 0x20, MEMORY_LIMIT = 0x22, PREF_MEMORY_BASE = 0x24, PREF_MEMORY_LIMIT = 0x26, PREF_BASE_UPPER32 = 0x28, PREF_LIMIT_UPPER32 = 0x2c, IO_BASE_UPPER16 = 0x30, IO_LIMIT_UPPER16 = 0x32, ROM_ADDRESS1 = 0x38, BRIDGE_CONTROL = 0x3e, -- Header type 2 (CardBus bridges) CB_CAPABILITY_LIST = 0x14, CB_SEC_STATUS = 0x16, CB_PRIMARY_BUS = 0x18, CB_CARD_BUS = 0x19, CB_SUBORDINATE_BUS = 0x1a, CB_LATENCY_TIMER = 0x1b, CB_MEMORY_BASE_0 = 0x1c, CB_MEMORY_LIMIT_0 = 0x20, CB_MEMORY_BASE_1 = 0x24, CB_MEMORY_LIMIT_1 = 0x28, CB_IO_BASE_0 = 0x2c, CB_IO_BASE_0_HI = 0x2e, CB_IO_LIMIT_0 = 0x30, CB_IO_LIMIT_0_HI = 0x32, CB_IO_BASE_1 = 0x34, CB_IO_BASE_1_HI = 0x36, CB_IO_LIMIT_1 = 0x38, CB_IO_LIMIT_1_HI = 0x3a, CB_BRIDGE_CONTROL = 0x3e, CB_SUBSYSTEM_VENDOR_ID = 0x40, CB_SUBSYSTEM_ID = 0x42, CB_LEGACY_MODE_BASE = 0x44, } -- unclear how best to group these, maybe just put everything in PCI and let app fix it c.PCI_BASE_ADDRESS = strflag { SPACE = 0x01, SPACE_IO = 0x01, SPACE_MEMORY = 0x00, MEM_TYPE_MASK = 0x06, MEM_TYPE_32 = 0x00, MEM_TYPE_1M = 0x02, MEM_TYPE_64 = 0x04, MEM_PREFETCH = 0x08, --MEM_MASK (~0x0fUL) --IO_MASK (~0x03UL) } c.TCP = strflag { NODELAY = 1, MAXSEG = 2, CORK = 3, KEEPIDLE = 4, KEEPINTVL = 5, KEEPCNT = 6, SYNCNT = 7, LINGER2 = 8, DEFER_ACCEPT = 9, WINDOW_CLAMP = 10, INFO = 11, QUICKACK = 12, CONGESTION = 13, MD5SIG = 14, THIN_LINEAR_TIMEOUTS= 16, THIN_DUPACK = 17, USER_TIMEOUT = 18, REPAIR = 19, REPAIR_QUEUE = 20, QUEUE_SEQ = 21, REPAIR_OPTIONS = 22, FASTOPEN = 23, TIMESTAMP = 24, } -- ipv6 sockopts c.IPV6 = strflag { ADDRFORM = 1, ["2292PKTINFO"] = 2, ["2292HOPOPTS"] = 3, ["2292DSTOPTS"] = 4, ["2292RTHDR"] = 5, ["2292PKTOPTIONS"]= 6, CHECKSUM = 7, ["2292HOPLIMIT"] = 8, NEXTHOP = 9, AUTHHDR = 10, FLOWINFO = 11, UNICAST_HOPS = 16, MULTICAST_IF = 17, MULTICAST_HOPS = 18, MULTICAST_LOOP = 19, ADD_MEMBERSHIP = 20, DROP_MEMBERSHIP = 21, ROUTER_ALERT = 22, MTU_DISCOVER = 23, MTU = 24, RECVERR = 25, V6ONLY = 26, JOIN_ANYCAST = 27, LEAVE_ANYCAST = 28, } -- need to use tobit to make sure within int range c.LINUX_REBOOT = strflag { MAGIC1 = tobit(0xfee1dead), MAGIC2 = tobit(672274793), MAGIC2A = tobit(85072278), MAGIC2B = tobit(369367448), MAGIC2C = tobit(537993216), } c.GRND = multiflags { NONBLOCK = 0x0001, RANDOM = 0x0002, } c.MFD = multiflags { CLOEXEC = 0x0001, ALLOW_SEALING = 0x0002, } return c
apache-2.0
Kosmos82/kosmosdarkstar
scripts/globals/items/cup_of_chamomile_tea.lua
18
1369
----------------------------------------- -- ID: 4603 -- Item: cup_of_chamomile_tea -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic 8 -- Vitality -2 -- Charisma 2 -- Magic Regen While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4603); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 8); target:addMod(MOD_VIT, -2); target:addMod(MOD_CHR, 2); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 8); target:delMod(MOD_VIT, -2); target:delMod(MOD_CHR, 2); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
m13790115/puker
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
Kosmos82/kosmosdarkstar
scripts/zones/Port_Bastok/npcs/Rajesh.lua
13
1393
----------------------------------- -- Area: Port Bastok -- NPC: Rajesh -- @zone 236 -- @pos -62 1 -8 ----------------------------------- package.loaded["scripts/zones/Port_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/zones/Port_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:hasKeyItem(AIRSHIP_PASS) == true and player:getGil() >= 200) then player:startEvent(0x008d); else player:startEvent(0x008e); end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x008d and option == 0) then X = player:getXPos(); if (X >= -58 and X <= -55) then player:delGil(200); end end end;
gpl-3.0
mikroskeem/advanced-sandbox
gamemode/spawnmenu/controls/ctrlcolor.lua
4
2384
-- -- ___ ___ _ _ _ __ _ ___ ___ __ __ -- |_ _|| __| / \ | \_/ | / _| / \ | o \ o \\ V / -- | | | _| | o || \_/ | ( |_n| o || / / \ / -- |_| |___||_n_||_| |_| \__/|_n_||_|\\_|\\ |_| 2009 -- -- local PANEL = {} AccessorFunc( PANEL, "m_ConVarR", "ConVarR" ) AccessorFunc( PANEL, "m_ConVarG", "ConVarG" ) AccessorFunc( PANEL, "m_ConVarB", "ConVarB" ) AccessorFunc( PANEL, "m_ConVarA", "ConVarA" ) local ColorRows = 16 --[[--------------------------------------------------------- Name: Init -----------------------------------------------------------]] function PANEL:Init() self.Mixer = vgui.Create( "DColorMixer", self ) self.Mixer:Dock( FILL ) self:SetTall( 230 ) end --[[--------------------------------------------------------- Name: PerformLayout -----------------------------------------------------------]] function PANEL:PerformLayout( x, y ) -- We try to avoid the ugly gap on the right. -- This seems a bit heavy handed to be calling in PerformLayout. self.Mixer.Palette:SetButtonSize( self:GetWide() / ColorRows ) end --[[--------------------------------------------------------- Name: SetLabel -----------------------------------------------------------]] function PANEL:SetLabel( text ) self.Mixer:SetLabel( text ) end --[[--------------------------------------------------------- Name: Paint -----------------------------------------------------------]] function PANEL:Paint() -- Invisible background! end --[[--------------------------------------------------------- Name: ConVarR -----------------------------------------------------------]] function PANEL:SetConVarR( cvar ) self.Mixer:SetConVarR( cvar ) end --[[--------------------------------------------------------- Name: ConVarG -----------------------------------------------------------]] function PANEL:SetConVarG( cvar ) self.Mixer:SetConVarG( cvar ) end --[[--------------------------------------------------------- Name: ConVarB -----------------------------------------------------------]] function PANEL:SetConVarB( cvar ) self.Mixer:SetConVarB( cvar ) end --[[--------------------------------------------------------- Name: ConVarA -----------------------------------------------------------]] function PANEL:SetConVarA( cvar ) self.Mixer:SetConVarA( cvar ) end vgui.Register( "CtrlColor", PANEL, "DPanel" )
mit
Kosmos82/kosmosdarkstar
scripts/zones/Kuftal_Tunnel/TextIDs.lua
15
1264
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory ITEM_OBTAINED = 6384; -- Obtained: <item> GIL_OBTAINED = 6385; -- Obtained <number> gil KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem> FISHING_MESSAGE_OFFSET = 7204; -- You can't fish here NOTHING_OUT_OF_ORDINARY = 6398; -- There is nothing out of the ordinary here. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7306; -- You unlock the chest! CHEST_FAIL = 7307; -- Fails to open the chest. CHEST_TRAP = 7308; -- The chest was trapped! CHEST_WEAK = 7309; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7310; -- The chest was a mimic! CHEST_MOOGLE = 7311; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7312; -- The chest was but an illusion... CHEST_LOCKED = 7313; -- The chest appears to be locked. -- Other Dialog FELL = 7324; -- The piece of wood fell off the cliff! EVIL = 7325; -- You sense an evil presence... FISHBONES = 7339; -- Fish bones lie scattered about the area... -- conquest Base CONQUEST_BASE = 7045; -- Tallying conquest results...
gpl-3.0
TannerRogalsky/haex
lib/meshed_batch.lua
3
2312
-- local image = self.preloaded_images['brick.jpg'] -- batch = g.newSpriteBatch(image, 4) -- batch:add(0, 0, 0, 100 / image:getHeight()) -- batch:add(100, 100, 0, 100 / image:getHeight()) -- batch:add(0, 200, 0, 100 / image:getHeight()) -- batch:add(300, 0, 0, 100 / image:getHeight()) -- local mesh, attributes = newMeshedBatch({ -- {"VertexColor", "byte", 4}, -- {"CoolVertexAttribute", "float", 2} -- }, batch) -- local shader = g.newShader('shaders/mesh_shader.glsl') -- g.setShader(shader) -- local function update_attrs() -- for i = 1, mesh:getVertexCount() do -- mesh:setVertexAttribute(i, attributes['VertexColor'], math.random(255), math.random(255), math.random(255)) -- mesh:setVertexAttribute(i, attributes['CoolVertexAttribute'], math.random(100), math.random(100)) -- end -- end -- timer = cron.every(0.1, update_attrs) local function dup(num, verts) local new = {} for i=1,num do for _,vert in ipairs(verts) do table.insert(new, vert) end end return new end local function contains(vertex_format, attributeName) local does_contain = false for i,attributeFormat in ipairs(vertex_format) do if attributeFormat[1] == attributeName then return true end end return does_contain end local function merge(table_a, table_b, ...) for i,v in ipairs(table_b) do if not contains(table_a, v[1]) then table.insert(table_a, v) end end if ... then return merge(table_a, ...) else return table_a end end local DEFAULT_VERTEX_FORMAT = { {"VertexPosition", "float", 2}, -- The x,y position of each vertex. {"VertexTexCoord", "float", 2}, -- The u,v texture coordinates of each vertex. {"VertexColor", "byte", 4}, -- The r,g,b,a color of each vertex. } local function newMeshedBatch(vertex_format, sprite_batch) local w, h = 1, 1 local vertices = { { 0, 0, 0, 0 }, { w, 0, 1, 0 }, { w, h, 1, 1 }, { 0, h, 0, 1 }, } local vf = merge({}, vertex_format, DEFAULT_VERTEX_FORMAT) local mesh = love.graphics.newMesh(vf, dup(sprite_batch:getBufferSize(), vertices)) local attributes = {} for i, attr in ipairs(vertex_format) do local name = attr[1] attributes[name] = i sprite_batch:attachAttribute(name, mesh) end return mesh, attributes end return newMeshedBatch
mit
Kosmos82/kosmosdarkstar
scripts/zones/Western_Altepa_Desert/npcs/_3h5.lua
13
1873
----------------------------------- -- Area: Western Altepa Desert -- NPC: _3h5 (Ruby Column) -- Notes: Mechanism for Altepa Gate -- @pos 59 10 -104 125 ----------------------------------- package.loaded["scripts/zones/Western_Altepa_Desert/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Western_Altepa_Desert/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local RubyID = npc:getID(); local Ruby = npc:getAnimation(); local Topaz = GetNPCByID(RubyID+1):getAnimation(); local Emerald = GetNPCByID(RubyID+2):getAnimation(); local Sapphire = GetNPCByID(RubyID+3):getAnimation(); if (Ruby ~= 8) then npc:setAnimation(8); GetNPCByID(RubyID-4):setAnimation(8); else player:messageSpecial(DOES_NOT_RESPOND); end if (Emerald == 8 and Sapphire == 8 and Topaz == 8) then local rand = math.random(15,30); local randT = rand * 60; -- Add timer for the door GetNPCByID(RubyID-5):openDoor(randT); -- Add same timer for the 4 center lights GetNPCByID(RubyID-4):openDoor(randT); GetNPCByID(RubyID-3):openDoor(randT); GetNPCByID(RubyID-2):openDoor(randT); GetNPCByID(RubyID-1):openDoor(randT); 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
aStonedPenguin/fprp
gamemode/modules/chat/sh_chatcommands.lua
1
3226
local plyMeta = FindMetaTable("Player"); fprp.chatCommands = fprp.chatCommands or {} local validChatCommand = { command = isstring, description = isstring, condition = fn.FOr{fn.Curry(fn.Eq, 2)(nil), isfunction}, delay = isnumber } local checkChatCommand = function(tbl) for k,v in pairs(validChatCommand) do if not validChatCommand[k](tbl[k]) then return false, k end end return true end function fprp.declareChatCommand(tbl) local valid, element = checkChatCommand(tbl); if not valid then fprp.error("Incorrect chat command! " .. element .. " is invalid!", 2); end tbl.command = string.lower(tbl.command); fprp.chatCommands[tbl.command] = fprp.chatCommands[tbl.command] or tbl for k, v in pairs(tbl) do fprp.chatCommands[tbl.command][k] = v end end function fprp.removeChatCommand(command) fprp.chatCommands[string.lower(command)] = nil end function fprp.chatCommandAlias(command, ...) local name for k, v in pairs{...} do name = string.lower(v); fprp.chatCommands[name] = table.Copy(fprp.chatCommands[command]); fprp.chatCommands[name].command = name end end function fprp.getChatCommand(command) return fprp.chatCommands[string.lower(command)] end function fprp.getChatCommands() return fprp.chatCommands end function fprp.getSortedChatCommands() local tbl = fn.Compose{table.ClearKeys, table.Copy, fprp.getChatCommands}(); table.SortByMember(tbl, "command", true); return tbl end -- chat commands that have been defined, but not declared fprp.getIncompleteChatCommands = fn.Curry(fn.Filter, 3)(fn.Compose{fn.Not, checkChatCommand})(fprp.chatCommands); /*--------------------------------------------------------------------------- Chat commands ---------------------------------------------------------------------------*/ fprp.declareChatCommand{ command = "pm", description = "Send a private message to someone.", delay = 1.5 } fprp.declareChatCommand{ command = "w", description = "Say something in whisper voice.", delay = 1.5 } fprp.declareChatCommand{ command = "y", description = "Yell something out loud.", delay = 1.5 } fprp.declareChatCommand{ command = "me", description = "Chat roleplay to say you're doing things that you can't show otherwise.", delay = 1.5 } fprp.declareChatCommand{ command = "/", description = "Global server chat.", delay = 1.5 } fprp.declareChatCommand{ command = "a", description = "Global server chat.", delay = 1.5 } fprp.declareChatCommand{ command = "ooc", description = "Global server chat.", delay = 1.5 } fprp.declareChatCommand{ command = "advert", description = "Advertise something to everyone in the server.", delay = 1.5 } fprp.declareChatCommand{ command = "broadcast", description = "Broadcast something as a mayor.", delay = 1.5, condition = plyMeta.isMayor } fprp.declareChatCommand{ command = "channel", description = "Tune into a radio channel.", delay = 1.5 } fprp.declareChatCommand{ command = "radio", description = "Say something through the radio.", delay = 1.5 } fprp.declareChatCommand{ command = "g", description = "Group chat.", delay = 1.5 } fprp.declareChatCommand{ command = "credits", description = "Send the fprp credits to someone.", delay = 1.5 }
mit
hadow/OpenRA
mods/ts/maps/fields-of-green/fields-of-green.lua
9
3041
NForce = { "e1", "e1", "e1", "e3", "cyborg", "cyborg" } NForcePath = { NodW.Location, GDIBase.Location } NForceInterval = 5 VNForce = { "bike", "bike", "bggy", "bggy", "e1", "e1", "e3" } VNForcePath = { South.Location, GDIBase.Location } VNForceInterval = 15 GForce = { "e1", "e1", "e1", "e1", "e2", "e1", "e2" } GForcePath = { GDIW.Location, NodBase.Location } GForceInterval = 5 VGForce = { "e2", "smech", "smech", "e1", "e1", "apc" } VGForcePath = { North.Location, NodBase.Location } VGForceInterval = 15 ProducedUnitTypes = { { nodhand1, { "e1", "e3" } }, { gdibar1, { "e1", "e2" } } } ProduceUnits = function(t) local factory = t[1] if not factory.IsDead then local unitType = t[2][Utils.RandomInteger(1, #t[2] + 1)] factory.Wait(Actor.BuildTime(unitType)) factory.Produce(unitType) factory.CallFunc(function() ProduceUnits(t) end) end end SetupFactories = function() Utils.Do(ProducedUnitTypes, function(pair) Trigger.OnProduction(pair[1], function(_, a) BindActorTriggers(a) end) end) end SetupInvulnerability = function() Utils.Do(Map.NamedActors, function(actor) if actor.HasProperty("AcceptsUpgrade") and actor.AcceptsUpgrade("unkillable") then actor.GrantUpgrade("unkillable") end end) end SendNodInfantry = function() local units = Reinforcements.Reinforce(nod, NForce, NForcePath, NForceInterval) Utils.Do(units, function(unit) BindActorTriggers(unit) end) Trigger.AfterDelay(DateTime.Seconds(60), SendNodInfantry) end SendNodVehicles = function() local units = Reinforcements.Reinforce(nod, VNForce, VNForcePath, VNForceInterval) Utils.Do(units, function(unit) BindActorTriggers(unit) end) Trigger.AfterDelay(DateTime.Seconds(110), SendNodVehicles) end SendGDIInfantry = function() local units = Reinforcements.Reinforce(gdi, GForce, GForcePath, GForceInterval) Utils.Do(units, function(unit) BindActorTriggers(unit) end) Trigger.AfterDelay(DateTime.Seconds(60), SendGDIInfantry) end SendGDIVehicles = function() local units = Reinforcements.Reinforce(gdi, VGForce, VGForcePath, VGForceInterval) Utils.Do(units, function(unit) BindActorTriggers(unit) end) Trigger.AfterDelay(DateTime.Seconds(110), SendGDIVehicles) end BindActorTriggers = function(a) if a.HasProperty("Hunt") then Trigger.OnIdle(a, a.Hunt) end if a.HasProperty("HasPassengers") then Trigger.OnDamaged(a, function() if a.HasPassengers then a.Stop() a.UnloadPassengers() end end) end end WorldLoaded = function() nod = Player.GetPlayer("Nod") gdi = Player.GetPlayer("GDI") SetupFactories() SetupInvulnerability() Utils.Do(ProducedUnitTypes, ProduceUnits) SendNodInfantry() Trigger.AfterDelay(DateTime.Seconds(50), SendNodVehicles) SendGDIInfantry() Trigger.AfterDelay(DateTime.Seconds(70), SendGDIVehicles) end
gpl-3.0
wingo/snabbswitch
src/program/snabbnfv/neutron_sync_agent/neutron_sync_agent.lua
5
1720
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local lib = require("core.lib") local syscall = require("syscall") local usage = require("program.snabbnfv.neutron_sync_agent.README_inc") local script = require("program.snabbnfv.neutron_sync_agent.neutron_sync_agent_sh_inc") local long_opts = { ["neutron-dir"] = "d", ["snabb-dir"] = "s", ["tmp-dir"] = "t", ["sync-host"] = "h", ["sync-port"] = "P", ["sync-path"] = "p", ["interval"] = "i", ["help"] = "H" } function run (args) local conf = { ["NEUTRON_DIR"] = os.getenv("NEUTRON_DIR"), ["SNABB_DIR"] = os.getenv("SNABB_DIR"), ["TMP_DIR"] = os.getenv("TMP_DIR"), ["NEUTRON2SNABB"] = os.getenv("NEUTRON2SNABB"), ["SYNC_HOST"] = os.getenv("SYNC_HOST"), ["SYNC_PORT"] = os.getenv("SYNC_PORT"), ["SYNC_PATH"] = os.getenv("SYNC_PATH"), ["SYNC_INTERVAL"] = os.getenv("SYNC_INTERVAL") } local opt = {} function opt.d (arg) conf["NEUTRON_DIR"] = arg end function opt.s (arg) conf["SNABB_DIR"] = arg end function opt.t (arg) conf["TMP_DIR"] = arg end function opt.h (arg) conf["SYNC_HOST"] = arg end function opt.P (arg) conf["SYNC_PORT"] = arg end function opt.p (arg) conf["SYNC_PATH"] = arg end function opt.i (arg) conf["SYNC_INTERVAL"] = arg end function opt.H (arg) print(usage) main.exit(1) end args = lib.dogetopt(args, opt, "d:s:t:h:P:p:i:H", long_opts) local env = {} for key, value in pairs(conf) do table.insert(env, key.."="..value) end syscall.execve("/bin/bash", {"/bin/bash", "-c", script}, env) end
apache-2.0
Kosmos82/kosmosdarkstar
scripts/zones/Yuhtunga_Jungle/npcs/Blue_Rafflesia.lua
15
6345
----------------------------------- -- Area: Yuhtunga Jungle -- NPC: Blue Rafflesia -- Used in quest Even More Gullible Travels -- @pos -468.876 -1 220.247 123 <many> ----------------------------------- package.loaded["scripts/zones/Yuhtunga_Jungle/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Yuhtunga_Jungle/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local evenmoreTravelsStatus = player:getQuestStatus(OUTLANDS, EVEN_MORE_GULLIBLES_TRAVELS) local questprogress = player:getVar("EVEN_MORE_GULLIBLES_PROGRESS"); local scentDay = player:getVar("RafflesiaScentDay"); local currentDay = VanadielDayOfTheYear(); local scentReady = ((scentDay < currentDay) or (scentDay > currentDay and player:getVar("RafflesiaScentYear") < VanadielYear())); local npcId = npc:getID(); if (npcId == 17281586) then if (evenmoreTravelsStatus == QUEST_ACCEPTED and questprogress == 1 and player:getVar("FirstBlueRafflesiaCS") == 0) then -- Player is on quest, first time. player:startEvent(0x0015); elseif (evenmoreTravelsStatus == QUEST_COMPLETED and scentReady == true and player:getVar("BathedInScent") == 0 and player:getVar("FirstBlueRafflesiaCS") == 0) then -- Repeating player:startEvent(0x0015); else player:messageSpecial(FLOWER_BLOOMING); end elseif (npcId == 17281587) then if (evenmoreTravelsStatus == QUEST_ACCEPTED and questprogress == 1 and player:getVar("SecondBlueRafflesiaCS") == 0) then player:startEvent(0x0016); elseif (evenmoreTravelsStatus == QUEST_COMPLETED and scentReady == true and player:getVar("BathedInScent") == 0 and player:getVar("SecondBlueRafflesiaCS") == 0) then player:startEvent(0x0016); else player:messageSpecial(FLOWER_BLOOMING); end elseif (npcId == 17281588) then if (evenmoreTravelsStatus == QUEST_ACCEPTED and questprogress == 1 and player:getVar("ThirdBlueRafflesiaCS") == 0) then player:startEvent(0x0017); elseif (evenmoreTravelsStatus == QUEST_COMPLETED and scentReady == true and player:getVar("BathedInScent") == 0 and player:getVar("ThirdBlueRafflesiaCS") == 0) then player:startEvent(0x0017); else player:messageSpecial(FLOWER_BLOOMING); end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("OPTION: %u",option); local evenmoreTravelsStatus = player:getQuestStatus(OUTLANDS, EVEN_MORE_GULLIBLES_TRAVELS) -- Set BathedInScent to 1 if they touched all 3 Rafflesia for EVEN_MORE_GULLIBLES_TRAVELS which opens the quest The Opo-Opo and I if (csid == 0x0015 and option == 1) then if (player:getVar("SecondBlueRafflesiaCS") == 1 and player:getVar("ThirdBlueRafflesiaCS") == 1) then -- This is 3rd Rafflessia clicked, progressing. player:setVar("SecondBlueRafflesiaCS", 0); player:setVar("ThirdBlueRafflesiaCS", 0); player:setVar("BathedInScent", 1); player:setVar("RafflesiaScentDay",VanadielDayOfTheYear()); player:setVar("RafflesiaScentYear",VanadielYear()); player:addItem(1144); -- Rafflesia Nectar player:messageSpecial(ITEM_OBTAINED,1144); player:messageSpecial(FEEL_DIZZY); -- You feel slightly dizzy. You must have breathed in too much of the pollen. if (evenmoreTravelsStatus == QUEST_ACCEPTED) then player:setVar("EVEN_MORE_GULLIBLES_PROGRESS", 2); end else player:setVar("FirstBlueRafflesiaCS", 1); player:addItem(1144); -- Rafflesia Nectar player:messageSpecial(ITEM_OBTAINED,1144); end elseif (csid == 0x0016 and option == 1) then if (player:getVar("FirstBlueRafflesiaCS") == 1 and player:getVar("ThirdBlueRafflesiaCS") == 1) then player:setVar("FirstBlueRafflesiaCS", 0); player:setVar("ThirdBlueRafflesiaCS", 0); player:setVar("BathedInScent", 1); player:setVar("RafflesiaScentDay",VanadielDayOfTheYear()); player:setVar("RafflesiaScentYear",VanadielYear()); player:addItem(1144); -- Rafflesia Nectar player:messageSpecial(ITEM_OBTAINED,1144); player:messageSpecial(FEEL_DIZZY); -- You feel slightly dizzy. You must have breathed in too much of the pollen. if (evenmoreTravelsStatus == QUEST_ACCEPTED) then player:setVar("EVEN_MORE_GULLIBLES_PROGRESS", 2); end else player:setVar("SecondBlueRafflesiaCS", 1); player:addItem(1144); -- Rafflesia Nectar player:messageSpecial(ITEM_OBTAINED,1144); end elseif (csid == 0x0017 and option == 1) then if (player:getVar("FirstBlueRafflesiaCS") == 1 and player:getVar("SecondBlueRafflesiaCS") == 1) then player:setVar("FirstBlueRafflesiaCS", 0); player:setVar("SecondBlueRafflesiaCS", 0); player:setVar("BathedInScent", 1); player:setVar("RafflesiaScentDay",VanadielDayOfTheYear()); player:setVar("RafflesiaScentYear",VanadielYear()); player:addItem(1144); -- Rafflesia Nectar player:messageSpecial(ITEM_OBTAINED,1144); player:messageSpecial(FEEL_DIZZY); -- You feel slightly dizzy. You must have breathed in too much of the pollen. if (evenmoreTravelsStatus == QUEST_ACCEPTED) then player:setVar("EVEN_MORE_GULLIBLES_PROGRESS", 2); end else player:setVar("ThirdBlueRafflesiaCS", 1); player:addItem(1144); -- Rafflesia Nectar player:messageSpecial(ITEM_OBTAINED,1144); end end end;
gpl-3.0
Kosmos82/kosmosdarkstar
scripts/globals/items/galette_des_rois.lua
18
1349
----------------------------------------- -- ID: 5875 -- Item: Galette Des Rois -- Food Effect: 180 Min, All Races ----------------------------------------- -- MP % 1 -- Intelligence +2 -- Random Jewel ----------------------------------------- require("scripts/globals/status"); require("scripts/zones/Bastok_Mines/TextIDs"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD)) then result = 246; end if (target:getFreeSlotsCount() == 0) then result = 308; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,5875); local rand = math.random(784,815); target:addItem(rand); -- Random Jewel end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MPP, 1); target:addMod(MOD_INT, 2); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MPP, 1); target:delMod(MOD_INT, 2); end;
gpl-3.0
ZDragonKNight/ZZZZ
plugins/stats.lua
81
4126
do -- Returns a table with `name` and `msgs` local function get_msgs_user_chat(user_id, chat_id) local user_info = {} local uhash = 'user:'..user_id local user = redis:hgetall(uhash) local um_hash = 'msgs:'..user_id..':'..chat_id user_info.msgs = tonumber(redis:get(um_hash) or 0) user_info.name = user_print_name(user)..' ['..user_id..']' return user_info end local function chat_stats(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end local file = io.open("./groups/lists/"..chat_id.."stats.txt", "w") file:write(text) file:flush() file:close() send_document("chat#id"..chat_id,"./groups/lists/"..chat_id.."stats.txt", ok_cb, false) return --text end local function chat_stats2(chat_id) -- Users on chat local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) local users_info = {} -- Get user info for i = 1, #users do local user_id = users[i] local user_info = get_msgs_user_chat(user_id, chat_id) table.insert(users_info, user_info) end -- Sort users by msgs number table.sort(users_info, function(a, b) if a.msgs and b.msgs then return a.msgs > b.msgs end end) local text = 'users in this chat \n' for k,user in pairs(users_info) do text = text..user.name..' = '..user.msgs..'\n' end return text end -- Save stats, ban user local function bot_stats() local redis_scan = [[ local cursor = '0' local count = 0 repeat local r = redis.call("SCAN", cursor, "MATCH", KEYS[1]) cursor = r[1] count = count + #r[2] until cursor == '0' return count]] -- Users local hash = 'msgs:*:'..our_id local r = redis:eval(redis_scan, 1, hash) local text = 'Users: '..r hash = 'chat:*:users' r = redis:eval(redis_scan, 1, hash) text = text..'\nGroups: '..r return text end local function run(msg, matches) if matches[1]:lower() == 'nod32' then -- Put everything you like :) local about = _config.about_text local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /nod32 ") return about end if matches[1]:lower() == "statslist" then if not is_momod(msg) then return "For mods only !" end local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats2(chat_id) end if matches[1]:lower() == "stats" then if not matches[2] then if not is_momod(msg) then return "For mods only !" end if msg.to.type == 'chat' then local chat_id = msg.to.id local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] requested group stats ") return chat_stats(chat_id) else return end end if matches[2] == "nod32" then -- Put everything you like :) if not is_admin(msg) then return "For admins only !" else return bot_stats() end end if matches[2] == "group" then if not is_admin(msg) then return "For admins only !" else return chat_stats(matches[3]) end end end end return { patterns = { "^[!/]([Ss]tats)$", "^[!/]([Ss]tatslist)$", "^[!/]([Ss]tats) (group) (%d+)", "^[!/]([Ss]tats) (nod32)",-- Put everything you like :) "^[!/]([Nn]od32)"-- Put everything you like :) }, run = run } end --Copyright and edit; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
Igalia/snabb
lib/luajit/testsuite/bench/revcomp.lua
6
1067
local sub = string.sub iubc = setmetatable({ A="T", C="G", B="V", D="H", K="M", R="Y", a="T", c="G", b="V", d="H", k="M", r="Y", T="A", G="C", V="B", H="D", M="K", Y="R", U="A", t="A", g="C", v="B", h="D", m="K", y="R", u="A", N="N", S="S", W="W", n="N", s="S", w="W", }, { __index = function(t, s) local r = t[sub(s, 2)]..t[sub(s, 1, 1)]; t[s] = r; return r end }) local wcode = [=[ return function(t, n) if n == 1 then return end local iubc, sub, write = iubc, string.sub, io.write local s = table.concat(t, "", 1, n-1) for i=#s-59,1,-60 do write(]=] for i=59,3,-4 do wcode = wcode.."iubc[sub(s, i+"..(i-3)..", i+"..i..")], " end wcode = wcode..[=["\n") end local r = #s % 60 if r ~= 0 then for i=r,1,-4 do write(iubc[sub(s, i-3 < 1 and 1 or i-3, i)]) end write("\n") end end ]=] local writerev = loadstring(wcode)() local t, n = {}, 1 for line in io.lines() do local c = sub(line, 1, 1) if c == ">" then writerev(t, n); io.write(line, "\n"); n = 1 elseif c ~= ";" then t[n] = line; n = n + 1 end end writerev(t, n)
apache-2.0
Kosmos82/kosmosdarkstar
scripts/zones/Pashhow_Marshlands_[S]/npcs/Cavernous_Maw.lua
29
1434
----------------------------------- -- Area: Sauromugue Champaign -- NPC: Cavernous Maw -- @pos 418 25 27 90 -- Teleports Players to Pashhow_Marshlands ----------------------------------- package.loaded["scripts/zones/Pashhow_Marshlands_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/campaign"); require("scripts/zones/Pashhow_Marshlands_[S]/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (hasMawActivated(player,4) == false) then player:startEvent(0x0064); else player:startEvent(0x0065); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (option == 1) then if (csid == 0x0064) then player:addNationTeleport(MAW,16); end toMaw(player,16); end end;
gpl-3.0
martin-traverse/premake-core
tests/actions/vstudio/vc200x/test_project.lua
16
4148
-- -- tests/actions/vstudio/vc200x/test_project.lua -- Validate generation of the opening <VisualStudioProject> element. -- Copyright (c) 2011-2014 Jason Perkins and the Premake project -- local suite = test.declare("vstudio_vs200x_project") local vc200x = premake.vstudio.vc200x -- -- Setup -- local wks, prj function suite.setup() _ACTION = 'vs2008' wks = test.createWorkspace() uuid "AE61726D-187C-E440-BD07-2556188A6565" end local function prepare() prj = test.getproject(wks, 1) vc200x.visualStudioProject(prj) end -- -- Verify the version numbers for each action. -- function suite.hasCorrectVersion_on2005() _ACTION = 'vs2005' prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="8.00" ]] end function suite.hasCorrectVersion_on2008() _ACTION = 'vs2008' prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" ]] end -- -- Check the structure with the default project values. -- function suite.structureIsCorrect_onDefaultValues() prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="Win32Proj" TargetFrameworkVersion="0" > ]] end -- -- Use the correct keyword for Managed C++ projects. -- function suite.keywordIsCorrect_onManagedC() clr "On" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="ManagedCProj" ]] end -- -- Omit Keyword and RootNamespace for non-Windows projects. -- function suite.noKeyword_onNotWindows() system "Linux" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" TargetFrameworkVersion="196613" > ]] end -- -- Include Keyword and RootNamespace for mixed system projects. -- function suite.includeKeyword_onMixedConfigs() filter "Debug" system "Windows" filter "Release" system "Linux" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="Win32Proj" TargetFrameworkVersion="0" > ]] end -- -- Makefile projects set new keyword. It should also drop the root -- namespace, but I need to figure out a better way to test for -- empty configurations in the project first. -- function suite.keywordIsCorrect_onMakefile() kind "Makefile" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end function suite.keywordIsCorrect_onNone() kind "None" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end --- -- Makefile projects which do not support all of the solution configurations -- add back the RootNamespace element. --- function suite.keywordIsCorrect_onMakefileWithMixedConfigs() removeconfigurations { "Release" } kind "Makefile" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end function suite.keywordIsCorrect_onNoneWithMixedConfigs() removeconfigurations { "Release" } kind "None" prepare() test.capture [[ <VisualStudioProject ProjectType="Visual C++" Version="9.00" Name="MyProject" ProjectGUID="{AE61726D-187C-E440-BD07-2556188A6565}" RootNamespace="MyProject" Keyword="MakeFileProj" TargetFrameworkVersion="196613" > ]] end
bsd-3-clause
Kosmos82/kosmosdarkstar
scripts/globals/items/moorish_idol.lua
18
1312
----------------------------------------- -- ID: 5121 -- Item: Moorish Idol -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity 2 -- Mind -4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if (target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5121); 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
torralba-lab/im2recipe
loader/DataLoader.lua
1
4089
require 'paths' require 'image' require 'hdf5' local DataLoader = torch.class('DataLoader') require 'loader.utils' function DataLoader:__init(dataTrain, dataVal, opts) self.batchSize = opts.batchSize self.mismatchFreq = opts.mismatchFreq -- percent of time a misaligned image should be presented self.dataTrain = dataTrain self.dataVal = dataVal --self.eor = soreor[2]:view(1, -1) groupByLen(dataTrain) groupByLen(dataVal) self.imfeatDim = opts.imfeatDim self.stDim = opts.stDim self.maxIngrs = opts.maxIngrs self.semantic = opts.semantic self.dataset = opts.dataset self.net = opts.net self.imstore = opts.imstore self.meanstd = { mean = { 0.485, 0.456, 0.406 }, std = { 0.229, 0.224, 0.225 }, } self.vgg_mean = torch.FloatTensor{123.68, 116.779, 103.939} self.imsize = opts.imsize torch.manualSeed(opts.seed) self.dsH5 = hdf5.open(self.dataset, 'r') collectgarbage() end function DataLoader:makebatch(partition) collectgarbage() partData = partition == 'val' and self.dataVal or self.dataTrain local seqlen = partData.lengths[torch.multinomial(partData.lenFreqs, 1)[1]] local seqlenInds = partData.indsByLen[seqlen] local batchSize = math.min(#seqlenInds, self.batchSize) local imagefile = self.dsH5:read('/ims_'..partData.partition) local selIndInds = torch.randperm(#seqlenInds) -- indices of indices in the batch local batchIds = torch.CharTensor(batchSize, 11) local batchImgs batchImgs = torch.Tensor(batchSize,3,self.imsize,self.imsize) local batchInstrs = torch.Tensor(seqlen, batchSize, self.stDim) local batchIngrs = torch.LongTensor(batchSize, self.maxIngrs) local batchMatches = torch.CharTensor(batchSize) -- whether image belongs to instrs local batchClsRecipe = torch.LongTensor(batchSize) local batchClsImg = torch.LongTensor(batchSize) --batchInstrs[-1]:copy(self.eor:expand(batchSize, self.stDim)) local batchMaxIngrs = 0 for i=1,batchSize do local selInd = seqlenInds[selIndInds[i]] batchIds[i]:sub(1, 10):copy(partData.ids[selInd]) if self.semantic then batchClsRecipe[i] = partData.classes[selInd] batchClsImg[i] = partData.classes[selInd] end local match = math.random() > self.mismatchFreq batchMatches[i] = match and 1 or -1 local position if match then position = selInd else local mismatch = selInd while mismatch == selInd do mismatch = torch.random(partData.ids:size(1)) end position = mismatch end local mean_pixel = self.vgg_mean:view(1,3,1,1) -- READING FROM JPG FILE --name = torch.serialize(partData.images[mismatch]:clone(),'ascii') --local img = loadImage(name:sub(74,148),self.imstore) -- Select random image from list of images for that sample local numims = partData.numims[position] local imid = torch.randperm(numims)[1] local impos = partData.impos[position][imid] local img = imagefile:partial({impos,impos},{1,3},{1,self.imstore},{1,self.imstore}):float() img = improc(self.imsize,img) img = img:view(1, img:size(1), img:size(2), img:size(3)) -- batch the image if self.net == 'resnet' then img:div(256) img = ImageNormalize(img,self.meanstd) else img:add(-1, mean_pixel:expandAs(img)) end batchImgs[i] = img if self.semantic then batchClsImg[i] = partData.classes[position] -- replace class with mismatched class end local rbp = partData.rbps[selInd] local rlen = partData.rlens[selInd] local svecs = partData.stvecs:narrow(1, rbp, rlen) batchInstrs[{{1, seqlen}, i}] = svecs batchIngrs[i] = partData.ingrs[selInd] end if self.semantic then return {batchImgs, batchInstrs, batchIngrs}, {batchMatches,batchClsImg,batchClsRecipe}, batchIds else return {batchImgs, batchInstrs, batchIngrs}, batchMatches, batchIds end end function DataLoader:partitionSize(partition) local ds = partition == 'train' and self.dataTrain or self.dataVal return ds.rlens:size(1) end function DataLoader:terminate() self.dsH5:close() end
mit
mahdib9/kp
plugins/vote.lua
615
2128
do local _file_votes = './data/votes.lua' function read_file_votes () local f = io.open(_file_votes, "r+") if f == nil then print ('Created voting file '.._file_votes) serialize_to_file({}, _file_votes) else print ('Values loaded: '.._file_votes) f:close() end return loadfile (_file_votes)() end function clear_votes (chat) local _votes = read_file_votes () _votes [chat] = {} serialize_to_file(_votes, _file_votes) end function votes_result (chat) local _votes = read_file_votes () local results = {} local result_string = "" if _votes [chat] == nil then _votes[chat] = {} end for user,vote in pairs (_votes[chat]) do if (results [vote] == nil) then results [vote] = user else results [vote] = results [vote] .. ", " .. user end end for vote,users in pairs (results) do result_string = result_string .. vote .. " : " .. users .. "\n" end return result_string end function save_vote(chat, user, vote) local _votes = read_file_votes () if _votes[chat] == nil then _votes[chat] = {} end _votes[chat][user] = vote serialize_to_file(_votes, _file_votes) end function run(msg, matches) if (matches[1] == "ing") then if (matches [2] == "reset") then clear_votes (tostring(msg.to.id)) return "Voting statistics reset.." elseif (matches [2] == "stats") then local votes_result = votes_result (tostring(msg.to.id)) if (votes_result == "") then votes_result = "[No votes registered]\n" end return "Voting statistics :\n" .. votes_result end else save_vote(tostring(msg.to.id), msg.from.print_name, tostring(tonumber(matches[2]))) return "Vote registered : " .. msg.from.print_name .. " " .. tostring(tonumber(matches [2])) end end return { description = "Plugin for voting in groups.", usage = { "!voting reset: Reset all the votes.", "!vote [number]: Cast the vote.", "!voting stats: Shows the statistics of voting." }, patterns = { "^!vot(ing) (reset)", "^!vot(ing) (stats)", "^!vot(e) ([0-9]+)$" }, run = run } end
gpl-2.0
squeek502/luvit
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
harveyhu2012/luci
modules/base/luasrc/http/protocol/date.lua
88
2760
--[[ HTTP protocol implementation for LuCI - date handling (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- --- LuCI http protocol implementation - date helper class. -- This class contains functions to parse, compare and format http dates. module("luci.http.protocol.date", package.seeall) require("luci.sys.zoneinfo") MONTHS = { "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec" } --- Return the time offset in seconds between the UTC and given time zone. -- @param tz Symbolic or numeric timezone specifier -- @return Time offset to UTC in seconds function tz_offset(tz) if type(tz) == "string" then -- check for a numeric identifier local s, v = tz:match("([%+%-])([0-9]+)") if s == '+' then s = 1 else s = -1 end if v then v = tonumber(v) end if s and v then return s * 60 * ( math.floor( v / 100 ) * 60 + ( v % 100 ) ) -- lookup symbolic tz elseif luci.sys.zoneinfo.OFFSET[tz:lower()] then return luci.sys.zoneinfo.OFFSET[tz:lower()] end end -- bad luck return 0 end --- Parse given HTTP date string and convert it to unix epoch time. -- @param data String containing the date -- @return Unix epoch time function to_unix(date) local wd, day, mon, yr, hr, min, sec, tz = date:match( "([A-Z][a-z][a-z]), ([0-9]+) " .. "([A-Z][a-z][a-z]) ([0-9]+) " .. "([0-9]+):([0-9]+):([0-9]+) " .. "([A-Z0-9%+%-]+)" ) if day and mon and yr and hr and min and sec then -- find month local month = 1 for i = 1, 12 do if MONTHS[i] == mon then month = i break end end -- convert to epoch time return tz_offset(tz) + os.time( { year = yr, month = month, day = day, hour = hr, min = min, sec = sec } ) end return 0 end --- Convert the given unix epoch time to valid HTTP date string. -- @param time Unix epoch time -- @return String containing the formatted date function to_http(time) return os.date( "%a, %d %b %Y %H:%M:%S GMT", time ) end --- Compare two dates which can either be unix epoch times or HTTP date strings. -- @param d1 The first date or epoch time to compare -- @param d2 The first date or epoch time to compare -- @return -1 - if d1 is lower then d2 -- @return 0 - if both dates are equal -- @return 1 - if d1 is higher then d2 function compare(d1, d2) if d1:match("[^0-9]") then d1 = to_unix(d1) end if d2:match("[^0-9]") then d2 = to_unix(d2) end if d1 == d2 then return 0 elseif d1 < d2 then return -1 else return 1 end end
apache-2.0
wingo/snabbswitch
src/program/snsh/snsh.lua
5
4537
-- Use of this source code is governed by the Apache 2.0 license; see COPYING. module(..., package.seeall) local lib = require("core.lib") local usage = require("program.snsh.README_inc") local long_opts = { ["package-path"] = "P", eval = "e", load = "l", program = "p", test = "t", interactive = "i", debug = "d", jit = "j", sigquit = "q", help = "h", } function run (parameters) local profiling = false local traceprofiling = false local start_repl = false local noop = true -- are we doing nothing? local program -- should we run a different program? -- Table of functions implementing command-line arguments local opt = {} function opt.h (arg) print(usage) main.exit(0) end function opt.l (arg) require(arg) noop = false end function opt.t (arg) require(arg).selftest() noop = false end function opt.q (arg) hook_sigquit(arg) end function opt.d (arg) _G.developer_debug = true end function opt.p (arg) program = arg end function opt.i (arg) start_repl = true noop = false end function opt.j (arg) if arg:match("^v") then local file = arg:match("^v=(.*)") if file == '' then file = nil end require("jit.v").start(file) elseif arg:match("^p") then local opts, file = arg:match("^p=([^,]*),?(.*)") if file == '' then file = nil end require("jit.p").start(opts, file) profiling = true elseif arg:match("^dump") then local opts, file = arg:match("^dump=([^,]*),?(.*)") if file == '' then file = nil end require("jit.dump").on(opts, file) elseif arg:match("^tprof") then require("lib.traceprof.traceprof").start() traceprofiling = true end end function opt.e (arg) local thunk, error = loadstring(arg) if thunk then thunk() else print(error) end noop = false end function opt.P (arg) package.path = arg end -- Execute command line arguments parameters = lib.dogetopt(parameters, opt, "hl:p:t:die:j:P:q:", long_opts) if program then local mod = (("program.%s.%s"):format(program, program)) require(mod).run(parameters) elseif #parameters > 0 then run_script(parameters) elseif noop then print(usage) main.exit(1) end if start_repl then repl() end if profiling then require("jit.p").stop() end if traceprofiling then require("lib.traceprof.traceprof").stop() end end function run_script (parameters) local command = table.remove(parameters, 1) main.parameters = parameters -- make remaining args available to script local r, error = pcall(dofile, command) if not r then print(error) main.exit(1) end end -- This is a simple REPL similar to LuaJIT's built-in REPL. It can only -- read single-line statements but does support the `=<expr>' syntax. function repl () local line = nil local function eval_line () if line:sub(0,1) == "=" then -- Evaluate line as expression. print(loadstring("return "..line:sub(2))()) else -- Evaluate line as statement local load = loadstring(line) if load then load() end end end repeat io.stdout:write("Snabb> ") io.stdout:flush() line = io.stdin:read("*l") if line then local status, err = pcall(eval_line) if not status then io.stdout:write(("Error in %s\n"):format(err)) end io.stdout:flush() end until not line end -- Cause SIGQUIT to enter the REPL. -- SIGQUIT can be triggered interactively with `Control \' in a terminal. function hook_sigquit (action) if action ~= 'repl' then print("ignoring unrecognized SIGQUIT action: " .. action) os.exit(1) end local S = require("syscall") local fd = S.signalfd("quit", "nonblock") -- handle SIGQUIT via fd S.sigprocmask("block", "quit") -- block traditional handler local timer = require("core.timer") timer.activate(timer.new("sigquit-repl", function () if (#S.util.signalfd_read(fd) > 0) then print("[snsh: SIGQUIT caught - entering REPL]") repl() end end, 1e4, 'repeating')) end
apache-2.0
dr01d3r/darkstar
scripts/zones/Lower_Jeuno/npcs/Parike-Poranke.lua
14
1121
----------------------------------- -- Area: Lower Jeuno -- NPC: Parike-Poranke -- Type: Adventurer's Assistant -- @zone 245 -- @pos -33.161 -1 -61.303 -- -- Auto-Script: Requires Verification (Verfied by Brawndo) ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(PARIKE_PORANKE_DIALOG); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
dr01d3r/darkstar
scripts/zones/Kazham/npcs/Kobhi_Sarhigamya.lua
14
1037
---------------------------------- -- Area: Kazham -- NPC: Kobhi Sarhigamya -- Type: Item Deliverer -- @zone 250 -- @pos -115.29 -11 -22.609 -- ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc, ITEM_DELIVERY_DIALOG); player:openSendBox(); 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
soundsrc/premake-stable
src/actions/codelite/codelite_project.lua
6
5691
-- -- codelite_project.lua -- Generate a CodeLite C/C++ project file. -- Copyright (c) 2009, 2011 Jason Perkins and the Premake project -- local codelite = premake.codelite local tree = premake.tree -- -- Write out a list of the source code files in the project. -- function codelite.files(prj) local tr = premake.project.buildsourcetree(prj) tree.traverse(tr, { -- folders are handled at the internal nodes onbranchenter = function(node, depth) _p(depth, '<VirtualDirectory Name="%s">', node.name) end, onbranchexit = function(node, depth) _p(depth, '</VirtualDirectory>') end, -- source files are handled at the leaves onleaf = function(node, depth) _p(depth, '<File Name="%s"/>', node.cfg.name) end, }, true, 1) end -- -- The main function: write out the project file. -- function premake.codelite.project(prj) io.indent = " " _p('<?xml version="1.0" encoding="utf-8"?>') _p('<CodeLite_Project Name="%s">', premake.esc(prj.name)) -- Write out the list of source code files in the project codelite.files(prj) local types = { ConsoleApp = "Executable", WindowedApp = "Executable", StaticLib = "Static Library", SharedLib = "Dynamic Library", } _p(' <Settings Type="%s">', types[prj.kind]) -- build a list of supported target platforms; I don't support cross-compiling yet local platforms = premake.filterplatforms(prj.solution, premake[_OPTIONS.cc].platforms, "Native") for i = #platforms, 1, -1 do if premake.platforms[platforms[i]].iscrosscompiler then table.remove(platforms, i) end end for _, platform in ipairs(platforms) do for cfg in premake.eachconfig(prj, platform) do local name = premake.esc(cfg.longname):gsub("|","_") local compiler = iif(cfg.language == "C", "gcc", "g++") _p(' <Configuration Name="%s" CompilerType="gnu %s" DebuggerType="GNU gdb debugger" Type="%s">', name, compiler, types[cfg.kind]) local fname = premake.esc(cfg.buildtarget.fullpath) local objdir = premake.esc(cfg.objectsdir) local runcmd = cfg.buildtarget.name local rundir = cfg.debugdir or cfg.buildtarget.directory local runargs = table.concat(cfg.debugargs, " ") local pause = iif(cfg.kind == "WindowedApp", "no", "yes") _p(' <General OutputFile="%s" IntermediateDirectory="%s" Command="./%s" CommandArguments="%s" WorkingDirectory="%s" PauseExecWhenProcTerminates="%s"/>', fname, objdir, runcmd, runargs, rundir, pause) -- begin compiler block -- local flags = premake.esc(table.join(premake.gcc.getcflags(cfg), premake.gcc.getcxxflags(cfg), cfg.buildoptions)) _p(' <Compiler Required="yes" Options="%s">', table.concat(flags, ";")) for _,v in ipairs(cfg.includedirs) do _p(' <IncludePath Value="%s"/>', premake.esc(v)) end for _,v in ipairs(cfg.defines) do _p(' <Preprocessor Value="%s"/>', premake.esc(v)) end _p(' </Compiler>') -- end compiler block -- -- begin linker block -- flags = premake.esc(table.join(premake.gcc.getldflags(cfg), cfg.linkoptions)) _p(' <Linker Required="yes" Options="%s">', table.concat(flags, ";")) for _,v in ipairs(premake.getlinks(cfg, "all", "directory")) do _p(' <LibraryPath Value="%s" />', premake.esc(v)) end for _,v in ipairs(premake.getlinks(cfg, "all", "basename")) do _p(' <Library Value="%s" />', premake.esc(v)) end _p(' </Linker>') -- end linker block -- -- begin resource compiler block -- if premake.findfile(cfg, ".rc") then local defines = table.implode(table.join(cfg.defines, cfg.resdefines), "-D", ";", "") local options = table.concat(cfg.resoptions, ";") _p(' <ResourceCompiler Required="yes" Options="%s%s">', defines, options) for _,v in ipairs(table.join(cfg.includedirs, cfg.resincludedirs)) do _p(' <IncludePath Value="%s"/>', premake.esc(v)) end _p(' </ResourceCompiler>') else _p(' <ResourceCompiler Required="no" Options=""/>') end -- end resource compiler block -- -- begin build steps -- if #cfg.prebuildcommands > 0 then _p(' <PreBuild>') for _,v in ipairs(cfg.prebuildcommands) do _p(' <Command Enabled="yes">%s</Command>', premake.esc(v)) end _p(' </PreBuild>') end if #cfg.postbuildcommands > 0 then _p(' <PostBuild>') for _,v in ipairs(cfg.postbuildcommands) do _p(' <Command Enabled="yes">%s</Command>', premake.esc(v)) end _p(' </PostBuild>') end -- end build steps -- _p(' <CustomBuild Enabled="no">') _p(' <CleanCommand></CleanCommand>') _p(' <BuildCommand></BuildCommand>') _p(' <SingleFileCommand></SingleFileCommand>') _p(' <MakefileGenerationCommand></MakefileGenerationCommand>') _p(' <ThirdPartyToolName>None</ThirdPartyToolName>') _p(' <WorkingDirectory></WorkingDirectory>') _p(' </CustomBuild>') _p(' <AdditionalRules>') _p(' <CustomPostBuild></CustomPostBuild>') _p(' <CustomPreBuild></CustomPreBuild>') _p(' </AdditionalRules>') _p(' </Configuration>') end end _p(' </Settings>') for _, platform in ipairs(platforms) do for cfg in premake.eachconfig(prj, platform) do _p(' <Dependencies name="%s">', cfg.longname:gsub("|","_")) for _,dep in ipairs(premake.getdependencies(prj)) do _p(' <Project Name="%s"/>', dep.name) end _p(' </Dependencies>') end end _p('</CodeLite_Project>') end
bsd-3-clause
SalvationDevelopment/Salvation-Scripts-Production
c75560629.lua
7
2787
--フリント function c75560629.initial_effect(c) --Activate local e1=Effect.CreateEffect(c) e1:SetCategory(CATEGORY_EQUIP) e1:SetType(EFFECT_TYPE_ACTIVATE) e1:SetCode(EVENT_FREE_CHAIN) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetTarget(c75560629.target) e1:SetOperation(c75560629.operation) c:RegisterEffect(e1) --atkdown local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_EQUIP) e2:SetCode(EFFECT_UPDATE_ATTACK) e2:SetCondition(c75560629.flcon) e2:SetValue(-300) c:RegisterEffect(e2) --cannot attack local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_EQUIP) e3:SetCode(EFFECT_CANNOT_ATTACK_ANNOUNCE) e3:SetCondition(c75560629.flcon) c:RegisterEffect(e3) --cannot change pos local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_EQUIP) e4:SetCode(EFFECT_CANNOT_CHANGE_POSITION) e4:SetCondition(c75560629.flcon) c:RegisterEffect(e4) --equip limit local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetCode(EFFECT_EQUIP_LIMIT) e5:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e5:SetValue(c75560629.eqlimit) c:RegisterEffect(e5) --reequip local e6=Effect.CreateEffect(c) e6:SetDescription(aux.Stringid(75560629,0)) e6:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F) e6:SetCode(EVENT_TO_GRAVE) e6:SetProperty(EFFECT_FLAG_CARD_TARGET) e6:SetCondition(c75560629.eqcon) e6:SetTarget(c75560629.target) e6:SetOperation(c75560629.operation) c:RegisterEffect(e6) local e7=e6:Clone() e7:SetCode(EVENT_REMOVE) c:RegisterEffect(e7) end function c75560629.flcon(e) local tc=e:GetHandler():GetEquipTarget() return tc:GetCode()~=83812099 or tc:IsDisabled() end function c75560629.eqlimit(e,c) return c:GetCode()~=83812099 or c:IsDisabled() or not c:GetEquipGroup():IsExists(Card.IsCode,1,e:GetHandler(),75560629) end function c75560629.filter(c) return c:IsFaceup() and (c:GetCode()~=83812099 or c:IsDisabled() or not c:GetEquipGroup():IsExists(Card.IsCode,1,nil,75560629)) end function c75560629.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and c75560629.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c75560629.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,nil) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_EQUIP) Duel.SelectTarget(tp,c75560629.filter,tp,LOCATION_MZONE,LOCATION_MZONE,1,1,nil) Duel.SetOperationInfo(0,CATEGORY_EQUIP,e:GetHandler(),1,0,0) end function c75560629.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local tc=Duel.GetFirstTarget() if c:IsRelateToEffect(e) and tc:IsRelateToEffect(e) and tc:IsFaceup() then Duel.Equip(tp,c,tc) end end function c75560629.eqcon(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() local ec=c:GetPreviousEquipTarget() return c:IsReason(REASON_LOST_TARGET) and ec and ec:IsReason(REASON_DESTROY) end
gpl-2.0
chaot4/ardour
share/scripts/delete_xrun_markers.lua
6
1092
ardour { ["type"] = "EditorAction", name = "Delete xrun markers", author = "Ardour Team", description = [[Delete all xrun markers in the current session]] } function factory () return function () for l in Session:locations():list():iter() do if l:is_mark() and string.find (l:name(), "^xrun%d*$") then Session:locations():remove (l); end end end end function icon (params) return function (ctx, width, height, fg) local mh = height - 3.5; local m3 = width / 3; local m6 = width / 6; ctx:set_line_width (.5) ctx:set_source_rgba (.8, .2, .2, 1.0) ctx:move_to (width / 2 - m6, 2) ctx:rel_line_to (m3, 0) ctx:rel_line_to (0, mh * 0.4) ctx:rel_line_to (-m6, mh * 0.6) ctx:rel_line_to (-m6, -mh * 0.6) ctx:close_path () ctx:fill_preserve () ctx:set_source_rgba (.0, .0, .0, 1.0) ctx:stroke () ctx:set_source_rgba (ARDOUR.LuaAPI.color_to_rgba (fg)) ctx:set_line_width (1) ctx:move_to (width * .2, height * .2) ctx:line_to (width * .8, height * .8) ctx:stroke () ctx:move_to (width * .8, height * .2) ctx:line_to (width * .2, height * .8) ctx:stroke () end end
gpl-2.0
aleju/cat-generator
sample.lua
1
8622
require 'torch' require 'image' require 'paths' require 'pl' require 'layers.cudnnSpatialConvolutionUpsample' require 'stn' require 'LeakyReLU' NN_UTILS = require 'utils.nn_utils' DATASET = require 'dataset' OPT = lapp[[ --save (default "logs") Directory in which the base 16x16 networks are stored. --G_base (default "adversarial.net") Filename for the 32x32 base network to load G from. --D_base (default "adversarial.net") Filename for the 32x32 base network to load D from. --neighbours Whether to search for nearest neighbours of generated images in the dataset (takes long) --scale (default 32) Height of images in the base network. --colorSpace (default "rgb") rgb|yuv|hsl|y --writeto (default "samples") Directory to save the images to --seed (default 1) Random number seed to use. --gpu (default 0) GPU to run on --runs (default 1) How often to sample and save images --noiseDim (default 100) Noise vector size. --batchSize (default 16) Sizes of batches. --aws Run in AWS mode. ]] if OPT.gpu < 0 then print("[ERROR] Sample script currently only runs on GPU, set --gpu=x where x is between 0 and 3.") exit() end if OPT.colorSpace == "y" then OPT.grayscale = true end -- Start GPU mode print("Starting gpu support...") require 'cutorch' require 'cunn' torch.setdefaulttensortype('torch.FloatTensor') cutorch.setDevice(OPT.gpu + 1) -- initialize seeds math.randomseed(OPT.seed) torch.manualSeed(OPT.seed) cutorch.manualSeed(OPT.seed) -- Image dimensions if OPT.grayscale then IMG_DIMENSIONS = {1, OPT.scale, OPT.scale} else IMG_DIMENSIONS = {3, OPT.scale, OPT.scale} end -- Initialize dataset --DATASET.nbChannels = IMG_DIMENSIONS[1] DATASET.colorSpace = OPT.colorSpace DATASET.setFileExtension("jpg") DATASET.setHeight(OPT.scale) DATASET.setWidth(OPT.scale) if OPT.aws then DATASET.setDirs({"/mnt/datasets/out_aug_64x64"}) else DATASET.setDirs({"dataset/out_aug_64x64"}) end -- Main function that runs the sampling function main() -- Load all models local G, D = loadModels() -- We need these global variables for some methods. Ugly code. MODEL_G = G MODEL_D = D print("Sampling...") for run=1,OPT.runs do -- save 64 randomly selected images from the training set local imagesTrainList = DATASET.loadRandomImages(64) -- dont use nn_utils.toImageTensor here, because the metatable of imagesTrainList was changed local imagesTrain = torch.Tensor(#imagesTrainList, imagesTrainList[1]:size(1), imagesTrainList[1]:size(2), imagesTrainList[1]:size(3)):float() for i=1,#imagesTrainList do imagesTrain[i] = imagesTrainList[i] end image.save(paths.concat(OPT.writeto, string.format('trainset_s1_%04d_base.jpg', run)), toGrid(imagesTrain, 8)) -- sample 1024 new images from G local images = NN_UTILS.createImages(1024, false) -- validate image dimensions if images[1]:size(1) ~= IMG_DIMENSIONS[1] or images[1]:size(2) ~= IMG_DIMENSIONS[2] or images[1]:size(3) ~= IMG_DIMENSIONS[3] then print("[WARNING] dimension mismatch between images generated by base G and command line parameters, --grayscale falsly on/off or --scale not set correctly") print("Dimension G:", images[1]:size()) print("Settings:", IMG_DIMENSIONS) end -- save big images of those 1024 random images image.save(paths.concat(OPT.writeto, string.format('random256_%04d_base.jpg', run)), toGrid(selectRandomImagesFrom(images, 256), 16)) image.save(paths.concat(OPT.writeto, string.format('random1024_%04d_base.jpg', run)), toGrid(images, 32)) -- Collect the best and worst images (according to D) from these images -- Save: 32 best images, 32 worst images, 32 randomly selected images local imagesBest, predictions = NN_UTILS.sortImagesByPrediction(images, false, 64) local imagesWorst, predictions = NN_UTILS.sortImagesByPrediction(images, true, 64) local imagesRandom = selectRandomImagesFrom(images, 64) imagesBest = NN_UTILS.toImageTensor(imagesBest) imagesWorst = NN_UTILS.toImageTensor(imagesWorst) imagesRandom = NN_UTILS.toImageTensor(imagesRandom) image.save(paths.concat(OPT.writeto, string.format('best_%04d_base.jpg', run)), toGrid(imagesBest, 8)) image.save(paths.concat(OPT.writeto, string.format('worst_%04d_base.jpg', run)), toGrid(imagesWorst, 8)) image.save(paths.concat(OPT.writeto, string.format('random_%04d_base.jpg', run)), toGrid(imagesRandom, 8)) -- Extract the 16 best images and find their closest neighbour in the training set if OPT.neighbours then local searchFor = {} for i=1,16 do table.insert(searchFor, imagesBest[i]:clone()) end local neighbours = findClosestNeighboursOf(searchFor) image.save(paths.concat(OPT.writeto, string.format('best_%04d_neighbours_base.jpg', run)), toNeighboursGrid(neighbours, 8)) end xlua.progress(run, OPT.runs) end print("Finished.") end -- Searches for the closest neighbours (2-Norm/torch.dist) for each image in the given list. -- @param images List of image tensors. -- @returns List of tables {image, closest neighbour's image, distance} function findClosestNeighboursOf(images) local result = {} local trainingSet = DATASET.loadImages(0, 9999999) for i=1,#images do local img = images[i] local closestDist = nil local closestImg = nil for j=1,trainingSet:size() do local dist = torch.dist(trainingSet[j], img) if closestDist == nil or dist < closestDist then closestDist = dist closestImg = trainingSet[j]:clone() end end table.insert(result, {img, closestImg, closestDist}) end return result end -- Normalizes a tensor of images. -- Currently that projects an images from 0.0 to 1.0 to range -1.0 to +1.0. -- @param images Tensor of images -- @param mean_ Currently ignored. -- @param std_ Currently ignored. -- @returns images Normalized images (NOTE: images are normalized in-place) function normalize(images, mean_, std_) -- normalizes in-place NN_UTILS.normalize(images, mean_, std_) return images end -- Converts images to one image grid with set amount of rows. -- @param images Tensor of images -- @param nrow Number of rows. -- @return Tensor function toGrid(images, nrow) return image.toDisplayTensor{input=NN_UTILS.toRgb(images, OPT.colorSpace), nrow=nrow} end -- Converts a table of images as returned by findClosestNeighboursOf() to one image grid. -- @param imagesWithNeighbours Table of (image, neighbour image, distance) -- @returns Tensor function toNeighboursGrid(imagesWithNeighbours) local img = imagesWithNeighbours[1][1] local imgpairs = torch.Tensor(#imagesWithNeighbours*2, img:size(1), img:size(2), img:size(3)):float() local imgpairs_idx = 1 for i=1,#imagesWithNeighbours do imgpairs[imgpairs_idx] = imagesWithNeighbours[i][1] imgpairs[imgpairs_idx + 1] = imagesWithNeighbours[i][2] imgpairs_idx = imgpairs_idx + 2 end return image.toDisplayTensor{input=NN_UTILS.toRgb(imgpairs, OPT.colorSpace), nrow=#imagesWithNeighbours} end -- Selects N random images from a tensor of images. -- @param tensor Tensor of images -- @param n Number of random images to select -- @returns List/table of images function selectRandomImagesFrom(tensor, n) local shuffle = torch.randperm(tensor:size(1)) local result = {} for i=1,math.min(n, tensor:size(1)) do table.insert(result, tensor[ shuffle[i] ]) end return result end -- Loads all necessary models/networks and returns them. -- @returns G, D function loadModels() local file -- load G base file = torch.load(paths.concat(OPT.save, OPT.G_base)) local G = file.G G:evaluate() -- load D base file = torch.load(paths.concat(OPT.save, OPT.D_base)) local D = file.D D:evaluate() return G, D end main()
mit
SalvationDevelopment/Salvation-Scripts-Production
c87047161.lua
5
1025
--マーメイド・シャーク function c87047161.initial_effect(c) --tohand local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(87047161,0)) e1:SetCategory(CATEGORY_TOHAND+CATEGORY_SEARCH) e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_O) e1:SetCode(EVENT_SUMMON_SUCCESS) e1:SetTarget(c87047161.target) e1:SetOperation(c87047161.operation) c:RegisterEffect(e1) end function c87047161.filter(c) local lv=c:GetLevel() return (lv==3 or lv==4 or lv==5) and c:IsRace(RACE_FISH) and c:IsAbleToHand() end function c87047161.target(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return Duel.IsExistingMatchingCard(c87047161.filter,tp,LOCATION_DECK,0,1,nil) end Duel.SetOperationInfo(0,CATEGORY_TOHAND,nil,1,tp,LOCATION_DECK) end function c87047161.operation(e,tp,eg,ep,ev,re,r,rp) Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_ATOHAND) local g=Duel.SelectMatchingCard(tp,c87047161.filter,tp,LOCATION_DECK,0,1,1,nil) if g:GetCount()>0 then Duel.SendtoHand(g,nil,REASON_EFFECT) Duel.ConfirmCards(1-tp,g) end end
gpl-2.0
SalvationDevelopment/Salvation-Scripts-Production
c53183600.lua
5
3306
--ブルーアイズ・トゥーン・ドラゴン function c53183600.initial_effect(c) c:EnableReviveLimit() --special summon local e2=Effect.CreateEffect(c) e2:SetType(EFFECT_TYPE_FIELD) e2:SetCode(EFFECT_SPSUMMON_PROC) e2:SetProperty(EFFECT_FLAG_UNCOPYABLE) e2:SetRange(LOCATION_HAND) e2:SetCondition(c53183600.spcon) e2:SetOperation(c53183600.spop) c:RegisterEffect(e2) --destroy local e3=Effect.CreateEffect(c) e3:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS) e3:SetRange(LOCATION_MZONE) e3:SetCode(EVENT_LEAVE_FIELD) e3:SetCondition(c53183600.sdescon) e3:SetOperation(c53183600.sdesop) c:RegisterEffect(e3) --direct attack local e4=Effect.CreateEffect(c) e4:SetType(EFFECT_TYPE_SINGLE) e4:SetCode(EFFECT_DIRECT_ATTACK) e4:SetCondition(c53183600.dircon) c:RegisterEffect(e4) local e5=Effect.CreateEffect(c) e5:SetType(EFFECT_TYPE_SINGLE) e5:SetCode(EFFECT_CANNOT_SELECT_BATTLE_TARGET) e5:SetCondition(c53183600.atcon) e5:SetValue(c53183600.atlimit) c:RegisterEffect(e5) local e6=Effect.CreateEffect(c) e6:SetType(EFFECT_TYPE_SINGLE) e6:SetCode(EFFECT_CANNOT_DIRECT_ATTACK) e6:SetCondition(c53183600.atcon) c:RegisterEffect(e6) --cannot attack local e7=Effect.CreateEffect(c) e7:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS) e7:SetCode(EVENT_SPSUMMON_SUCCESS) e7:SetOperation(c53183600.atklimit) c:RegisterEffect(e7) --attack cost local e8=Effect.CreateEffect(c) e8:SetType(EFFECT_TYPE_SINGLE) e8:SetCode(EFFECT_ATTACK_COST) e8:SetCost(c53183600.atcost) e8:SetOperation(c53183600.atop) c:RegisterEffect(e8) end function c53183600.cfilter(c) return c:IsFaceup() and c:IsCode(15259703) end function c53183600.spcon(e,c) if c==nil then return true end local tp=c:GetControler() return Duel.IsExistingMatchingCard(c53183600.cfilter,tp,LOCATION_ONFIELD,0,1,nil) and Duel.GetLocationCount(tp,LOCATION_MZONE)>-2 and Duel.CheckReleaseGroup(tp,nil,2,nil) end function c53183600.spop(e,tp,eg,ep,ev,re,r,rp,c) local tp=c:GetControler() local g=Duel.SelectReleaseGroup(tp,nil,2,2,nil) Duel.Release(g,REASON_COST) end function c53183600.sfilter(c) return c:IsReason(REASON_DESTROY) and c:IsPreviousPosition(POS_FACEUP) and c:GetPreviousCodeOnField()==15259703 and c:IsPreviousLocation(LOCATION_ONFIELD) end function c53183600.sdescon(e,tp,eg,ep,ev,re,r,rp) return eg:IsExists(c53183600.sfilter,1,nil) end function c53183600.sdesop(e,tp,eg,ep,ev,re,r,rp) Duel.Destroy(e:GetHandler(),REASON_EFFECT) end function c53183600.atkfilter(c) return c:IsFaceup() and c:IsType(TYPE_TOON) end function c53183600.dircon(e) return not Duel.IsExistingMatchingCard(c53183600.atkfilter,e:GetHandlerPlayer(),0,LOCATION_MZONE,1,nil) end function c53183600.atcon(e) return Duel.IsExistingMatchingCard(c53183600.atkfilter,e:GetHandlerPlayer(),0,LOCATION_MZONE,1,nil) end function c53183600.atlimit(e,c) return not c:IsType(TYPE_TOON) or c:IsFacedown() end function c53183600.atklimit(e,tp,eg,ep,ev,re,r,rp) local e1=Effect.CreateEffect(e:GetHandler()) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetCode(EFFECT_CANNOT_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_END) e:GetHandler():RegisterEffect(e1) end function c53183600.atcost(e,c,tp) return Duel.CheckLPCost(tp,500) end function c53183600.atop(e,tp,eg,ep,ev,re,r,rp) Duel.PayLPCost(tp,500) end
gpl-2.0
dr01d3r/darkstar
scripts/globals/effects/aftermath_lv1.lua
30
1130
----------------------------------- -- -- EFFECT_AFTERMATH_LV1 -- ----------------------------------- require("scripts/globals/status"); ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) local power = effect:getPower(); if (effect:getSubPower() == 1) then target:addMod(MOD_ACC,power); elseif (effect:getSubPower() == 2) then target:addMod(MOD_MACC,power) elseif (effect:getSubPower() == 3) then target:addMod(MOD_RACC,power) end end; ----------------------------------- -- onEffectTick Action ----------------------------------- function onEffectTick(target,effect) end; ----------------------------------- -- onEffectLose Action ----------------------------------- function onEffectLose(target,effect) local power = effect:getPower(); if (effect:getSubPower() == 1) then target:delMod(MOD_ACC,power); elseif (effect:getSubPower() == 2) then target:delMod(MOD_MACC,power) elseif (effect:getSubPower() == 3) then target:delMod(MOD_RACC,power) end end;
gpl-3.0
kidaa/luvi
src/lua/luvibundle.lua
2
9490
local uv = require('uv') local miniz = require('miniz') local luvi = require('luvi') local luviPath = require('luvipath') local pathJoin = luviPath.pathJoin local getenv = require('os').getenv local tmpBase = luviPath.isWindows and (getenv("TMP") or uv.cwd()) or (getenv("TMPDIR") or '/tmp') -- Bundle from folder on disk local function folderBundle(base) local bundle = { base = base } function bundle.stat(path) path = pathJoin(base, "./" .. path) local raw, err = uv.fs_stat(path) if not raw then return nil, err end return { type = string.lower(raw.type), size = raw.size, mtime = raw.mtime, } end function bundle.readdir(path) path = pathJoin(base, "./" .. path) local req, err = uv.fs_scandir(path) if not req then return nil, err end local files = {} repeat local ent = uv.fs_scandir_next(req) if ent then files[#files + 1] = ent.name end until not ent return files end function bundle.readfile(path) path = pathJoin(base, "./" .. path) local fd, stat, data, err stat, err = uv.fs_stat(path) if not stat then return nil, err end if stat.type ~= "file" then return end fd, err = uv.fs_open(path, "r", 0644) if not fd then return nil, err end if stat then data, err = uv.fs_read(fd, stat.size, 0) end uv.fs_close(fd) return data, err end return bundle end -- Insert a prefix into all bundle calls local function chrootBundle(bundle, prefix) local bundleStat = bundle.stat function bundle.stat(path) return bundleStat(prefix .. path) end local bundleReaddir = bundle.readdir function bundle.readdir(path) return bundleReaddir(prefix .. path) end local bundleReadfile = bundle.readfile function bundle.readfile(path) return bundleReadfile(prefix .. path) end end -- Use a zip file as a bundle local function zipBundle(base, zip) local bundle = { base = base } function bundle.stat(path) path = pathJoin("./" .. path) if path == "" then return { type = "directory", size = 0, mtime = 0 } end local err local index = zip:locate_file(path) if not index then index, err = zip:locate_file(path .. "/") if not index then return nil, err end end local raw = zip:stat(index) return { type = raw.filename:sub(-1) == "/" and "directory" or "file", size = raw.uncomp_size, mtime = raw.time, } end function bundle.readdir(path) path = pathJoin("./" .. path) local index, err if path == "" then index = 0 else path = path .. "/" index, err = zip:locate_file(path ) if not index then return nil, err end if not zip:is_directory(index) then return nil, path .. " is not a directory" end end local files = {} for i = index + 1, zip:get_num_files() do local filename = zip:get_filename(i) if string.sub(filename, 1, #path) ~= path then break end filename = filename:sub(#path + 1) local n = string.find(filename, "/") if n == #filename then filename = string.sub(filename, 1, #filename - 1) n = nil end if not n then files[#files + 1] = filename end end return files end function bundle.readfile(path) path = pathJoin("./" .. path) local index, err = zip:locate_file(path) if not index then return nil, err end return zip:extract(index) end -- Support zips with a single folder inserted at top-level local entries = bundle.readdir("") if #entries == 1 and bundle.stat(entries[1]).type == "directory" then chrootBundle(bundle, entries[1] .. '/') end return bundle end local function buildBundle(target, bundle) target = pathJoin(uv.cwd(), target) print("Creating new binary: " .. target) local fd = assert(uv.fs_open(target, "w", 511)) -- 0777 local binSize do local source = uv.exepath() local reader = miniz.new_reader(source) if reader then -- If contains a zip, find where the zip starts binSize = reader:get_offset() else -- Otherwise just read the file size binSize = uv.fs_stat(source).size end local fd2 = assert(uv.fs_open(source, "r", 384)) -- 0600 print("Copying initial " .. binSize .. " bytes from " .. source) uv.fs_sendfile(fd, fd2, 0, binSize) uv.fs_close(fd2) end local writer = miniz.new_writer() local function copyFolder(path) local files = bundle.readdir(path) if not files then return end for i = 1, #files do local name = files[i] if string.sub(name, 1, 1) ~= "." then local child = pathJoin(path, name) local stat = bundle.stat(child) if stat.type == "directory" then writer:add(child .. "/", "") copyFolder(child) elseif stat.type == "file" then print(" " .. child) writer:add(child, bundle.readfile(child), 9) end end end end print("Zipping " .. bundle.base) copyFolder("") print("Writing zip file") uv.fs_write(fd, writer:finalize(), binSize) uv.fs_close(fd) print("Done building " .. target) return end -- Given a list of bundles, merge them into a single VFS. Lower indexed items -- overshadow later items. local function combinedBundle(bundles) local bases = {} for i = 1, #bundles do bases[i] = bundles[i].base end local bundle = { base = table.concat(bases, ";") } function bundle.stat(path) local err for i = 1, #bundles do local stat stat, err = bundles[i].stat(path) if stat then return stat end end return nil, err end function bundle.readdir(path) local has = {} local files, err for i = 1, #bundles do local list list, err = bundles[i].readdir(path) if list then for j = 1, #list do local name = list[j] if has[name] then print("Warning multiple overlapping versions of " .. name) else has[name] = true if files then files[#files + 1] = name else files = { name } end end end end end if files then return files else return nil, err end end function bundle.readfile(path) local err for i = 1, #bundles do local data data, err = bundles[i].readfile(path) if data then return data end end return nil, err end return bundle end local function makeBundle(bundlePaths) local parts = {} for n = 1, #bundlePaths do local path = pathJoin(uv.cwd(), bundlePaths[n]) bundlePaths[n] = path local bundle local zip = miniz.new_reader(path) if zip then bundle = zipBundle(path, zip) else local stat = uv.fs_stat(path) if not stat or stat.type ~= "directory" then error("ERROR: " .. path .. " is not a zip file or a folder") end bundle = folderBundle(path) end parts[n] = bundle end if #parts == 1 then return parts[1] end return combinedBundle(parts) end local function commonBundle(bundlePaths, mainPath, args) mainPath = mainPath or "main.lua" local bundle = assert(makeBundle(bundlePaths)) luvi.bundle = bundle bundle.paths = bundlePaths bundle.mainPath = mainPath function bundle.action(path, action, ...) -- If it's a real path, run it directly. if uv.fs_access(path, "r") then return action(path) end -- Otherwise, copy to a temporary folder and run from there local data, err = bundle.readfile(path) if not data then return nil, err end local dir = assert(uv.fs_mkdtemp(pathJoin(tmpBase, "lib-XXXXXX"))) path = pathJoin(dir, path:match("[^/\\]+$")) local fd = uv.fs_open(path, "w", 384) -- 0600 uv.fs_write(fd, data, 0) uv.fs_close(fd) local success, ret = pcall(action, path, ...) uv.fs_unlink(path) uv.fs_rmdir(dir) assert(success, ret) return ret end function bundle.register(name, path) if not path then path = name + ".lua" end package.preload[name] = function (...) local lua = assert(bundle.readfile(path)) return assert(loadstring(lua, "bundle:" .. path))(...) end end _G.args = args -- Auto-register the require system if present local mainRequire local stat = bundle.stat("deps/require.lua") if stat and stat.type == "file" then bundle.register('require', "deps/require.lua") mainRequire = require('require')("bundle:main.lua") end -- Auto-setup global p and libuv version of print if mainRequire and bundle.stat("deps/pretty-print") or bundle.stat("deps/pretty-print.lua") then _G.p = mainRequire('pretty-print').prettyPrint end if not args then return bundle, mainRequire end if mainRequire then return mainRequire("./" .. mainPath) else local main = bundle.readfile(mainPath) if not main then error("Missing " .. mainPath .. " in " .. bundle.base) end local fn = assert(loadstring(main, "bundle:" .. mainPath)) return fn(unpack(args)) end end -- Legacy export for makeBundle luvi.makeBundle = makeBundle return { folderBundle = folderBundle, chrootBundle = chrootBundle, zipBundle = zipBundle, buildBundle = buildBundle, combinedBundle = combinedBundle, makeBundle = makeBundle, commonBundle = commonBundle, }
apache-2.0
SalvationDevelopment/Salvation-Scripts-Production
c95943058.lua
2
2571
--E-HERO ヘル・ゲイナー function c95943058.initial_effect(c) --extra atk local e1=Effect.CreateEffect(c) e1:SetDescription(aux.Stringid(95943058,0)) e1:SetProperty(EFFECT_FLAG_CARD_TARGET) e1:SetType(EFFECT_TYPE_IGNITION) e1:SetRange(LOCATION_MZONE) e1:SetCondition(c95943058.condition) e1:SetCost(c95943058.cost) e1:SetTarget(c95943058.target) e1:SetOperation(c95943058.operation) c:RegisterEffect(e1) end function c95943058.condition(e,tp,eg,ep,ev,re,r,rp) return Duel.IsAbleToEnterBP() end function c95943058.cost(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return e:GetHandler():IsAbleToRemoveAsCost() end Duel.Remove(e:GetHandler(),POS_FACEUP,REASON_COST) end function c95943058.filter(c) return c:IsFaceup() and c:IsRace(RACE_FIEND) and not c:IsHasEffect(EFFECT_EXTRA_ATTACK) end function c95943058.target(e,tp,eg,ep,ev,re,r,rp,chk,chkc) if chkc then return chkc:IsLocation(LOCATION_MZONE) and chkc:IsControler(tp) and c95943058.filter(chkc) end if chk==0 then return Duel.IsExistingTarget(c95943058.filter,tp,LOCATION_MZONE,0,1,e:GetHandler()) end Duel.Hint(HINT_SELECTMSG,tp,HINTMSG_FACEUP) Duel.SelectTarget(tp,c95943058.filter,tp,LOCATION_MZONE,0,1,1,e:GetHandler()) end function c95943058.operation(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() --extra atk local tc=Duel.GetFirstTarget() if tc:IsRelateToEffect(e) then local e1=Effect.CreateEffect(c) e1:SetType(EFFECT_TYPE_SINGLE) e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE) e1:SetCode(EFFECT_EXTRA_ATTACK) e1:SetReset(RESET_EVENT+0x1fe0000) e1:SetValue(1) tc:RegisterEffect(e1) end --sp summon local e2=Effect.CreateEffect(c) e2:SetDescription(aux.Stringid(95943058,1)) e2:SetCategory(CATEGORY_SPECIAL_SUMMON) e2:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_TRIGGER_F) e2:SetRange(LOCATION_REMOVED) e2:SetCode(EVENT_PHASE+PHASE_STANDBY) e2:SetCountLimit(1) e2:SetReset(RESET_EVENT+0x1fe0000+RESET_PHASE+PHASE_STANDBY+RESET_SELF_TURN,2) e2:SetCondition(c95943058.spcon) e2:SetTarget(c95943058.sptg) e2:SetOperation(c95943058.spop) e2:SetLabel(Duel.GetTurnCount(tp)+2) c:RegisterEffect(e2) end function c95943058.spcon(e,tp,eg,ep,ev,re,r,rp) return Duel.GetTurnPlayer()==tp and e:GetLabel()==Duel.GetTurnCount(tp) end function c95943058.sptg(e,tp,eg,ep,ev,re,r,rp,chk) if chk==0 then return true end Duel.SetOperationInfo(0,CATEGORY_SPECIAL_SUMMON,e:GetHandler(),1,0,0) end function c95943058.spop(e,tp,eg,ep,ev,re,r,rp) local c=e:GetHandler() if not c:IsRelateToEffect(e) then return end Duel.SpecialSummon(c,0,tp,tp,false,false,POS_FACEUP_ATTACK) end
gpl-2.0