repo_name
stringlengths
6
69
path
stringlengths
6
178
copies
stringclasses
278 values
size
stringlengths
4
7
content
stringlengths
671
917k
license
stringclasses
15 values
Ninjistix/darkstar
scripts/zones/Lower_Jeuno/npcs/_l10.lua
3
2485
----------------------------------- -- Area: Lower Jeuno -- NPC: Streetlamp -- Involved in Quests: Community Service -- !pos -18 0 -4 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/NPCIDs"); require("scripts/zones/Lower_Jeuno/TextIDs"); -- lamp id vary from 17780881 to 17780892 -- lamp cs vary from 0x0078 to 0x0083 (120 to 131) local lampNum = 10; local lampId = lampIdOffset + lampNum; local cs = lampCsOffset + lampNum; function onTrade(player,npc,trade) end; function onTrigger(player,npc) local hour = VanadielHour(); local playerOnQuest = GetServerVariable("[JEUNO]CommService"); -- player is on the quest if playerOnQuest == player:getID() then if hour >= 20 and hour < 21 then player:startEvent(cs,4); -- It is too early to light it. You must wait until nine o'clock. elseif hour >= 21 or hour < 1 then if npc:getAnimation() == ANIMATION_OPEN_DOOR then player:startEvent(cs,2); -- The lamp is already lit. else player:startEvent(cs,1,lampNum); -- Light the lamp? Yes/No end else player:startEvent(cs,3); -- You have failed to light the lamps in time. end -- player is not on the quest else if npc:getAnimation() == ANIMATION_OPEN_DOOR then player:startEvent(cs,5); -- The lamp is lit. else player:startEvent(cs,6); -- You examine the lamp. It seems that it must be lit manually. end end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) if csid == cs and option == 1 then -- lamp is now lit GetNPCByID(lampId):setAnimation(ANIMATION_OPEN_DOOR); -- tell player how many remain local lampsRemaining = 12; for i=0,11 do local lamp = GetNPCByID(lampIdOffset + i); if lamp:getAnimation() == ANIMATION_OPEN_DOOR then lampsRemaining = lampsRemaining - 1; end end if lampsRemaining == 0 then player:messageSpecial(LAMP_MSG_OFFSET); else player:messageSpecial(LAMP_MSG_OFFSET+1,lampsRemaining); end end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/The_Sanctuary_of_ZiTah/npcs/Cermet_Headstone.lua
5
3092
----------------------------------- -- Area: The Sanctuary of Zi'Tah -- NPC: Cermet Headstone -- Involved in Mission: ZM5 Headstone Pilgrimage (Light Headstone) -- !pos 235 0 280 121 ----------------------------------- package.loaded["scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"] = nil; ----------------------------------- require("scripts/zones/The_Sanctuary_of_ZiTah/TextIDs"); require("scripts/zones/The_Sanctuary_of_ZiTah/MobIDs"); require("scripts/globals/keyitems"); require("scripts/globals/missions"); require("scripts/globals/titles"); function onTrade(player,npc,trade) end; function onTrigger(player,npc) -- HEADSTONE PILGRIMAGE if (player:getCurrentMission(ZILART) == HEADSTONE_PILGRIMAGE) then if (player:hasKeyItem(LIGHT_FRAGMENT)) then player:messageSpecial(ALREADY_OBTAINED_FRAG,LIGHT_FRAGMENT); elseif (os.time() >= npc:getLocalVar("cooldown")) then if (not GetMobByID(DOOMED_PILGRIMS):isSpawned()) then player:startEvent(200,LIGHT_FRAGMENT); else player:messageSpecial(SOMETHING_BETTER); end else player:addKeyItem(LIGHT_FRAGMENT); if ( player:hasKeyItem(ICE_FRAGMENT) and player:hasKeyItem(EARTH_FRAGMENT) and player:hasKeyItem(WATER_FRAGMENT) and player:hasKeyItem(FIRE_FRAGMENT) and player:hasKeyItem(LIGHTNING_FRAGMENT) and player:hasKeyItem(WIND_FRAGMENT) ) then player:messageSpecial(FOUND_ALL_FRAGS,LIGHT_FRAGMENT); player:addTitle(BEARER_OF_THE_EIGHT_PRAYERS); player:completeMission(ZILART,HEADSTONE_PILGRIMAGE); player:addMission(ZILART,THROUGH_THE_QUICKSAND_CAVES); else player:messageSpecial(KEYITEM_OBTAINED,LIGHT_FRAGMENT); end end -- SOUL SEARCHING elseif (player:hasCompletedMission(ZILART,THE_CHAMBER_OF_ORACLES) and not player:hasCompleteQuest(OUTLANDS,SOUL_SEARCHING)) then player:addQuest(OUTLANDS,SOUL_SEARCHING); player:startEvent(202,PRISMATIC_FRAGMENT); -- DEFAULT DIALOGS elseif (player:hasCompletedMission(ZILART,HEADSTONE_PILGRIMAGE)) then player:messageSpecial(ZILART_MONUMENT); else player:messageSpecial(CANNOT_REMOVE_FRAG); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) -- HEADSTONE PILGRIMAGE if (csid == 200 and option == 1) then SpawnMob(DOOMED_PILGRIMS):updateClaim(player); -- SOUL SEARCHING elseif (csid == 202) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13416); else player:tradeComplete(); player:addItem(13416); -- Bat Earring player:messageSpecial(ITEM_OBTAINED,13416); player:completeQuest(OUTLANDS,SOUL_SEARCHING); player:addTitle(GUIDER_OF_SOULS_TO_THE_SANCTUARY); end end end;
gpl-3.0
Ninjistix/darkstar
scripts/zones/Lower_Jeuno/npcs/Tuh_Almobankha.lua
5
3724
----------------------------------- -- Area: Lower Jeuno -- NPC: Tuh Almobankha -- Title Change NPC -- !pos -14 0 -61 245 ----------------------------------- require("scripts/globals/titles"); local title2 = { BROWN_MAGE_GUINEA_PIG , BROWN_MAGIC_BYPRODUCT , RESEARCHER_OF_CLASSICS , TORCHBEARER , FORTUNETELLER_IN_TRAINING , CHOCOBO_TRAINER , CLOCK_TOWER_PRESERVATIONIST , LIFE_SAVER , CARD_COLLECTOR , TWOS_COMPANY , TRADER_OF_ANTIQUITIES , GOBLINS_EXCLUSIVE_FASHION_MANNEQUIN , TENSHODO_MEMBER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { ACTIVIST_FOR_KINDNESS , ENVOY_TO_THE_NORTH , EXORCIST_IN_TRAINING , FOOLS_ERRAND_RUNNER , STREET_SWEEPER , MERCY_ERRAND_RUNNER , BELIEVER_OF_ALTANA , TRADER_OF_MYSTERIES , WANDERING_MINSTREL , ANIMAL_TRAINER , HAVE_WINGS_WILL_FLY , ROD_RETRIEVER , DESTINED_FELLOW , TROUPE_BRILIOTH_DANCER , PROMISING_DANCER , STARDUST_DANCER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { TIMEKEEPER , BRINGER_OF_BLISS , PROFESSIONAL_LOAFER , TRADER_OF_RENOWN , HORIZON_BREAKER , SUMMIT_BREAKER , BROWN_BELT , DUCAL_DUPE , CHOCOBO_LOVE_GURU , PICKUP_ARTIST , WORTHY_OF_TRUST , A_FRIEND_INDEED , CHOCOROOKIE , CRYSTAL_STAKES_CUPHOLDER , WINNING_OWNER , VICTORIOUS_OWNER , TRIUMPHANT_OWNER , HIGH_ROLLER , FORTUNES_FAVORITE , CHOCOCHAMPION , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { PARAGON_OF_BEASTMASTER_EXCELLENCE , PARAGON_OF_BARD_EXCELLENCE , SKY_BREAKER , BLACK_BELT , GREEDALOX , CLOUD_BREAKER , STAR_BREAKER , ULTIMATE_CHAMPION_OF_THE_WORLD , DYNAMISJEUNO_INTERLOPER , DYNAMISBEAUCEDINE_INTERLOPER , DYNAMISXARCABARD_INTERLOPER , DYNAMISQUFIM_INTERLOPER , CONQUEROR_OF_FATE , SUPERHERO , SUPERHEROINE , ELEGANT_DANCER , DAZZLING_DANCE_DIVA , GRIMOIRE_BEARER , FELLOW_FORTIFIER , BUSHIN_ASPIRANT , BUSHIN_RYU_INHERITOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { GRAND_GREEDALOX , SILENCER_OF_THE_ECHO , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title7 = { 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } function onTrade(player,npc,trade) end; function onTrigger(player,npc) player:startEvent(10014,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==10014) then if (option > 0 and option <29) then if (player:delGil(400)) then player:setTitle( title2[option] ) end elseif (option > 256 and option <285) then if (player:delGil(500)) then player:setTitle( title3[option - 256] ) end elseif (option > 512 and option < 541) then if (player:delGil(600)) then player:setTitle( title4[option - 512] ) end elseif (option > 768 and option <797) then if (player:delGil(700)) then player:setTitle( title5[option - 768] ) end elseif (option > 1024 and option < 1053) then if (player:delGil(800)) then player:setTitle( title6[option - 1024] ) end end end end;
gpl-3.0
Ninjistix/darkstar
scripts/globals/mobskills/mangle.lua
37
1070
--------------------------------------------- -- Mangle -- Family: Qutrub -- Description: Deals damage in a threefold attack to targets in a fan-shaped area of effect. -- Type: Physical -- Utsusemi/Blink absorb: 3 shadows -- Range: Front cone -- Notes: Used only when wielding their initial sword, or the dagger on their backs. --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) if (mob:AnimationSub() == 0 or mob:AnimationSub() == 2) then return 0; else return 1; end end; function onMobWeaponSkill(target, mob, skill) local numhits = 3; local accmod = 1; local dmgmod = .8; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); target:delHP(dmg); return dmg; end;
gpl-3.0
mandersan/premake-core
modules/xcode/tests/test_xcode_dependencies.lua
3
9840
-- -- tests/actions/xcode/test_xcode_dependencies.lua -- Automated test suite for Xcode project dependencies. -- Copyright (c) 2009-2011 Jason Perkins and the Premake project -- local suite = test.declare("xcode_deps") local p = premake local xcode = p.modules.xcode --------------------------------------------------------------------------- -- Setup/Teardown --------------------------------------------------------------------------- local wks, prj, prj2, tr function suite.teardown() wks = nil prj = nil prj2 = nil tr = nil end function suite.setup() _TARGET_OS = "macosx" p.action.set('xcode4') wks, prj = test.createWorkspace() links { "MyProject2" } prj2 = test.createproject(wks) kind "StaticLib" configuration "Debug" targetsuffix "-d" end local function prepare() wks = p.oven.bakeWorkspace(wks) xcode.prepareWorkspace(wks) local prj3 = p.workspace.getproject(wks, 1) --prj2 = test.getproject(wks, 2) tr = xcode.buildprjtree(prj3) end --------------------------------------------------------------------------- -- PBXBuildFile tests --------------------------------------------------------------------------- function suite.PBXBuildFile_ListsDependencyTargets_OnStaticLib() prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 5931FBCA4D31453CD21C5A0A /* libMyProject2-d.a in Frameworks */ = {isa = PBXBuildFile; fileRef = CCB6C53210CA9664049C1B72 /* libMyProject2-d.a */; }; /* End PBXBuildFile section */ ]] end function suite.PBXBuildFile_ListsDependencyTargets_OnSharedLib() kind "SharedLib" prepare() xcode.PBXBuildFile(tr) test.capture [[ /* Begin PBXBuildFile section */ 1BC538B0FA67D422AF49D6F0 /* libMyProject2-d.dylib in Frameworks */ = {isa = PBXBuildFile; fileRef = 107168B810144BEA4A68FEF8 /* libMyProject2-d.dylib */; }; /* End PBXBuildFile section */ ]] end --------------------------------------------------------------------------- -- PBXContainerItemProxy tests --------------------------------------------------------------------------- function suite.PBXContainerItemProxy_ListsProjectConfigs() prepare() xcode.PBXContainerItemProxy(tr) test.capture [[ /* Begin PBXContainerItemProxy section */ 17DF877139AB34A376605DB1 /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = CBD893DEB01F9C10340CCA1E /* MyProject2.xcodeproj */; proxyType = 2; remoteGlobalIDString = E052136F28C2F7A16D61C9AF; remoteInfo = "libMyProject2-d.a"; }; 6A19FA0A8BE5A73CC89AD04A /* PBXContainerItemProxy */ = { isa = PBXContainerItemProxy; containerPortal = CBD893DEB01F9C10340CCA1E /* MyProject2.xcodeproj */; proxyType = 1; remoteGlobalIDString = DA5DB975C549DF670D2FA7B5; remoteInfo = "libMyProject2-d.a"; }; /* End PBXContainerItemProxy section */ ]] end --------------------------------------------------------------------------- -- PBXFileReference tests --------------------------------------------------------------------------- function suite.PBXFileReference_ListsDependencies() prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; CBD893DEB01F9C10340CCA1E /* libMyProject2-d.a */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = "MyProject2.xcodeproj"; path = MyProject2.xcodeproj; sourceTree = SOURCE_ROOT; }; /* End PBXFileReference section */ ]] end function suite.PBXFileReference_UsesRelativePaths() prj.location = "MyProject" prj2.location = "MyProject2" prepare() xcode.PBXFileReference(tr) test.capture [[ /* Begin PBXFileReference section */ 149CF6C96C0269BB1E108509 /* libMyProject2-d.a */ = {isa = PBXFileReference; lastKnownFileType = "wrapper.pb-project"; name = "MyProject2.xcodeproj"; path = ../MyProject2.xcodeproj; sourceTree = SOURCE_ROOT; }; 19A5C4E61D1697189E833B26 /* MyProject */ = {isa = PBXFileReference; explicitFileType = "compiled.mach-o.executable"; includeInIndex = 0; name = MyProject; path = MyProject; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXFileReference section */ ]] end --------------------------------------------------------------------------- -- PBXFrameworksBuildPhase tests --------------------------------------------------------------------------- function suite.PBXFrameworksBuildPhase_ListsDependencies_OnStaticLib() prepare() xcode.PBXFrameworksBuildPhase(tr) test.capture [[ /* Begin PBXFrameworksBuildPhase section */ 9FDD37564328C0885DF98D96 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 5931FBCA4D31453CD21C5A0A /* libMyProject2-d.a in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ ]] end function suite.PBXFrameworksBuildPhase_ListsDependencies_OnSharedLib() kind "SharedLib" prepare() xcode.PBXFrameworksBuildPhase(tr) test.capture [[ /* Begin PBXFrameworksBuildPhase section */ 9FDD37564328C0885DF98D96 /* Frameworks */ = { isa = PBXFrameworksBuildPhase; buildActionMask = 2147483647; files = ( 1BC538B0FA67D422AF49D6F0 /* libMyProject2-d.dylib in Frameworks */, ); runOnlyForDeploymentPostprocessing = 0; }; /* End PBXFrameworksBuildPhase section */ ]] end --------------------------------------------------------------------------- -- PBXGroup tests --------------------------------------------------------------------------- function suite.PBXGroup_ListsDependencies() prepare() xcode.PBXGroup(tr) test.capture [[ /* Begin PBXGroup section */ 12F5A37D963B00EFBF8281BD /* MyProject */ = { isa = PBXGroup; children = ( A6C936B49B3FADE6EA134CF4 /* Products */, 9D968EAA920D05DCE0E0A4EA /* Projects */, ); name = MyProject; sourceTree = "<group>"; }; 9D968EAA920D05DCE0E0A4EA /* Projects */ = { isa = PBXGroup; children = ( CBD893DEB01F9C10340CCA1E /* MyProject2.xcodeproj */, ); name = Projects; sourceTree = "<group>"; }; A6C936B49B3FADE6EA134CF4 /* Products */ = { isa = PBXGroup; children = ( 19A5C4E61D1697189E833B26 /* MyProject */, ); name = Products; sourceTree = "<group>"; }; C7F36A91F7853983D29278D1 /* Products */ = { isa = PBXGroup; children = ( CCB6C53210CA9664049C1B72 /* libMyProject2-d.a */, ); name = Products; sourceTree = "<group>"; }; /* End PBXGroup section */ ]] end --------------------------------------------------------------------------- -- PBXNativeTarget tests --------------------------------------------------------------------------- function suite.PBXNativeTarget_ListsDependencies() prepare() xcode.PBXNativeTarget(tr) test.capture [[ /* Begin PBXNativeTarget section */ 48B5980C775BEBFED09D464C /* MyProject */ = { isa = PBXNativeTarget; buildConfigurationList = 8E187FB5316408E74C34D5F5 /* Build configuration list for PBXNativeTarget "MyProject" */; buildPhases = ( 0FC4B7F6B3104128CDE10E36 /* Resources */, 7971D14D1CBD5A7F378E278D /* Sources */, 9FDD37564328C0885DF98D96 /* Frameworks */, ); buildRules = ( ); dependencies = ( B5ABA79AE53D768CC04AB5DA /* PBXTargetDependency */, ); name = MyProject; productInstallPath = "$(HOME)/bin"; productName = MyProject; productReference = 19A5C4E61D1697189E833B26 /* MyProject */; productType = "com.apple.product-type.tool"; }; /* End PBXNativeTarget section */ ]] end --------------------------------------------------------------------------- -- PBXProject tests --------------------------------------------------------------------------- function suite.PBXProject_ListsDependencies() prepare() xcode.PBXProject(tr) test.capture [[ /* Begin PBXProject section */ 08FB7793FE84155DC02AAC07 /* Project object */ = { isa = PBXProject; buildConfigurationList = 1DEB928908733DD80010E9CD /* Build configuration list for PBXProject "MyProject" */; compatibilityVersion = "Xcode 3.2"; hasScannedForEncodings = 1; mainGroup = 12F5A37D963B00EFBF8281BD /* MyProject */; projectDirPath = ""; projectReferences = ( { ProductGroup = C7F36A91F7853983D29278D1 /* Products */; ProjectRef = CBD893DEB01F9C10340CCA1E /* MyProject2.xcodeproj */; }, ); projectRoot = ""; targets = ( 48B5980C775BEBFED09D464C /* MyProject */, ); }; /* End PBXProject section */ ]] end --------------------------------------------------------------------------- -- PBXReferenceProxy tests --------------------------------------------------------------------------- function suite.PBXReferenceProxy_ListsDependencies() prepare() xcode.PBXReferenceProxy(tr) test.capture [[ /* Begin PBXReferenceProxy section */ CCB6C53210CA9664049C1B72 /* libMyProject2-d.a */ = { isa = PBXReferenceProxy; fileType = archive.ar; path = "libMyProject2-d.a"; remoteRef = 17DF877139AB34A376605DB1 /* PBXContainerItemProxy */; sourceTree = BUILT_PRODUCTS_DIR; }; /* End PBXReferenceProxy section */ ]] end --------------------------------------------------------------------------- -- PBXTargetDependency tests --------------------------------------------------------------------------- function suite.PBXTargetDependency_ListsDependencies() prepare() xcode.PBXTargetDependency(tr) test.capture [[ /* Begin PBXTargetDependency section */ B5ABA79AE53D768CC04AB5DA /* PBXTargetDependency */ = { isa = PBXTargetDependency; name = "libMyProject2-d.a"; targetProxy = 6A19FA0A8BE5A73CC89AD04A /* PBXContainerItemProxy */; }; /* End PBXTargetDependency section */ ]] end
bsd-3-clause
davidbuzz/ardupilot
libraries/AP_Scripting/examples/orbit_follow.lua
9
1546
-- example that does an orbit of a vehicle that is being followed -- by adjusting the follow offset X and Y parameters -- user settable FOLL_ORB_TIME and FOLL_ORB_RADIUS parameters -- are provided for the time for one orbit (in seconds) and the radius -- of the orbit -- setup param block for FOLL_ extensions local PARAM_TABLE_KEY = 83 local PARAM_TABLE_PREFIX = "FOLL_" assert(param:add_table(PARAM_TABLE_KEY, PARAM_TABLE_PREFIX, 2), 'could not add param table') function bind_param(name) local p = Parameter() assert(p:init(name), string.format('could not find %s parameter', name)) return p end function bind_add_param(name, index, default_value) assert(param:add_param(PARAM_TABLE_KEY, index, name, default_value), string.format('could not add %s', PARAM_TABLE_PREFIX .. name)) return bind_param(PARAM_TABLE_PREFIX .. name) end local FOLL_OFS_X = bind_param("FOLL_OFS_X") local FOLL_OFS_Y = bind_param("FOLL_OFS_Y") local FOLL_ORB_RADIUS = bind_add_param("ORB_RADIUS", 1, 5) local FOLL_ORB_TIME = bind_add_param("ORB_TIME", 2, 10) local t = 0 function update() t = t + 0.1 --gcs:send_text(0, string.format("t=%.2f X=%.2f Y=%.2f", t, FOLL_OFS_X:get(), FOLL_OFS_Y:get())) if t > FOLL_ORB_TIME:get() then t = t - FOLL_ORB_TIME:get() end FOLL_OFS_X:set(math.cos((t/FOLL_ORB_TIME:get())*2*math.pi)*FOLL_ORB_RADIUS:get()) FOLL_OFS_Y:set(math.sin((t/FOLL_ORB_TIME:get())*2*math.pi)*FOLL_ORB_RADIUS:get()) return update, 100 end gcs:send_text(0, string.format("orbit started")) return update, 100
gpl-3.0
Ninjistix/darkstar
scripts/zones/Abyssea-Konschtat/npcs/Conflux_Surveyor.lua
3
3234
----------------------------------- -- Zone: Abyssea - Konschtat -- NPC: Conflux Surveyor -- Type: -- !pos 133.000 -72.738 -824.000 15 ----------------------------------- package.loaded["scripts/zones/Abyssea-Konschtat/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/abyssea"); require("scripts/zones/Abyssea-Konschtat/TextIDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local visitant = 0; local prevtime = player:getVar("Abyssea_Time"); local STONES = getTravStonesTotal(player); local SOJOURN = getAbyssiteTotal(player,SOJOURN); if (player:hasStatusEffect(EFFECT_VISITANT)) then visitant = 60; end player:startEvent(2001,0,visitant,prevtime,STONES,SOJOURN,0,0,0); end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); local SOJOURN = getAbyssiteTotal(player,"SOJOURN"); local duration = 0; local prevtime = player:getVar("Abyssea_Time"); -- Gets reduced by Visitants "on tic". if (prevtime > 7200) then prevtime = 7200; duration = prevtime; else duration = prevtime; end duration = duration+(SOJOURN *180); if (csid == 2001) then if (option == 2) then -- Use no stones, use previous remaining time player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0); player:setVar("Abyssea_Time",duration); elseif (option == 65538) then -- Use 1 stone duration = ((duration + 1800) * VISITANT_BONUS); player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0); player:setVar("Abyssea_Time",duration); spendTravStones(player,1); elseif (option == 65539) then -- Use 1 stone player:PrintToPlayer( "Not implemented yet, sorry!" ); -- Todo: extend time elseif (option == 131074) then -- Use 2 stone duration = ((duration + 3600) * VISITANT_BONUS); player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0); player:setVar("Abyssea_Time",duration); spendTravStones(player,2); elseif (option == 131075) then -- Use 2 stone player:PrintToPlayer( "Not implemented yet, sorry!" ); -- Todo: extend time elseif (option == 196610) then -- Use 3 stone duration = ((duration + 5400) * VISITANT_BONUS); player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0); player:setVar("Abyssea_Time",duration); spendTravStones(player,3); elseif (option == 196611) then -- Use 3 stone player:PrintToPlayer( "Not implemented yet, sorry!" ); -- Todo: extend time elseif (option == 262146) then -- Use 4 stone duration = ((duration + 7200) * VISITANT_BONUS); player:addStatusEffect(EFFECT_VISITANT,0,3,duration,0,0); player:setVar("Abyssea_Time",duration); spendTravStones(player,4); end end end;
gpl-3.0
ASHRAF97/ASHRAFKASPER
plugins/getfile.lua
14
1025
--[[ ▀▄ ▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀▄▀▄▄▀▀▄▄▀▀▄▄▀▀▄▄▀▀ ▀▄ ▄▀ ▀▄ ▄▀ ▀▄ ▄▀ BY MOHAMMED HISHAM ▀▄ ▄▀ ▀▄ ▄▀ BY MOHAMMEDHISHAM (@TH3BOSS) ▀▄ ▄▀ ▀▄ ▄▀ JUST WRITED BY MOHAMMED HISHAM ▀▄ ▄▀ ▀▄ ▄▀ get file : جلب ملف ▀▄ ▄▀ ▀▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀▄▄▀▀▄▄▀▄▄▀▀ --]] local function run(msg, matches) if matches[1] == "جلب ملف" then local file = matches[2] if is_sudo(msg) then --sudo only ! local receiver = get_receiver(msg) send_document(receiver, "./plugins/"..file..".lua", ok_cb, false) else return nil end end end return { patterns = { "^(جلب ملف) (.*)$" }, run = run }
gpl-2.0
fjz13/Medusa
Test/Test/Dev/Resource/Script/Medusa/Lib/stringExtend.lua
4
1166
function string.split(str, delimiter) if (delimiter=='') then return false end local pos,arr = 0, {} -- for each divider found for st,sp in function() return string.find(str, delimiter, pos, true) end do table.insert(arr, string.sub(str, pos, st - 1)) pos = sp + 1 end table.insert(arr, string.sub(str, pos)) return arr end function string.ltrim(str) return string.gsub(str, "^[ \t\n\r]+", "") end function string.rtrim(str) return string.gsub(str, "[ \t\n\r]+$", "") end function string.trim(str) str = string.gsub(str, "^[ \t\n\r]+", "") return string.gsub(str, "[ \t\n\r]+$", "") end function string.LastPart(str) local index=1; while true do local begin,_= string.find(str,".",index,true); if begin then index=begin+1;else break;end end return string.sub(str,index); end function string.PrevPart(str) local index=1; while true do local begin,_= string.find(str,".",index,true); if begin then index=begin+1;else break;end end if index==1 then return str; else return string.sub(str,1,index-2); end end function string.CombinePart(str1,str2) return str1.."."..str2; end
mit
Ninjistix/darkstar
scripts/zones/Temple_of_Uggalepih/npcs/_4fx.lua
5
1651
----------------------------------- -- Area: Temple of Uggalepih -- NPC: Granite Door -- !pos 340 0.1 329 159 ----------------------------------- package.loaded["scripts/zones/Temple_of_Uggalepih/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Temple_of_Uggalepih/TextIDs"); require("scripts/globals/missions"); require("scripts/globals/keyitems"); ----------------------------------- function onTrade(player,npc,trade) if (trade:hasItemQty(1143,1) and trade:getItemCount() == 1 and player:getZPos() < 332) then -- Trade cursed key if (player:getCurrentMission(WINDURST) == AWAKENING_OF_THE_GODS and player:getVar("MissionStatus") == 4) then player:tradeComplete(); player:startEvent(23); else player:tradeComplete(); player:messageSpecial(YOUR_KEY_BREAKS,0,1143); player:startEvent(25); end else player:messageSpecial(NOTHING_HAPPENS); end end; function onTrigger(player,npc) if (player:getZPos() < 332) then player:messageSpecial(DOOR_LOCKED); else player:startEvent(26); end end; function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 23) then player:setPos(340,0,333); player:delKeyItem(BLANK_BOOK_OF_THE_GODS); player:addKeyItem(BOOK_OF_THE_GODS); player:messageSpecial(KEYITEM_OBTAINED,BOOK_OF_THE_GODS); player:setVar("MissionStatus",5); end end;
gpl-3.0
Tele-Fox/CYR
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-3.0
dmccuskey/dmc-websockets
dmc_corona/lib/dmc_lua/lua_error.lua
46
3628
--====================================================================-- -- lua_error.lua -- -- Documentation: -- * http://github.com/dmccuskey/lua-error --====================================================================-- --[[ The MIT License (MIT) Copyright (C) 2014-2015 David McCuskey. All Rights Reserved. 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. --]] --====================================================================-- --== DMC Lua Library : Lua Error --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.3.0" --====================================================================-- --== Imports local Class = require 'lua_class' -- Check imports -- TODO: work on this assert( Class, "lua_error: requires lua_class" ) if checkModule then checkModule( Class, '1.1.2' ) end --====================================================================-- --== Setup, Constants -- none --====================================================================-- --== Support Functions -- based on https://gist.github.com/cwarden/1207556 local function try( funcs ) local try_f, catch_f, finally_f = funcs[1], funcs[2], funcs[3] assert( try_f, "lua-error: missing function for try()" ) --==-- local status, result = pcall(try_f) if not status and catch_f then catch_f(result) end if finally_f then finally_f() end return result end local function catch(f) return f[1] end local function finally(f) return f[1] end --====================================================================-- --== Error Base Class --====================================================================-- local Error = newClass( nil, { name="Error Instance" } ) --== Class Constants ==-- Error.__version = VERSION Error.DEFAULT_PREFIX = "ERROR: " Error.DEFAULT_MESSAGE = "There was an error" function Error:__new__( message, params ) message = message or self.DEFAULT_MESSAGE params = params or {} params.prefix = params.prefix or self.DEFAULT_PREFIX --==-- -- guard subclasses if self.is_class then return end -- save args self.prefix = params.prefix self.message = message self.traceback = debug.traceback() end -- must return a string -- function Error:__tostring__( id ) return table.concat( { self.prefix, self.message, "\n", self.traceback } ) end --====================================================================-- --== Error API Setup --====================================================================-- -- globals _G.try = try _G.catch = catch _G.finally = finally return Error
mit
alimashmamali/test
plugins/banhammer.lua
1085
11557
local function pre_process(msg) -- SERVICE MESSAGE if msg.action and msg.action.type then local action = msg.action.type -- Check if banned user joins chat by link if action == 'chat_add_user_link' then local user_id = msg.from.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs kick_user(user_id, msg.to.id) end end -- Check if banned user joins chat if action == 'chat_add_user' then local user_id = msg.action.user.id print('Checking invited user '..user_id) local banned = is_banned(user_id, msg.to.id) if banned or is_gbanned(user_id) then -- Check it with redis print('User is banned!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs kick_user(user_id, msg.to.id) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:incr(banhash) local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id local banaddredis = redis:get(banhash) if banaddredis then if tonumber(banaddredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times end if tonumber(banaddredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id redis:set(banhash, 0)-- Reset the Counter end end end if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings'] then if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end end end if msg.action.user.username ~= nil then if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs kick_user(msg.action.user.id, msg.to.id) end end end -- No further checks return msg end -- banned user is talking ! if msg.to.type == 'chat' then local data = load_data(_config.moderation.data) local group = msg.to.id local texttext = 'groups' --if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not --chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false) --return --end local user_id = msg.from.id local chat_id = msg.to.id local banned = is_banned(user_id, chat_id) if banned or is_gbanned(user_id) then -- Check it with redis print('Banned user talking!') local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs kick_user(user_id, chat_id) msg.text = '' end end return msg end local function kick_ban_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local user_id = member_id local member = result.username local chat_id = extra.chat_id local from_id = extra.from_id local get_cmd = extra.get_cmd local receiver = "chat#id"..chat_id if get_cmd == "kick" then if member_id == from_id then return send_large_msg(receiver, "You can't kick yourself") end if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't kick mods/owner/admins") end return kick_user(member_id, chat_id) elseif get_cmd == 'ban' then if is_momod2(member_id, chat_id) and not is_admin2(sender) then return send_large_msg(receiver, "You can't ban mods/owner/admins") end send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned') return ban_user(member_id, chat_id) elseif get_cmd == 'unban' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned') local hash = 'banned:'..chat_id redis:srem(hash, member_id) return 'User '..user_id..' unbanned' elseif get_cmd == 'banall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned') return banall_user(member_id, chat_id) elseif get_cmd == 'unbanall' then send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned') return unbanall_user(member_id, chat_id) end end local function run(msg, matches) if matches[1]:lower() == 'id' then if msg.to.type == "user" then return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id end if type(msg.reply_id) ~= "nil" then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") id = get_message(msg.reply_id,get_message_callback_id, false) elseif matches[1]:lower() == 'id' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ") return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id end end if matches[1]:lower() == 'kickme' then-- /kickme local receiver = get_receiver(msg) if msg.to.type == 'chat' then local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false) end end if not is_momod(msg) then -- Ignore normal users return end if matches[1]:lower() == "banlist" then -- Ban list ! local chat_id = msg.to.id if matches[2] and is_admin(msg) then chat_id = matches[2] end return ban_list(chat_id) end if matches[1]:lower() == 'ban' then-- /ban if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,ban_by_reply_admins, false) else msgr = get_message(msg.reply_id,ban_by_reply, false) end end local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't ban mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't ban your self !" end local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2]) ban_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'ban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unban' then -- /unban if type(msg.reply_id)~="nil" and is_momod(msg) then local msgr = get_message(msg.reply_id,unban_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then local user_id = targetuser local hash = 'banned:'..chat_id redis:srem(hash, user_id) local name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2]) return 'User '..user_id..' unbanned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unban', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'kick' then if type(msg.reply_id)~="nil" and is_momod(msg) then if is_admin(msg) then local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false) else msgr = get_message(msg.reply_id,Kick_by_reply, false) end end if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return end if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then return "you can't kick mods/owner/admins" end if tonumber(matches[2]) == tonumber(msg.from.id) then return "You can't kick your self !" end local user_id = matches[2] local chat_id = msg.to.id name = user_print_name(msg.from) savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2]) kick_user(user_id, chat_id) else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'kick', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if not is_admin(msg) then return end if matches[1]:lower() == 'banall' then -- Global ban if type(msg.reply_id) ~="nil" and is_admin(msg) then return get_message(msg.reply_id,banall_by_reply, false) end local user_id = matches[2] local chat_id = msg.to.id local targetuser = matches[2] if string.match(targetuser, '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end banall_user(targetuser) return 'User ['..user_id..' ] globally banned' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'banall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == 'unbanall' then -- Global unban local user_id = matches[2] local chat_id = msg.to.id if string.match(matches[2], '^%d+$') then if tonumber(matches[2]) == tonumber(our_id) then return false end unbanall_user(user_id) return 'User ['..user_id..' ] removed from global ban list' else local cbres_extra = { chat_id = msg.to.id, get_cmd = 'unbanall', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') res_user(username, kick_ban_res, cbres_extra) end end if matches[1]:lower() == "gbanlist" then -- Global ban list return banall_list() end end return { patterns = { "^[!/]([Bb]anall) (.*)$", "^[!/]([Bb]anall)$", "^[!/]([Bb]anlist) (.*)$", "^[!/]([Bb]anlist)$", "^[!/]([Gg]banlist)$", "^[!/]([Bb]an) (.*)$", "^[!/]([Kk]ick)$", "^[!/]([Uu]nban) (.*)$", "^[!/]([Uu]nbanall) (.*)$", "^[!/]([Uu]nbanall)$", "^[!/]([Kk]ick) (.*)$", "^[!/]([Kk]ickme)$", "^[!/]([Bb]an)$", "^[!/]([Uu]nban)$", "^[!/]([Ii]d)$", "^!!tgservice (.+)$" }, run = run, pre_process = pre_process }
gpl-2.0
EvPowerTeam/EV_OP
feeds/luci/libs/nixio/docsrc/nixio.TLSSocket.lua
173
2926
--- TLS Socket Object. -- TLS Sockets contain the underlying socket and context in the fields -- "socket" and "context". -- @cstyle instance module "nixio.TLSSocket" --- Initiate the TLS handshake as client with the server. -- @class function -- @name TLSSocket.connect -- @usage This function calls SSL_connect(). -- @usage You have to call either connect or accept before transmitting data. -- @see TLSSocket.accept -- @return true --- Wait for a TLS handshake from a client. -- @class function -- @name TLSSocket.accept -- @usage This function calls SSL_accept(). -- @usage You have to call either connect or accept before transmitting data. -- @see TLSSocket.connect -- @return true --- Send a message to the socket. -- @class function -- @name TLSSocket.send -- @usage This function calls SSL_write(). -- @usage <strong>Warning:</strong> It is not guaranteed that all data -- in the buffer is written at once. -- You have to check the return value - the number of bytes actually written - -- or use the safe IO functions in the high-level IO utility module. -- @usage Unlike standard Lua indexing the lowest offset and default is 0. -- @param buffer Buffer holding the data to be written. -- @param offset Offset to start reading the buffer from. (optional) -- @param length Length of chunk to read from the buffer. (optional) -- @return number of bytes written --- Send a message on the socket (This is an alias for send). -- See the send description for a detailed description. -- @class function -- @name TLSSocket.write -- @param buffer Buffer holding the data to be written. -- @param offset Offset to start reading the buffer from. (optional) -- @param length Length of chunk to read from the buffer. (optional) -- @see TLSSocket.send -- @return number of bytes written --- Receive a message on the socket. -- @class function -- @name TLSSocket.recv -- @usage This function calls SSL_read(). -- @usage <strong>Warning:</strong> It is not guaranteed that all requested data -- is read at once. -- You have to check the return value - the length of the buffer actually read - -- or use the safe IO functions in the high-level IO utility module. -- @usage The length of the return buffer is limited by the (compile time) -- nixio buffersize which is <em>nixio.const.buffersize</em> (8192 by default). -- Any read request greater than that will be safely truncated to this value. -- @param length Amount of data to read (in Bytes). -- @return buffer containing data successfully read --- Receive a message on the socket (This is an alias for recv). -- See the recv description for more details. -- @class function -- @name TLSSocket.read -- @param length Amount of data to read (in Bytes). -- @see TLSSocket.recv -- @return buffer containing data successfully read --- Shut down the TLS connection. -- @class function -- @name TLSSocket.shutdown -- @usage This function calls SSL_shutdown(). -- @return true
gpl-2.0
siggame/Joueur.lua
games/anarchy/fireDepartment.lua
2
4613
-- FireDepartment: Can put out fires completely. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local Building = require("games.anarchy.building") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- Can put out fires completely. -- @classmod FireDepartment local FireDepartment = class(Building) -- initializes a FireDepartment with basic logic as provided by the Creer code generator function FireDepartment:init(...) Building.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- The amount of fire removed from a building when bribed to extinguish a building. self.fireExtinguished = 0 --- (inherited) When true this building has already been bribed this turn and cannot be bribed again this turn. -- @field[bool] self.bribed -- @see Building.bribed --- (inherited) The Building directly to the east of this building, or nil if not present. -- @field[Building] self.buildingEast -- @see Building.buildingEast --- (inherited) The Building directly to the north of this building, or nil if not present. -- @field[Building] self.buildingNorth -- @see Building.buildingNorth --- (inherited) The Building directly to the south of this building, or nil if not present. -- @field[Building] self.buildingSouth -- @see Building.buildingSouth --- (inherited) The Building directly to the west of this building, or nil if not present. -- @field[Building] self.buildingWest -- @see Building.buildingWest --- (inherited) How much fire is currently burning the building, and thus how much damage it will take at the end of its owner's turn. 0 means no fire. -- @field[number] self.fire -- @see Building.fire --- (inherited) String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. -- @field[string] self.gameObjectName -- @see GameObject.gameObjectName --- (inherited) How much health this building currently has. When this reaches 0 the Building has been burned down. -- @field[number] self.health -- @see Building.health --- (inherited) A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. -- @field[string] self.id -- @see GameObject.id --- (inherited) True if this is the Headquarters of the owning player, false otherwise. Burning this down wins the game for the other Player. -- @field[bool] self.isHeadquarters -- @see Building.isHeadquarters --- (inherited) Any strings logged will be stored here. Intended for debugging. -- @field[{string, ...}] self.logs -- @see GameObject.logs --- (inherited) The player that owns this building. If it burns down (health reaches 0) that player gets an additional bribe(s). -- @field[Player] self.owner -- @see Building.owner --- (inherited) The location of the Building along the x-axis. -- @field[number] self.x -- @see Building.x --- (inherited) The location of the Building along the y-axis. -- @field[number] self.y -- @see Building.y end --- Bribes this FireDepartment to extinguish the some of the fire in a building. -- @tparam Building building The Building you want to extinguish. -- @treturn bool True if the bribe worked, false otherwise. function FireDepartment:extinguish(building) return not not (self:_runOnServer("extinguish", { building = building, })) end --- (inherited) Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @function FireDepartment:log -- @see GameObject:log -- @tparam string message A string to add to this GameObject's log. Intended for debugging. -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return FireDepartment
mit
yangboz/petulant-octo-dubstep
HP_ID_Print_App/cocos2d-x-3.2/cocos/scripting/lua-bindings/auto/api/SpriteBatchNode.lua
1
4454
-------------------------------- -- @module SpriteBatchNode -- @extend Node,TextureProtocol -------------------------------- -- @function [parent=#SpriteBatchNode] appendChild -- @param self -- @param #cc.Sprite sprite -------------------------------- -- @function [parent=#SpriteBatchNode] addSpriteWithoutQuad -- @param self -- @param #cc.Sprite sprite -- @param #int int -- @param #int int -- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode) -------------------------------- -- @function [parent=#SpriteBatchNode] reorderBatch -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#SpriteBatchNode] removeAllChildrenWithCleanup -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#SpriteBatchNode] lowestAtlasIndexInChild -- @param self -- @param #cc.Sprite sprite -- @return long#long ret (return value: long) -------------------------------- -- @function [parent=#SpriteBatchNode] atlasIndexForChild -- @param self -- @param #cc.Sprite sprite -- @param #int int -- @return long#long ret (return value: long) -------------------------------- -- @function [parent=#SpriteBatchNode] setTextureAtlas -- @param self -- @param #cc.TextureAtlas textureatlas -------------------------------- -- @function [parent=#SpriteBatchNode] getTexture -- @param self -- @return Texture2D#Texture2D ret (return value: cc.Texture2D) -------------------------------- -- @function [parent=#SpriteBatchNode] increaseAtlasCapacity -- @param self -------------------------------- -- @function [parent=#SpriteBatchNode] getTextureAtlas -- @param self -- @return TextureAtlas#TextureAtlas ret (return value: cc.TextureAtlas) -------------------------------- -- @function [parent=#SpriteBatchNode] insertQuadFromSprite -- @param self -- @param #cc.Sprite sprite -- @param #long long -------------------------------- -- @function [parent=#SpriteBatchNode] setTexture -- @param self -- @param #cc.Texture2D texture2d -------------------------------- -- @function [parent=#SpriteBatchNode] rebuildIndexInOrder -- @param self -- @param #cc.Sprite sprite -- @param #long long -- @return long#long ret (return value: long) -------------------------------- -- @function [parent=#SpriteBatchNode] highestAtlasIndexInChild -- @param self -- @param #cc.Sprite sprite -- @return long#long ret (return value: long) -------------------------------- -- @function [parent=#SpriteBatchNode] removeChildAtIndex -- @param self -- @param #long long -- @param #bool bool -------------------------------- -- @function [parent=#SpriteBatchNode] removeSpriteFromAtlas -- @param self -- @param #cc.Sprite sprite -------------------------------- -- @function [parent=#SpriteBatchNode] create -- @param self -- @param #string str -- @param #long long -- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode) -------------------------------- -- @function [parent=#SpriteBatchNode] createWithTexture -- @param self -- @param #cc.Texture2D texture2d -- @param #long long -- @return SpriteBatchNode#SpriteBatchNode ret (return value: cc.SpriteBatchNode) -------------------------------- -- @function [parent=#SpriteBatchNode] addChild -- @param self -- @param #cc.Node node -- @param #int int -- @param #int int -------------------------------- -- @function [parent=#SpriteBatchNode] draw -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table mat4 -- @param #unsigned int int -------------------------------- -- @function [parent=#SpriteBatchNode] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#SpriteBatchNode] visit -- @param self -- @param #cc.Renderer renderer -- @param #mat4_table mat4 -- @param #unsigned int int -------------------------------- -- @function [parent=#SpriteBatchNode] sortAllChildren -- @param self -------------------------------- -- @function [parent=#SpriteBatchNode] removeChild -- @param self -- @param #cc.Node node -- @param #bool bool -------------------------------- -- @function [parent=#SpriteBatchNode] reorderChild -- @param self -- @param #cc.Node node -- @param #int int return nil
mit
tltneon/NutScript
gamemode/core/sh_config.lua
2
6757
nut.config = nut.config or {} nut.config.stored = nut.config.stored or {} function nut.config.add(key, value, desc, callback, data, noNetworking, schemaOnly) local oldConfig = nut.config.stored[key] nut.config.stored[key] = {data = data, value = oldConfig and oldConfig.value or value, default = value, desc = desc, noNetworking = noNetworking, global = !schemaOnly, callback = callback} end function nut.config.setDefault(key, value) local config = nut.config.stored[key] if (config) then config.default = value end end function nut.config.forceSet(key, value, noSave) local config = nut.config.stored[key] if (config) then config.value = value end if (noSave) then nut.config.save() end end function nut.config.set(key, value) local config = nut.config.stored[key] if (config) then local oldValue = value config.value = value if (SERVER) then if (!config.noNetworking) then netstream.Start(nil, "cfgSet", key, value) end if (config.callback) then config.callback(oldValue, value) end nut.config.save() end end end function nut.config.get(key, default) local config = nut.config.stored[key] if (config) then if (config.value != nil) then return config.value elseif (config.default != nil) then return config.default end end return default end function nut.config.load() if (SERVER) then local globals = nut.data.get("config", nil, true, true) local data = nut.data.get("config", nil, false, true) if (globals) then for k, v in pairs(globals) do nut.config.stored[k] = nut.config.stored[k] or {} nut.config.stored[k].value = v end end if (data) then for k, v in pairs(data) do nut.config.stored[k] = nut.config.stored[k] or {} nut.config.stored[k].value = v end end end nut.util.include("nutscript/gamemode/config/sh_config.lua") hook.Run("InitializedConfig") end if (SERVER) then function nut.config.getChangedValues() local data = {} for k, v in pairs(nut.config.stored) do if (v.default != v.value) then data[k] = v.value end end return data end function nut.config.send(client) netstream.Start(client, "cfgList", nut.config.getChangedValues()) end function nut.config.save() local globals = {} local data = {} for k, v in pairs(nut.config.getChangedValues()) do if (nut.config.stored[k].global) then globals[k] = v else data[k] = v end end -- Global and schema data set respectively. nut.data.set("config", globals, true, true) nut.data.set("config", data, false, true) end netstream.Hook("cfgSet", function(client, key, value) // NEED TO ADD HOOK: CanPlayerModifyConfig if (client:IsSuperAdmin() and type(nut.config.stored[key].default) == type(value)) then nut.config.set(key, value) if (type(value) == "table") then local value2 = "[" local count = table.Count(value) local i = 1 for k, v in SortedPairs(value) do value2 = value2..v..(i == count and "]" or ", ") i = i + 1 end value = value2 end nut.util.notifyLocalized("cfgSet", nil, client:Name(), key, tostring(value), v) end end) else netstream.Hook("cfgList", function(data) for k, v in pairs(data) do if (nut.config.stored[k]) then nut.config.stored[k].value = v end end hook.Run("InitializedConfig", data) end) netstream.Hook("cfgSet", function(key, value) local config = nut.config.stored[key] if (config) then if (config.callback) then config.callback(config.value, value) end config.value = value local properties = nut.gui.properties if (IsValid(properties)) then local row = properties:GetCategory(L(config.data and config.data.category or "misc")):GetRow(key) if (IsValid(row)) then if (type(value) == "table" and value.r and value.g and value.b) then value = Vector(value.r / 255, value.g / 255, value.b / 255) end row:SetValue(value) end end end end) end if (CLIENT) then hook.Add("CreateMenuButtons", "nutConfig", function(tabs) if (LocalPlayer():IsSuperAdmin() and hook.Run("CanPlayerUseConfig", LocalPlayer()) != false) then tabs["config"] = function(panel) local scroll = panel:Add("DScrollPanel") scroll:Dock(FILL) local properties = scroll:Add("DProperties") properties:SetSize(panel:GetSize()) nut.gui.properties = properties -- We're about to store the categories in this buffer. local buffer = {} for k, v in pairs(nut.config.stored) do -- Get the category name. local index = v.data and v.data.category or "misc" -- Insert the config into the category list. buffer[index] = buffer[index] or {} buffer[index][k] = v end -- Loop through the categories in alphabetical order. for category, configs in SortedPairs(buffer) do category = L(category) -- Ditto, except we're looping through configs. for k, v in SortedPairs(configs) do -- Determine which type of panel to create. local form = v.data and v.data.form local value = nut.config.stored[k].default if (!form) then local formType = type(value) if (formType == "number") then form = "Int" value = tonumber(nut.config.get(k)) or value elseif (formType == "boolean") then form = "Boolean" value = util.tobool(nut.config.get(k)) else form = "Generic" end end -- VectorColor currently only exists for DProperties. if (form == "Generic" and type(value) == "table" and value.r and value.g and value.b) then -- Convert the color to a vector. value = Vector(value.r / 255, value.g / 255, value.b / 255) form = "VectorColor" end local delay = 1 if (form == "Boolean") then delay = 0 end -- Add a new row for the config to the properties. local row = properties:CreateRow(category, k) row:Setup(form, v.data and v.data.data or {}) row:SetValue(value) row:SetToolTip(v.desc) row.DataChanged = function(this, value) timer.Create("nutCfgSend"..k, delay, 1, function() if (IsValid(row)) then if (form == "VectorColor") then local vector = Vector(value) value = Color(math.floor(vector.x * 255), math.floor(vector.y * 255), math.floor(vector.z * 255)) elseif (form == "Int" or form == "Float") then value = tonumber(value) if (form == "Int") then value = math.Round(value) end elseif (form == "Boolean") then value = util.tobool(value) end netstream.Start("cfgSet", k, value) end end) end end end end end end) end
mit
harryzeng/skynet
service/gate.lua
46
1934
local skynet = require "skynet" local gateserver = require "snax.gateserver" local netpack = require "netpack" local watchdog local connection = {} -- fd -> connection : { fd , client, agent , ip, mode } local forwarding = {} -- agent -> connection skynet.register_protocol { name = "client", id = skynet.PTYPE_CLIENT, } local handler = {} function handler.open(source, conf) watchdog = conf.watchdog or source end function handler.message(fd, msg, sz) -- recv a package, forward it local c = connection[fd] local agent = c.agent if agent then skynet.redirect(agent, c.client, "client", 0, msg, sz) else skynet.send(watchdog, "lua", "socket", "data", fd, netpack.tostring(msg, sz)) end end function handler.connect(fd, addr) local c = { fd = fd, ip = addr, } connection[fd] = c skynet.send(watchdog, "lua", "socket", "open", fd, addr) end local function unforward(c) if c.agent then forwarding[c.agent] = nil c.agent = nil c.client = nil end end local function close_fd(fd) local c = connection[fd] if c then unforward(c) connection[fd] = nil end end function handler.disconnect(fd) close_fd(fd) skynet.send(watchdog, "lua", "socket", "close", fd) end function handler.error(fd, msg) close_fd(fd) skynet.send(watchdog, "lua", "socket", "error", fd, msg) end function handler.warning(fd, size) skynet.send(watchdog, "lua", "socket", "warning", fd, size) end local CMD = {} function CMD.forward(source, fd, client, address) local c = assert(connection[fd]) unforward(c) c.client = client or 0 c.agent = address or source forwarding[c.agent] = c gateserver.openclient(fd) end function CMD.accept(source, fd) local c = assert(connection[fd]) unforward(c) gateserver.openclient(fd) end function CMD.kick(source, fd) gateserver.closeclient(fd) end function handler.command(cmd, source, ...) local f = assert(CMD[cmd]) return f(source, ...) end gateserver.start(handler)
mit
magnum357i/Magnum-s-Aegisub-Scripts
automation/autoload/mag.break_lines.lua
1
11871
function lang_switch_keys(lang) local in_lang = {} local langs = { [1] = {lang_key = "tr", lang_name = "Türkçe", script_name = "Satır Böl", sub_menu = "Satır/Böl"}, [2] = {lang_key = "en", lang_name = "English", script_name = "Break Lines", sub_menu = "Lines/Break"} } local lang_list = {} local script_name_list = {} local sub_menu_list = {} for i = 1, #langs do lang_list[langs[i].lang_key] = langs[i].lang_name script_name_list[langs[i].lang_key] = langs[i].script_name sub_menu_list[langs[i].lang_key] = langs[i].sub_menu end if lang == langs[1].lang_key then in_lang["module_incompatible"] = "Mag modülünün kurulu sürümü bu lua dosyası ile uyumsuz!\n\nModül dosyasının en az \"%s\" sürümü veya daha üstü gerekiyor.\n\n\nŞimdi indirme sayfasına gitmek ister misiniz?" in_lang["module_not_found"] = "Mag modülü bulunamadı!\n\nBu lua dosyasını kullanmak için Mag modülünü indirip Aegisub programı kapalıyken\n\"Aegisub/automation/include/\" dizinine taşımanız gerekiyor.\n\n\nŞimdi indirme sayfasına gitmek ister misiniz?" in_lang["module_yes"] = "Git" in_lang["module_no"] = "Daha Sonra" in_lang["s_name"] = langs[1].script_name in_lang["s_desc"] = "Bölünmemiş ve bölünmesi gereken satırları böler." in_lang["buttonKey1"] = "Böl" in_lang["buttonKey2"] = "Kapat" in_lang["guiLabelKey1"] = "Karakter sınırı:" in_lang["guiLabelKey2"] = "Boşlukları ve noktalama işaretlerini yoksay" in_lang["guiLabelKey3"] = "Yukarıda kalacak kelimeler:" in_lang["guiLabelKey4"] = "Aşağıda kalacak kelimeler:" in_lang["topWordsDefault"] = "de,da,ki,ile,ya,kadar,mı,mi,mu,mü,bile,için,gibi" in_lang["bottomWordsDefault"] = "ama,lakin,fakat,ve,hem,anca,oysa,oysaki,ha,yoksa,en,her" in_lang["key1"] = "[Toplam bölünen satır: {%s}]\nBir konuşma çizgisi: {%s}\nİki konuşma çizgisi: {%s}\nKonuşma çizgisiz: {%s}" elseif lang == langs[2].lang_key then in_lang["module_incompatible"] = "The installed version of the Mag module is incompatible with this lua file!\n\nAt least \"%s\" version or higher of the module file is required.\n\n\nWould you like to go to the download page now?" in_lang["module_not_found"] = "The module named Mag could not be found!\n\nTo use this file, you need to download the module named mag\nand move it to \"Aegisub/automation/include/\" directory when Aegisub is off.\n\n\nDo you want to go to download page now?" in_lang["module_yes"] = "Go" in_lang["module_no"] = "Later" in_lang["s_name"] = langs[2].script_name in_lang["s_desc"] = "Breaks the lines that are not breaked and must be breaked." in_lang["buttonKey1"] = "Break" in_lang["buttonKey2"] = "Close" in_lang["buttonKey3"] = "Close" in_lang["guiLabelKey1"] = "Character limit:" in_lang["guiLabelKey2"] = "Ignore spaces and punctuations" in_lang["guiLabelKey3"] = "Top words:" in_lang["guiLabelKey4"] = "Bottom words:" in_lang["topWordsDefault"] = "" in_lang["bottomWordsDefault"] = "on,in,at,about,am,is,are,was,were,and,but,or,still,so,as,like,otherwise,both,either,neither,also,after,before,while,since,once,when,by,such,for,can,must,have,had,should,will,to" in_lang["key1"] = "[Total breaking {%s:[line][lines]: #}]\nOne speech {%s:[line][lines]: #}\nTwo speech {%s:[line][lines]: #}\nNon-speech {%s:[line][lines]: #}" end return in_lang, lang_list, script_name_list, sub_menu_list end c_lang_switch = "en" c_lang, c_lang_list, c_script_name_list, c_sub_name_list = lang_switch_keys(c_lang_switch) script_name = c_lang.s_name script_description = c_lang.s_desc script_author = "Magnum357" script_version = "1.3.1" script_mag_version = "1.1.4.8" script_file_name = "mag.break_lines" script_file_ext = ".lua" include_unicode = true mag_import, mag = pcall(require, "mag") if mag_import then mag.lang = c_lang_switch c_lock_gui = false c_buttons1 = {c_lang.buttonKey1, c_lang.buttonKey2} c = {} c.apply_lines = mag.window.lang.message("select") c.comment_mode = true c.empty_mode = true c.max_char = 40 c.space_and_punc = false c.top_words = "" c.bottom_words = "" gui = { main1 = { {class = "label", x = 0, y = 0, width = 1, height = 1, label = c_lang.guiLabelKey1}, max_char = {class = "intedit", name = "max_char", min = 30, max = 60, x = 1, y = 0, width = 1, height = 1}, {class = "label", x = 0, y = 1, width = 1, height = 1, label = c_lang.guiLabelKey3}, top_words = {class = "edit", name = "top_words", x = 1, y = 1, width = 1, height = 1}, {class = "label", x = 0, y = 2, width = 1, height = 1, label = c_lang.guiLabelKey4}, bottom_words = {class = "edit", name = "bottom_words", x = 1, y = 2, width = 1, height = 1}, {class = "label", x = 0, y = 3, width = 1, height = 1, label = mag.window.lang.message("apply")}, apply_lines = {class = "dropdown", name = "apply_lines", x = 1, y = 3, width = 1, height = 1}, comment_mode = {class = "checkbox", name = "comment_mode", x = 1, y = 4, width = 1, height = 1, label = mag.window.lang.message("comment_mode")}, empty_mode = {class = "checkbox", name = "empty_mode", x = 1, y = 5, width = 1, height = 1, label = mag.window.lang.message("empty_mode")}, space_and_punc = {class = "checkbox", name = "space_and_punc", x = 1, y = 6, width = 1, height = 1, label = c_lang.guiLabelKey2}, }, } end function break_line(subs,sel) local line, index local counter = {line_type1 = 0, line_type2 = 0, line_type3 = 0} local pcs = false local lines_index = mag.line.index(subs, sel, c.apply_lines, c.comment_mode, c.empty_mode) local top_words = mag.array.create(c.top_words) local bottom_words = mag.array.create(c.bottom_words) for i = 1, #lines_index do mag.window.progress(i, #lines_index) local pcs2 = false index = lines_index[i] line = subs[index] local strip_line = mag.strip.bracket(line.text) if not mag.match(strip_line, "\\N") then local word = mag.string.words(line.text) if mag.match(strip_line, "%-%s") or mag.match(strip_line, "%s%-") then local speech_count = mag.string.count(strip_dash(strip_line), "%-") if speech_count == 1 or speech_count == 2 then if speech_count == 1 then counter["line_type1"] = counter["line_type1"] + 1 elseif speech_count == 2 then counter["line_type2"] = counter["line_type2"] + 1 end for w = 1, #word do if w > 1 and mag.match(strip_dash(word[w]), "%-") then word[w] = "\\N"..word[w] if not pcs then pcs = true end pcs2 = true end if word[w] ~= nil and mag.match(strip_dash(word[w]), "%-") then word[w] = mag.trim.left(word[w]) end word[w] = word[w] end line.text = mag.array.concat(word) end end if not pcs2 then local text_len = len(line.text) if text_len >= c.max_char then counter["line_type3"] = counter["line_type3"] + 1 if not pcs then pcs = true end local half_len = text_len / 2 local diff = {} for w = 1, #word do local ptext = "" local ntext = "" for k = 1, #word do if k <= w then ptext = ptext..word[k] else ntext = ntext..word[k] end end local difff = {} difff.val = mag.convert.positive(len(ptext) - len(ntext)) difff.i = w mag.array.insert(diff, difff) end local sort_diff = {} for key in pairs(diff) do mag.array.insert(sort_diff, diff[key].val) end mag.sort.basic(sort_diff) local break_point for key in pairs(diff) do if diff[key].val == sort_diff[1] then break_point = diff[key].i break end end local break_prev = "" local break_next = "" -- Not break speech line if mag.strip.space(word[break_point]) == "-" then break_point = break_point - 1 end if mag.array.search(top_words, mag.gsub(word[break_point+1], "[%s"..mag.pattern.punc.."]+", "")) == true then break_point = break_point + 1 elseif mag.array.search(bottom_words, mag.gsub(word[break_point], "[%s"..mag.pattern.punc.."]+", "")) == true then break_point = break_point - 1 end for m = 1, #word do local word_part = word[m] if m <= break_point then break_prev = break_prev..word_part else break_next = break_next..word_part end end break_next = mag.trim.left(break_next) line.text = mag.format("%s\\N%s", break_prev, break_next) end end end if pcs then subs[index] = line end end if pcs then mag.show.log(mag.string.format(c_lang.key1, counter["line_type1"] + counter["line_type2"] + counter["line_type3"], counter["line_type1"], counter["line_type2"], counter["line_type3"] )) end mag.show.no_op(pcs) end function len(s) s = mag.strip.bracket(s) s = strip_special(s) if c.space_and_punc then s = mag.strip.space(s) s = mag.strip.punc(s) end return mag.convert.len(s) end function strip_special(str) str = mag.gsub(str, "\\[nN]", "") str = mag.gsub(str, "\\h", " ") return str end function strip_dash(s) return s:gsub("["..mag.pattern.letter..mag.pattern.number.."]%-", ""):gsub("%-["..mag.pattern.letter..mag.pattern.number.."]", "") end function add_macro1(subs,sel) local apply_items = mag.list.full_apply(subs, sel, "comment") c.apply_lines = mag.array.search_apply(apply_items, c.apply_lines) gui.main1.apply_lines.items = apply_items if c.top_words == "" then c.top_words = c_lang.topWordsDefault end if c.bottom_words == "" then c.bottom_words = c_lang.bottomWordsDefault end local ok, config repeat mag.config.put(gui.main1) ok, config = mag.window.dialog(gui.main1, c_buttons1) mag.config.take(config) until ok == mag.convert.ascii(c_buttons1[1]) and c.apply_lines ~= mag.window.lang.message("select") or ok == mag.convert.ascii(c_buttons1[2]) if ok == mag.convert.ascii(c_buttons1[1]) then break_line(subs, sel) end end function check_macro1(subs,sel) if c_lock_gui then mag.show.log(1, mag.window.lang.message("restart_aegisub")) else mag.config.get(c) local fe, fee = pcall(add_macro1, subs, sel) mag.window.funce(fe, fee) mag.window.undo_point() mag.config.set(c) end end function mag_redirect_gui() local mag_module_link = "https://github.com/magnum357i/Magnum-s-Aegisub-Scripts" local k = aegisub.dialog.display({{class = "label", label = mag_gui_message}}, {c_lang.module_yes, c_lang.module_no}) if k == c_lang.module_yes then os.execute("start "..mag_module_link) end end if mag_import then if mag_module_version:gsub("%.", "") < script_mag_version:gsub("%.", "") then mag_gui_message = string.format(c_lang.module_incompatible, script_mag_version) aegisub.register_macro(script_name, script_desription, mag_redirect_gui) else mag.window.register(c_sub_name_list[c_lang_switch].."/"..mag.window.lang.message("gui_tabname"), check_macro1) mag.window.lang.register(c_sub_name_list[c_lang_switch]) end else mag_gui_message = c_lang.module_not_found aegisub.register_macro(script_name, script_desription, mag_redirect_gui) end
mit
Toukibi/ToSAddon
Do-It-Yourself/LuaOnly/alter_DeveloperConsole/developerconsole.lua
1
7863
function DEVELOPERCONSOLE_ON_INIT(addon, frame) local acutil = require("acutil"); acutil.slashCommand("/dev", DEVELOPERCONSOLE_TOGGLE_FRAME); acutil.slashCommand("/console", DEVELOPERCONSOLE_TOGGLE_FRAME); acutil.slashCommand("/devconsole", DEVELOPERCONSOLE_TOGGLE_FRAME); acutil.slashCommand("/developerconsole", DEVELOPERCONSOLE_TOGGLE_FRAME); acutil.setupHook(DEVELOPERCONSOLE_PRINT_TEXT, "print"); CLEAR_CONSOLE(); end function DEVELOPERCONSOLE_TOGGLE_FRAME() ui.ToggleFrame("developerconsole"); end function DEVELOPERCONSOLE_OPEN() local frame = ui.GetFrame("developerconsole"); local textViewLog = frame:GetChild("textview_log"); textViewLog:ShowWindow(1); local devconsole = ui.GetFrame("developerconsole"); devconsole:ShowTitleBar(0); --devconsole:ShowTitleBarFrame(1); devconsole:ShowWindow(0); devconsole:SetSkinName("chat_window"); devconsole:ShowWindow(1); --devconsole:Resize(800, 500); local input = devconsole:GetChild("input"); if input ~= nil then input:Move(0, 0); input:SetOffset(10, 450); --input:ShowWindow(1); --input:Resize(675, 40); --input:SetGravity(ui.LEFT, ui.CENTER); end local executeButton = devconsole:GetChild("execute"); if executeButton ~= nil then --executeButton:Resize(100, 40); executeButton:SetOffset(690, 450); executeButton:SetText("Execute"); end local debugUIButton = devconsole:GetChild("debugUI"); if debugUIButton ~= nil then --debugUIButton:Resize(100, 40); debugUIButton:SetOffset(690, 405); debugUIButton:SetText("Debug UI"); end local clearButton = devconsole:GetChild("clearConsole"); if clearButton ~= nil then clearButton:Resize(100, 40); clearButton:SetOffset(690, 360); clearButton:SetText("Clear"); end local textlog = devconsole:GetChild("textview_log"); if textlog ~= nil then --textlog:Resize(675, 435); textlog:SetOffset(10, 10); end devconsole:Invalidate(); --ui.SysMsg("input: " .. input:GetX() .. " " .. input:GetY() .. " " .. input:GetWidth() .. " " .. input:GetHeight()); --ui.SysMsg("execute: " .. executeButton:GetX() .. " " .. executeButton:GetY() .. " " .. executeButton:GetWidth() .. " " .. executeButton:GetHeight()); --ui.SysMsg("debugUI: " .. debugUIButton:GetX() .. " " .. debugUIButton:GetY() .. " " .. debugUIButton:GetWidth() .. " " .. debugUIButton:GetHeight()); --ui.SysMsg("textlog: " .. textlog:GetX() .. " " .. textlog:GetY() .. " " .. textlog:GetWidth() .. " " .. textlog:GetHeight()); end function DEVELOPERCONSOLE_CLOSE() end function TOGGLE_UI_DEBUG() debug.ToggleUIDebug(); end function CLEAR_CONSOLE() local frame = ui.GetFrame("developerconsole"); if frame ~= nil then local textlog = frame:GetChild("textview_log"); if textlog ~= nil then tolua.cast(textlog, "ui::CTextView"); textlog:Clear(); textlog:AddText("Developer Console", "white_16_ol"); textlog:AddText("Enter command and press execute!", "white_16_ol"); end end end function DEVELOPERCONSOLE_PRINT_TEXT(text) if text == nil or text == "" then return; end local frame = ui.GetFrame("developerconsole"); local textlog = frame:GetChild("textview_log"); if textlog ~= nil then tolua.cast(textlog, "ui::CTextView"); textlog:AddText(text, "white_16_ol"); end end local function order_pairs(tab) local sorted = {}; for key in pairs(tab) do table.insert(sorted,key); end table.sort(sorted); local i = 0; return function() i = i + 1 if i > #sorted then return nil,nil else local key=sorted[i] return key,tab[key] end end end function DEVELOPERCONSOLE_PRINT_VALUE(frame, objName, objValue, ParentName, indentStr, ViewValue) frame = frame or ui.GetFrame("developerconsole"); local textlog = frame:GetChild("textview_log"); indentStr = indentStr or ""; ParentName = ParentName or ""; if ViewValue == nil then ViewValue = false end local commandText = ""; local typeStr = type(objValue); if typeStr == "userdata" or typeStr == "table" then if typeStr == "userdata" then objValue = getmetatable(objValue) end for pName, pValue in order_pairs(objValue) do local strLeft = "{#666666}" .. indentStr .. "└{/}{#444466}" .. tostring(pName) .. "{/}"; local pType = type(pValue); if pName == "tolua_ubox" then textlog:AddText("{#666666}" .. indentStr .. "└{/}{#666644}[" .. tostring(pName) .. "]{/}", "white_16_ol"); elseif pType == "function" then local funcStr = string.format("{#888888}(%s){/}", tostring(pValue)); local valueStr = ""; if ViewValue and string.sub(pName, 1, 2) ~= "__" and objName ~= ".set" then valueStr = "{#444444}={/} "; local funcSrcStr = "" if objName == ".get" then funcSrcStr = string.format("return tostring(%s.%s)", ParentName, pName); else funcSrcStr = string.format("return tostring(%s:%s())", ParentName, pName); end -- textlog:AddText(tostring(funcSrcStr), "white_16_ol"); -- local funcResult = assert(load(funcSrcStr))(); local status, objResult = pcall(load(funcSrcStr)) if not status then --textlog:AddText(tostring(objResult), "white_16_ol"); else valueStr = valueStr .. "{#336666}" .. objResult .. "{/} "; end end if string.sub(pName, 1, 2) ~= "__" and objName ~= ".set" then textlog:AddText(string.format("%s {#888888}%s{/}%s", strLeft, valueStr, funcStr), "white_16_ol"); end elseif pType == "userdata" or pType == "table" then local NextParentName = ParentName; if objName ~= ".get" then else NextParentName = NextParentName .. objName end textlog:AddText(strLeft .. " {#444444}={/} {#005500}" .. pType .. "{/}", "white_16_ol"); DEVELOPERCONSOLE_PRINT_VALUE(frame, tostring(pName), pValue, NextParentName, indentStr .. "│ ", ViewValue); else textlog:AddText(strLeft .. " {#444444}={/} " .. tostring(pValue), "white_16_ol") end end else local f = assert(print(tostring(objValue))); local status, error = pcall(f); if not status then textlog:AddText(tostring(error), "white_16_ol"); end end end function DEVELOPERCONSOLE_ENTER_KEY(frame, control, argStr, argNum) local textlog = frame:GetChild("textview_log"); if textlog ~= nil then tolua.cast(textlog, "ui::CTextView"); local editbox = frame:GetChild("input"); if editbox ~= nil then tolua.cast(editbox, "ui::CEditControl"); local commandText = editbox:GetText(); if commandText ~= nil and commandText ~= "" then textlog:AddText(" ", "white_16_ol"); local s = "[Execute] " .. commandText; textlog:AddText("{#333333}" .. s .. "{/}", "white_16_ol"); if string.sub(commandText, 1, 2) == "??" then local ViewValue = false local objName = string.sub(commandText,3) if string.sub(commandText, 1, 3) == "???" then ViewValue = true; objName = string.sub(commandText,4) end local objValue = assert(load(string.format("return %s", objName)))(); textlog:AddText("{#444444}type of {#005500}" .. objName .. "{/} is {#005500}" .. type(objValue) .. "{/}{/}", "white_16_ol"); DEVELOPERCONSOLE_PRINT_VALUE(frame, objName, objValue, objName, nil, ViewValue); elseif string.sub(commandText, 1, 1) == "?" then local objName = string.sub(commandText,2) local objValue = assert(load(string.format("return %s", objName)))(); local strLeft = "{#444466}" .. tostring(objName) .. "{/} {#444444}={/} "; textlog:AddText(strLeft .. tostring(objValue), "white_16_ol") else local f = assert(load(commandText)); local status, error = pcall(f); if not status then textlog:AddText(tostring(error), "white_16_ol"); end end end end end end
gpl-3.0
harryzeng/skynet
lualib/mongo.lua
58
11027
local bson = require "bson" local socket = require "socket" local socketchannel = require "socketchannel" local skynet = require "skynet" local driver = require "mongo.driver" local md5 = require "md5" local rawget = rawget local assert = assert local bson_encode = bson.encode local bson_encode_order = bson.encode_order local bson_decode = bson.decode local empty_bson = bson_encode {} local mongo = {} mongo.null = assert(bson.null) mongo.maxkey = assert(bson.maxkey) mongo.minkey = assert(bson.minkey) mongo.type = assert(bson.type) local mongo_cursor = {} local cursor_meta = { __index = mongo_cursor, } local mongo_client = {} local client_meta = { __index = function(self, key) return rawget(mongo_client, key) or self:getDB(key) end, __tostring = function (self) local port_string if self.port then port_string = ":" .. tostring(self.port) else port_string = "" end return "[mongo client : " .. self.host .. port_string .."]" end, -- DO NOT need disconnect, because channel will shutdown during gc } local mongo_db = {} local db_meta = { __index = function (self, key) return rawget(mongo_db, key) or self:getCollection(key) end, __tostring = function (self) return "[mongo db : " .. self.name .. "]" end } local mongo_collection = {} local collection_meta = { __index = function(self, key) return rawget(mongo_collection, key) or self:getCollection(key) end , __tostring = function (self) return "[mongo collection : " .. self.full_name .. "]" end } local function dispatch_reply(so) local len_reply = so:read(4) local reply = so:read(driver.length(len_reply)) local result = { result = {} } local succ, reply_id, document, cursor_id, startfrom = driver.reply(reply, result.result) result.document = document result.cursor_id = cursor_id result.startfrom = startfrom result.data = reply return reply_id, succ, result end local function __parse_addr(addr) local host, port = string.match(addr, "([^:]+):(.+)") return host, tonumber(port) end local function mongo_auth(mongoc) local user = rawget(mongoc, "username") local pass = rawget(mongoc, "password") return function() if user ~= nil and pass ~= nil then assert(mongoc:auth(user, pass)) end local rs_data = mongoc:runCommand("ismaster") if rs_data.ok == 1 then if rs_data.hosts then local backup = {} for _, v in ipairs(rs_data.hosts) do local host, port = __parse_addr(v) table.insert(backup, {host = host, port = port}) end mongoc.__sock:changebackup(backup) end if rs_data.ismaster then return else local host, port = __parse_addr(rs_data.primary) mongoc.host = host mongoc.port = port mongoc.__sock:changehost(host, port) end end end end function mongo.client( conf ) local first = conf local backup = nil if conf.rs then first = conf.rs[1] backup = conf.rs end local obj = { host = first.host, port = first.port or 27017, username = first.username, password = first.password, } obj.__id = 0 obj.__sock = socketchannel.channel { host = obj.host, port = obj.port, response = dispatch_reply, auth = mongo_auth(obj), backup = backup, nodelay = true, } setmetatable(obj, client_meta) obj.__sock:connect(true) -- try connect only once return obj end function mongo_client:getDB(dbname) local db = { connection = self, name = dbname, full_name = dbname, database = false, __cmd = dbname .. "." .. "$cmd", } db.database = db return setmetatable(db, db_meta) end function mongo_client:disconnect() if self.__sock then local so = self.__sock self.__sock = false so:close() end end function mongo_client:genId() local id = self.__id + 1 self.__id = id return id end function mongo_client:runCommand(...) if not self.admin then self.admin = self:getDB "admin" end return self.admin:runCommand(...) end function mongo_client:auth(user,password) local password = md5.sumhexa(string.format("%s:mongo:%s",user,password)) local result= self:runCommand "getnonce" if result.ok ~=1 then return false end local key = md5.sumhexa(string.format("%s%s%s",result.nonce,user,password)) local result= self:runCommand ("authenticate",1,"user",user,"nonce",result.nonce,"key",key) return result.ok == 1 end function mongo_client:logout() local result = self:runCommand "logout" return result.ok == 1 end function mongo_db:runCommand(cmd,cmd_v,...) local conn = self.connection local request_id = conn:genId() local sock = conn.__sock local bson_cmd if not cmd_v then bson_cmd = bson_encode_order(cmd,1) else bson_cmd = bson_encode_order(cmd,cmd_v,...) end local pack = driver.query(request_id, 0, self.__cmd, 0, 1, bson_cmd) -- we must hold req (req.data), because req.document is a lightuserdata, it's a pointer to the string (req.data) local req = sock:request(pack, request_id) local doc = req.document return bson_decode(doc) end function mongo_db:getCollection(collection) local col = { connection = self.connection, name = collection, full_name = self.full_name .. "." .. collection, database = self.database, } self[collection] = setmetatable(col, collection_meta) return col end mongo_collection.getCollection = mongo_db.getCollection function mongo_collection:insert(doc) if doc._id == nil then doc._id = bson.objectid() end local sock = self.connection.__sock local pack = driver.insert(0, self.full_name, bson_encode(doc)) -- flags support 1: ContinueOnError sock:request(pack) end function mongo_collection:safe_insert(doc) return self.database:runCommand("insert", self.name, "documents", {bson_encode(doc)}) end function mongo_collection:batch_insert(docs) for i=1,#docs do if docs[i]._id == nil then docs[i]._id = bson.objectid() end docs[i] = bson_encode(docs[i]) end local sock = self.connection.__sock local pack = driver.insert(0, self.full_name, docs) sock:request(pack) end function mongo_collection:update(selector,update,upsert,multi) local flags = (upsert and 1 or 0) + (multi and 2 or 0) local sock = self.connection.__sock local pack = driver.update(self.full_name, flags, bson_encode(selector), bson_encode(update)) sock:request(pack) end function mongo_collection:delete(selector, single) local sock = self.connection.__sock local pack = driver.delete(self.full_name, single, bson_encode(selector)) sock:request(pack) end function mongo_collection:findOne(query, selector) local conn = self.connection local request_id = conn:genId() local sock = conn.__sock local pack = driver.query(request_id, 0, self.full_name, 0, 1, query and bson_encode(query) or empty_bson, selector and bson_encode(selector)) -- we must hold req (req.data), because req.document is a lightuserdata, it's a pointer to the string (req.data) local req = sock:request(pack, request_id) local doc = req.document return bson_decode(doc) end function mongo_collection:find(query, selector) return setmetatable( { __collection = self, __query = query and bson_encode(query) or empty_bson, __selector = selector and bson_encode(selector), __ptr = nil, __data = nil, __cursor = nil, __document = {}, __flags = 0, __skip = 0, __sortquery = nil, __limit = 0, } , cursor_meta) end function mongo_cursor:sort(key_list) self.__sortquery = bson_encode {['$query'] = self.__query, ['$orderby'] = key_list} return self end function mongo_cursor:skip(amount) self.__skip = amount return self end function mongo_cursor:limit(amount) self.__limit = amount return self end function mongo_cursor:count(with_limit_and_skip) local cmd = { 'count', self.__collection.name, 'query', self.__query, } if with_limit_and_skip then local len = #cmd cmd[len+1] = 'limit' cmd[len+2] = self.__limit cmd[len+3] = 'skip' cmd[len+4] = self.__skip end local ret = self.__collection.database:runCommand(table.unpack(cmd)) assert(ret and ret.ok == 1) return ret.n end -- collection:createIndex({username = 1}, {unique = true}) function mongo_collection:createIndex(keys, option) local name = option.name option.name = nil if not name then for k, v in pairs(keys) do name = (name == nil) and k or (name .. "_" .. k) name = name .. "_" .. v end end local doc = {}; doc.name = name doc.key = keys for k, v in pairs(option) do doc[k] = v end return self.database:runCommand("createIndexes", self.name, "indexes", {doc}) end mongo_collection.ensureIndex = mongo_collection.createIndex; function mongo_collection:drop() return self.database:runCommand("drop", self.name) end -- collection:dropIndex("age_1") -- collection:dropIndex("*") function mongo_collection:dropIndex(indexName) return self.database:runCommand("dropIndexes", self.name, "index", indexName) end -- collection:findAndModify({query = {name = "userid"}, update = {["$inc"] = {nextid = 1}}, }) -- keys, value type -- query, table -- sort, table -- remove, bool -- update, table -- new, bool -- fields, bool -- upsert, boolean function mongo_collection:findAndModify(doc) assert(doc.query) assert(doc.update or doc.remove) local cmd = {"findAndModify", self.name}; for k, v in pairs(doc) do table.insert(cmd, k) table.insert(cmd, v) end return self.database:runCommand(table.unpack(cmd)) end function mongo_cursor:hasNext() if self.__ptr == nil then if self.__document == nil then return false end local conn = self.__collection.connection local request_id = conn:genId() local sock = conn.__sock local pack if self.__data == nil then local query = self.__sortquery or self.__query pack = driver.query(request_id, self.__flags, self.__collection.full_name, self.__skip, -self.__limit, query, self.__selector) else if self.__cursor then pack = driver.more(request_id, self.__collection.full_name, -self.__limit, self.__cursor) else -- no more self.__document = nil self.__data = nil return false end end local ok, result = pcall(sock.request,sock,pack, request_id) local doc = result.document local cursor = result.cursor_id if ok then if doc then self.__document = result.result self.__data = result.data self.__ptr = 1 self.__cursor = cursor return true else self.__document = nil self.__data = nil self.__cursor = nil return false end else self.__document = nil self.__data = nil self.__cursor = nil if doc then local err = bson_decode(doc) error(err["$err"]) else error("Reply from mongod error") end end end return true end function mongo_cursor:next() if self.__ptr == nil then error "Call hasNext first" end local r = bson_decode(self.__document[self.__ptr]) self.__ptr = self.__ptr + 1 if self.__ptr > #self.__document then self.__ptr = nil end return r end function mongo_cursor:close() -- todo: warning hasNext after close if self.__cursor then local sock = self.__collection.connection.__sock local pack = driver.kill(self.__cursor) sock:request(pack) end end return mongo
mit
FizzerWL/ExampleMods
RandomStartingCitiesMod/Utilities.lua
3
1934
function NewIdentity() local data = Mod.PublicGameData; local ret = data.Identity or 1; data.Identity = ret + 1; Mod.PublicGameData = data; return ret; end function Dump(obj) if obj.proxyType ~= nil then DumpProxy(obj); elseif type(obj) == 'table' then DumpTable(obj); else print('Dump ' .. type(obj)); end end function DumpTable(tbl) for k,v in pairs(tbl) do print('k = ' .. tostring(k) .. ' (' .. type(k) .. ') ' .. ' v = ' .. tostring(v) .. ' (' .. type(v) .. ')'); end end function DumpProxy(obj) print('type=' .. obj.proxyType .. ' readOnly=' .. tostring(obj.readonly) .. ' readableKeys=' .. table.concat(obj.readableKeys, ',') .. ' writableKeys=' .. table.concat(obj.writableKeys, ',')); end function split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, 1) while s do if s ~= 1 or cap ~= "" then table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) table.insert(t, cap) end return t end function map(array, func) local new_array = {} local i = 1; for _,v in pairs(array) do new_array[i] = func(v); i = i + 1; end return new_array end function filter(array, func) local new_array = {} local i = 1; for _,v in pairs(array) do if (func(v)) then new_array[i] = v; i = i + 1; end end return new_array end function first(array, func) for _,v in pairs(array) do if (func(v)) then return v; end end return nil; end function randomFromArray(array) local len = #array; local i = math.random(len); return array[i]; end function startsWith(str, sub) return string.sub(str, 1, string.len(sub)) == sub; end function shuffle(tbl) for i = #tbl, 2, -1 do local j = math.random(i) tbl[i], tbl[j] = tbl[j], tbl[i] end end
mit
FizzerWL/ExampleMods
HybridDistributionMod/Utilities.lua
3
1934
function NewIdentity() local data = Mod.PublicGameData; local ret = data.Identity or 1; data.Identity = ret + 1; Mod.PublicGameData = data; return ret; end function Dump(obj) if obj.proxyType ~= nil then DumpProxy(obj); elseif type(obj) == 'table' then DumpTable(obj); else print('Dump ' .. type(obj)); end end function DumpTable(tbl) for k,v in pairs(tbl) do print('k = ' .. tostring(k) .. ' (' .. type(k) .. ') ' .. ' v = ' .. tostring(v) .. ' (' .. type(v) .. ')'); end end function DumpProxy(obj) print('type=' .. obj.proxyType .. ' readOnly=' .. tostring(obj.readonly) .. ' readableKeys=' .. table.concat(obj.readableKeys, ',') .. ' writableKeys=' .. table.concat(obj.writableKeys, ',')); end function split(str, pat) local t = {} -- NOTE: use {n = 0} in Lua-5.0 local fpat = "(.-)" .. pat local last_end = 1 local s, e, cap = str:find(fpat, 1) while s do if s ~= 1 or cap ~= "" then table.insert(t,cap) end last_end = e+1 s, e, cap = str:find(fpat, last_end) end if last_end <= #str then cap = str:sub(last_end) table.insert(t, cap) end return t end function map(array, func) local new_array = {} local i = 1; for _,v in pairs(array) do new_array[i] = func(v); i = i + 1; end return new_array end function filter(array, func) local new_array = {} local i = 1; for _,v in pairs(array) do if (func(v)) then new_array[i] = v; i = i + 1; end end return new_array end function first(array, func) for _,v in pairs(array) do if (func(v)) then return v; end end return nil; end function randomFromArray(array) local len = #array; local i = math.random(len); return array[i]; end function startsWith(str, sub) return string.sub(str, 1, string.len(sub)) == sub; end function shuffle(tbl) for i = #tbl, 2, -1 do local j = math.random(i) tbl[i], tbl[j] = tbl[j], tbl[i] end end
mit
HannesTuhkala/saitohud
src/SaitoHUD/lua/saitohud/vgui/DListView_CheckboxLine.lua
3
1940
-- SaitoHUD -- Copyright (c) 2009-2010 sk89q <http://www.sk89q.com> -- Copyright (c) 2010 BoJaN -- -- This program is free software: you can redistribute it and/or modify -- it under the terms of the GNU General Public License as published by -- the Free Software Foundation, either version 2 of the License, or -- (at your option) any later version. -- -- This program is distributed in the hope that it will be useful, -- but WITHOUT ANY WARRANTY; without even the implied warranty of -- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -- GNU General Public License for more details. -- -- You should have received a copy of the GNU General Public License -- along with this program. If not, see <http://www.gnu.org/licenses/>. -- -- $Id$ local PANEL = {} function PANEL:Init() self.BaseClass.Init(self) self.Check = vgui.Create("DCheckBox", self) self.Check:SetSize(14, 14) self.Check.OnChange = function() self:SetColumnText(1, self.Check:GetChecked() and "1" or "") self:OnChange(self.Check:GetChecked()) end end function PANEL:OnChange(checked) end function PANEL:SetChecked(checked) self.Check:SetValue(checked) end function PANEL:GetChecked() return self.Check:GetChecked() end function PANEL:DataLayout(listView) self:ApplySchemeSettings() local height = self:GetTall() local x = 0 for k, column in pairs(self.Columns) do if k == 1 then column:SetVisible(false) end local w = listView:ColumnWidth(k) column:SetPos(x, 0) column:SetSize(w, height) if k == 1 then self.Check:SetPos(x + (w - self.Check:GetWide()) / 2, (height - self.Check:GetTall()) / 2) end x = x + w end end vgui.Register("DListView_CheckboxLine", PANEL, "DListView_Line")
gpl-2.0
ElectricPrism/stargus
scripts/zerg/construction.lua
1
5259
-- FIXME: need support for animations while building DefineConstruction("construction-zerg", { Files = { File = "zerg/units/building morph.png", Size = {160, 192}}, ShadowFiles = { File = "zerg/units/building morph shadow.png", Size = {160, 192}}, Constructions = { {Percent = 0, File = "construction", Frame = 0}, {Percent = 1, File = "construction", Frame = 1}, {Percent = 2, File = "construction", Frame = 7},{Percent = 3, File = "construction", Frame = 6},{Percent = 4, File = "construction", Frame = 7},{Percent = 5, File = "construction", Frame = 8},{Percent = 6, File = "construction", Frame = 9},{Percent = 7, File = "construction", Frame = 8},{Percent = 8, File = "construction", Frame = 7},{Percent = 9, File = "construction", Frame = 8},{Percent = 10, File = "construction", Frame = 9},{Percent = 11, File = "construction", Frame = 8},{Percent = 12, File = "construction", Frame = 7},{Percent = 13, File = "construction", Frame = 8},{Percent = 14, File = "construction", Frame = 9},{Percent = 15, File = "construction", Frame = 8},{Percent = 16, File = "construction", Frame = 7},{Percent = 17, File = "construction", Frame = 8},{Percent = 18, File = "construction", Frame = 9},{Percent = 19, File = "construction", Frame = 8},{Percent = 20, File = "construction", Frame = 7},{Percent = 21, File = "construction", Frame = 8},{Percent = 22, File = "construction", Frame = 9},{Percent = 23, File = "construction", Frame = 8},{Percent = 24, File = "construction", Frame = 7},{Percent = 25, File = "construction", Frame = 8},{Percent = 26, File = "construction", Frame = 9},{Percent = 27, File = "construction", Frame = 8},{Percent = 28, File = "construction", Frame = 7},{Percent = 29, File = "construction", Frame = 8},{Percent = 30, File = "construction", Frame = 9},{Percent = 31, File = "construction", Frame = 8},{Percent = 32, File = "construction", Frame = 7},{Percent = 33, File = "construction", Frame = 8},{Percent = 34, File = "construction", Frame = 9},{Percent = 35, File = "construction", Frame = 8},{Percent = 36, File = "construction", Frame = 7},{Percent = 37, File = "construction", Frame = 8},{Percent = 38, File = "construction", Frame = 9},{Percent = 39, File = "construction", Frame = 8},{Percent = 40, File = "construction", Frame = 7},{Percent = 41, File = "construction", Frame = 8},{Percent = 42, File = "construction", Frame = 9},{Percent = 43, File = "construction", Frame = 8},{Percent = 44, File = "construction", Frame = 7},{Percent = 45, File = "construction", Frame = 8},{Percent = 46, File = "construction", Frame = 9},{Percent = 47, File = "construction", Frame = 8},{Percent = 48, File = "construction", Frame = 7},{Percent = 49, File = "construction", Frame = 8},{Percent = 50, File = "construction", Frame = 9},{Percent = 51, File = "construction", Frame = 8},{Percent = 52, File = "construction", Frame = 7},{Percent = 53, File = "construction", Frame = 8},{Percent = 54, File = "construction", Frame = 9},{Percent = 55, File = "construction", Frame = 8},{Percent = 56, File = "construction", Frame = 7},{Percent = 57, File = "construction", Frame = 8},{Percent = 58, File = "construction", Frame = 9},{Percent = 59, File = "construction", Frame = 8},{Percent = 60, File = "construction", Frame = 7},{Percent = 61, File = "construction", Frame = 8},{Percent = 62, File = "construction", Frame = 9},{Percent = 63, File = "construction", Frame = 8},{Percent = 64, File = "construction", Frame = 7},{Percent = 65, File = "construction", Frame = 8},{Percent = 66, File = "construction", Frame = 9},{Percent = 67, File = "construction", Frame = 8},{Percent = 68, File = "construction", Frame = 7},{Percent = 69, File = "construction", Frame = 8},{Percent = 70, File = "construction", Frame = 9},{Percent = 71, File = "construction", Frame = 8},{Percent = 72, File = "construction", Frame = 7},{Percent = 73, File = "construction", Frame = 8},{Percent = 74, File = "construction", Frame = 9},{Percent = 75, File = "construction", Frame = 8},{Percent = 76, File = "construction", Frame = 7},{Percent = 77, File = "construction", Frame = 8},{Percent = 78, File = "construction", Frame = 9},{Percent = 79, File = "construction", Frame = 8},{Percent = 80, File = "construction", Frame = 7},{Percent = 81, File = "construction", Frame = 8},{Percent = 82, File = "construction", Frame = 9},{Percent = 83, File = "construction", Frame = 8},{Percent = 84, File = "construction", Frame = 7},{Percent = 85, File = "construction", Frame = 8},{Percent = 86, File = "construction", Frame = 9},{Percent = 87, File = "construction", Frame = 8},{Percent = 88, File = "construction", Frame = 7},{Percent = 89, File = "construction", Frame = 8},{Percent = 90, File = "construction", Frame = 9},{Percent = 91, File = "construction", Frame = 8},{Percent = 92, File = "construction", Frame = 7},{Percent = 93, File = "construction", Frame = 8},{Percent = 94, File = "construction", Frame = 9},{Percent = 95, File = "construction", Frame = 8},{Percent = 96, File = "construction", Frame = 7},{Percent = 97, File = "construction", Frame = 8},{Percent = 98, File = "construction", Frame = 9},{Percent = 99, File = "construction", Frame = 8},{Percent = 100, File = "construction", Frame = 7}, } })
gpl-2.0
yangboz/petulant-octo-dubstep
HP_ID_Print_App/cocos2d-x-3.2/cocos/scripting/lua-bindings/auto/api/DisplayManager.lua
1
3623
-------------------------------- -- @module DisplayManager -- @extend Ref -------------------------------- -- @function [parent=#DisplayManager] getDisplayRenderNode -- @param self -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- @function [parent=#DisplayManager] getAnchorPointInPoints -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- @function [parent=#DisplayManager] getDisplayRenderNodeType -- @param self -- @return DisplayType#DisplayType ret (return value: ccs.DisplayType) -------------------------------- -- @function [parent=#DisplayManager] removeDisplay -- @param self -- @param #int int -------------------------------- -- @function [parent=#DisplayManager] setForceChangeDisplay -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#DisplayManager] init -- @param self -- @param #ccs.Bone bone -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#DisplayManager] getContentSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#DisplayManager] getBoundingBox -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- overload function: addDisplay(cc.Node, int) -- -- overload function: addDisplay(ccs.DisplayData, int) -- -- @function [parent=#DisplayManager] addDisplay -- @param self -- @param #ccs.DisplayData displaydata -- @param #int int -------------------------------- -- overload function: containPoint(float, float) -- -- overload function: containPoint(vec2_table) -- -- @function [parent=#DisplayManager] containPoint -- @param self -- @param #float float -- @param #float float -- @return bool#bool ret (retunr value: bool) -------------------------------- -- @function [parent=#DisplayManager] changeDisplayWithIndex -- @param self -- @param #int int -- @param #bool bool -------------------------------- -- @function [parent=#DisplayManager] changeDisplayWithName -- @param self -- @param #string str -- @param #bool bool -------------------------------- -- @function [parent=#DisplayManager] isForceChangeDisplay -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#DisplayManager] getCurrentDisplayIndex -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#DisplayManager] getAnchorPoint -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- @function [parent=#DisplayManager] getDecorativeDisplayList -- @param self -- @return array_table#array_table ret (return value: array_table) -------------------------------- -- @function [parent=#DisplayManager] isVisible -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#DisplayManager] setVisible -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#DisplayManager] create -- @param self -- @param #ccs.Bone bone -- @return DisplayManager#DisplayManager ret (return value: ccs.DisplayManager) -------------------------------- -- @function [parent=#DisplayManager] DisplayManager -- @param self return nil
mit
adminerror/00000000
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
gpl-2.0
kobakei/CCLocalNotification
cocos2d/external/lua/luajit/src/dynasm/dasm_mips.lua
74
28080
------------------------------------------------------------------------------ -- DynASM MIPS module. -- -- Copyright (C) 2005-2013 Mike Pall. All rights reserved. -- See dynasm.lua for full copyright notice. ------------------------------------------------------------------------------ -- Module information: local _info = { arch = "mips", description = "DynASM MIPS module", version = "1.3.0", vernum = 10300, release = "2012-01-23", author = "Mike Pall", license = "MIT", } -- Exported glue functions for the arch-specific module. local _M = { _info = _info } -- Cache library functions. local type, tonumber, pairs, ipairs = type, tonumber, pairs, ipairs local assert, setmetatable = assert, setmetatable local _s = string local sub, format, byte, char = _s.sub, _s.format, _s.byte, _s.char local match, gmatch = _s.match, _s.gmatch local concat, sort = table.concat, table.sort local bit = bit or require("bit") local band, shl, sar, tohex = bit.band, bit.lshift, bit.arshift, bit.tohex -- Inherited tables and callbacks. local g_opt, g_arch local wline, werror, wfatal, wwarn -- Action name list. -- CHECK: Keep this in sync with the C code! local action_names = { "STOP", "SECTION", "ESC", "REL_EXT", "ALIGN", "REL_LG", "LABEL_LG", "REL_PC", "LABEL_PC", "IMM", } -- Maximum number of section buffer positions for dasm_put(). -- CHECK: Keep this in sync with the C code! local maxsecpos = 25 -- Keep this low, to avoid excessively long C lines. -- Action name -> action number. local map_action = {} for n,name in ipairs(action_names) do map_action[name] = n-1 end -- Action list buffer. local actlist = {} -- Argument list for next dasm_put(). Start with offset 0 into action list. local actargs = { 0 } -- Current number of section buffer positions for dasm_put(). local secpos = 1 ------------------------------------------------------------------------------ -- Dump action names and numbers. local function dumpactions(out) out:write("DynASM encoding engine action codes:\n") for n,name in ipairs(action_names) do local num = map_action[name] out:write(format(" %-10s %02X %d\n", name, num, num)) end out:write("\n") end -- Write action list buffer as a huge static C array. local function writeactions(out, name) local nn = #actlist if nn == 0 then nn = 1; actlist[0] = map_action.STOP end out:write("static const unsigned int ", name, "[", nn, "] = {\n") for i = 1,nn-1 do assert(out:write("0x", tohex(actlist[i]), ",\n")) end assert(out:write("0x", tohex(actlist[nn]), "\n};\n\n")) end ------------------------------------------------------------------------------ -- Add word to action list. local function wputxw(n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[#actlist+1] = n end -- Add action to list with optional arg. Advance buffer pos, too. local function waction(action, val, a, num) local w = assert(map_action[action], "bad action name `"..action.."'") wputxw(0xff000000 + w * 0x10000 + (val or 0)) if a then actargs[#actargs+1] = a end if a or num then secpos = secpos + (num or 1) end end -- Flush action list (intervening C code or buffer pos overflow). local function wflush(term) if #actlist == actargs[1] then return end -- Nothing to flush. if not term then waction("STOP") end -- Terminate action list. wline(format("dasm_put(Dst, %s);", concat(actargs, ", ")), true) actargs = { #actlist } -- Actionlist offset is 1st arg to next dasm_put(). secpos = 1 -- The actionlist offset occupies a buffer position, too. end -- Put escaped word. local function wputw(n) if n >= 0xff000000 then waction("ESC") end wputxw(n) end -- Reserve position for word. local function wpos() local pos = #actlist+1 actlist[pos] = "" return pos end -- Store word to reserved position. local function wputpos(pos, n) assert(n >= 0 and n <= 0xffffffff and n % 1 == 0, "word out of range") actlist[pos] = n end ------------------------------------------------------------------------------ -- Global label name -> global label number. With auto assignment on 1st use. local next_global = 20 local map_global = setmetatable({}, { __index = function(t, name) if not match(name, "^[%a_][%w_]*$") then werror("bad global label") end local n = next_global if n > 2047 then werror("too many global labels") end next_global = n + 1 t[name] = n return n end}) -- Dump global labels. local function dumpglobals(out, lvl) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("Global labels:\n") for i=20,next_global-1 do out:write(format(" %s\n", t[i])) end out:write("\n") end -- Write global label enum. local function writeglobals(out, prefix) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("enum {\n") for i=20,next_global-1 do out:write(" ", prefix, t[i], ",\n") end out:write(" ", prefix, "_MAX\n};\n") end -- Write global label names. local function writeglobalnames(out, name) local t = {} for name, n in pairs(map_global) do t[n] = name end out:write("static const char *const ", name, "[] = {\n") for i=20,next_global-1 do out:write(" \"", t[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Extern label name -> extern label number. With auto assignment on 1st use. local next_extern = 0 local map_extern_ = {} local map_extern = setmetatable({}, { __index = function(t, name) -- No restrictions on the name for now. local n = next_extern if n > 2047 then werror("too many extern labels") end next_extern = n + 1 t[name] = n map_extern_[n] = name return n end}) -- Dump extern labels. local function dumpexterns(out, lvl) out:write("Extern labels:\n") for i=0,next_extern-1 do out:write(format(" %s\n", map_extern_[i])) end out:write("\n") end -- Write extern label names. local function writeexternnames(out, name) out:write("static const char *const ", name, "[] = {\n") for i=0,next_extern-1 do out:write(" \"", map_extern_[i], "\",\n") end out:write(" (const char *)0\n};\n") end ------------------------------------------------------------------------------ -- Arch-specific maps. local map_archdef = { sp="r29", ra="r31" } -- Ext. register name -> int. name. local map_type = {} -- Type name -> { ctype, reg } local ctypenum = 0 -- Type number (for Dt... macros). -- Reverse defines for registers. function _M.revdef(s) if s == "r29" then return "sp" elseif s == "r31" then return "ra" end return s end ------------------------------------------------------------------------------ -- Template strings for MIPS instructions. local map_op = { -- First-level opcodes. j_1 = "08000000J", jal_1 = "0c000000J", b_1 = "10000000B", beqz_2 = "10000000SB", beq_3 = "10000000STB", bnez_2 = "14000000SB", bne_3 = "14000000STB", blez_2 = "18000000SB", bgtz_2 = "1c000000SB", addi_3 = "20000000TSI", li_2 = "24000000TI", addiu_3 = "24000000TSI", slti_3 = "28000000TSI", sltiu_3 = "2c000000TSI", andi_3 = "30000000TSU", lu_2 = "34000000TU", ori_3 = "34000000TSU", xori_3 = "38000000TSU", lui_2 = "3c000000TU", beqzl_2 = "50000000SB", beql_3 = "50000000STB", bnezl_2 = "54000000SB", bnel_3 = "54000000STB", blezl_2 = "58000000SB", bgtzl_2 = "5c000000SB", lb_2 = "80000000TO", lh_2 = "84000000TO", lwl_2 = "88000000TO", lw_2 = "8c000000TO", lbu_2 = "90000000TO", lhu_2 = "94000000TO", lwr_2 = "98000000TO", sb_2 = "a0000000TO", sh_2 = "a4000000TO", swl_2 = "a8000000TO", sw_2 = "ac000000TO", swr_2 = "b8000000TO", cache_2 = "bc000000NO", ll_2 = "c0000000TO", lwc1_2 = "c4000000HO", pref_2 = "cc000000NO", ldc1_2 = "d4000000HO", sc_2 = "e0000000TO", swc1_2 = "e4000000HO", sdc1_2 = "f4000000HO", -- Opcode SPECIAL. nop_0 = "00000000", sll_3 = "00000000DTA", movf_2 = "00000001DS", movf_3 = "00000001DSC", movt_2 = "00010001DS", movt_3 = "00010001DSC", srl_3 = "00000002DTA", rotr_3 = "00200002DTA", sra_3 = "00000003DTA", sllv_3 = "00000004DTS", srlv_3 = "00000006DTS", rotrv_3 = "00000046DTS", srav_3 = "00000007DTS", jr_1 = "00000008S", jalr_1 = "0000f809S", jalr_2 = "00000009DS", movz_3 = "0000000aDST", movn_3 = "0000000bDST", syscall_0 = "0000000c", syscall_1 = "0000000cY", break_0 = "0000000d", break_1 = "0000000dY", sync_0 = "0000000f", mfhi_1 = "00000010D", mthi_1 = "00000011S", mflo_1 = "00000012D", mtlo_1 = "00000013S", mult_2 = "00000018ST", multu_2 = "00000019ST", div_2 = "0000001aST", divu_2 = "0000001bST", add_3 = "00000020DST", move_2 = "00000021DS", addu_3 = "00000021DST", sub_3 = "00000022DST", negu_2 = "00000023DT", subu_3 = "00000023DST", and_3 = "00000024DST", or_3 = "00000025DST", xor_3 = "00000026DST", not_2 = "00000027DS", nor_3 = "00000027DST", slt_3 = "0000002aDST", sltu_3 = "0000002bDST", tge_2 = "00000030ST", tge_3 = "00000030STZ", tgeu_2 = "00000031ST", tgeu_3 = "00000031STZ", tlt_2 = "00000032ST", tlt_3 = "00000032STZ", tltu_2 = "00000033ST", tltu_3 = "00000033STZ", teq_2 = "00000034ST", teq_3 = "00000034STZ", tne_2 = "00000036ST", tne_3 = "00000036STZ", -- Opcode REGIMM. bltz_2 = "04000000SB", bgez_2 = "04010000SB", bltzl_2 = "04020000SB", bgezl_2 = "04030000SB", tgei_2 = "04080000SI", tgeiu_2 = "04090000SI", tlti_2 = "040a0000SI", tltiu_2 = "040b0000SI", teqi_2 = "040c0000SI", tnei_2 = "040e0000SI", bltzal_2 = "04100000SB", bal_1 = "04110000B", bgezal_2 = "04110000SB", bltzall_2 = "04120000SB", bgezall_2 = "04130000SB", synci_1 = "041f0000O", -- Opcode SPECIAL2. madd_2 = "70000000ST", maddu_2 = "70000001ST", mul_3 = "70000002DST", msub_2 = "70000004ST", msubu_2 = "70000005ST", clz_2 = "70000020DS=", clo_2 = "70000021DS=", sdbbp_0 = "7000003f", sdbbp_1 = "7000003fY", -- Opcode SPECIAL3. ext_4 = "7c000000TSAM", -- Note: last arg is msbd = size-1 ins_4 = "7c000004TSAM", -- Note: last arg is msb = pos+size-1 wsbh_2 = "7c0000a0DT", seb_2 = "7c000420DT", seh_2 = "7c000620DT", rdhwr_2 = "7c00003bTD", -- Opcode COP0. mfc0_2 = "40000000TD", mfc0_3 = "40000000TDW", mtc0_2 = "40800000TD", mtc0_3 = "40800000TDW", rdpgpr_2 = "41400000DT", di_0 = "41606000", di_1 = "41606000T", ei_0 = "41606020", ei_1 = "41606020T", wrpgpr_2 = "41c00000DT", tlbr_0 = "42000001", tlbwi_0 = "42000002", tlbwr_0 = "42000006", tlbp_0 = "42000008", eret_0 = "42000018", deret_0 = "4200001f", wait_0 = "42000020", -- Opcode COP1. mfc1_2 = "44000000TG", cfc1_2 = "44400000TG", mfhc1_2 = "44600000TG", mtc1_2 = "44800000TG", ctc1_2 = "44c00000TG", mthc1_2 = "44e00000TG", bc1f_1 = "45000000B", bc1f_2 = "45000000CB", bc1t_1 = "45010000B", bc1t_2 = "45010000CB", bc1fl_1 = "45020000B", bc1fl_2 = "45020000CB", bc1tl_1 = "45030000B", bc1tl_2 = "45030000CB", ["add.s_3"] = "46000000FGH", ["sub.s_3"] = "46000001FGH", ["mul.s_3"] = "46000002FGH", ["div.s_3"] = "46000003FGH", ["sqrt.s_2"] = "46000004FG", ["abs.s_2"] = "46000005FG", ["mov.s_2"] = "46000006FG", ["neg.s_2"] = "46000007FG", ["round.l.s_2"] = "46000008FG", ["trunc.l.s_2"] = "46000009FG", ["ceil.l.s_2"] = "4600000aFG", ["floor.l.s_2"] = "4600000bFG", ["round.w.s_2"] = "4600000cFG", ["trunc.w.s_2"] = "4600000dFG", ["ceil.w.s_2"] = "4600000eFG", ["floor.w.s_2"] = "4600000fFG", ["movf.s_2"] = "46000011FG", ["movf.s_3"] = "46000011FGC", ["movt.s_2"] = "46010011FG", ["movt.s_3"] = "46010011FGC", ["movz.s_3"] = "46000012FGT", ["movn.s_3"] = "46000013FGT", ["recip.s_2"] = "46000015FG", ["rsqrt.s_2"] = "46000016FG", ["cvt.d.s_2"] = "46000021FG", ["cvt.w.s_2"] = "46000024FG", ["cvt.l.s_2"] = "46000025FG", ["cvt.ps.s_3"] = "46000026FGH", ["c.f.s_2"] = "46000030GH", ["c.f.s_3"] = "46000030VGH", ["c.un.s_2"] = "46000031GH", ["c.un.s_3"] = "46000031VGH", ["c.eq.s_2"] = "46000032GH", ["c.eq.s_3"] = "46000032VGH", ["c.ueq.s_2"] = "46000033GH", ["c.ueq.s_3"] = "46000033VGH", ["c.olt.s_2"] = "46000034GH", ["c.olt.s_3"] = "46000034VGH", ["c.ult.s_2"] = "46000035GH", ["c.ult.s_3"] = "46000035VGH", ["c.ole.s_2"] = "46000036GH", ["c.ole.s_3"] = "46000036VGH", ["c.ule.s_2"] = "46000037GH", ["c.ule.s_3"] = "46000037VGH", ["c.sf.s_2"] = "46000038GH", ["c.sf.s_3"] = "46000038VGH", ["c.ngle.s_2"] = "46000039GH", ["c.ngle.s_3"] = "46000039VGH", ["c.seq.s_2"] = "4600003aGH", ["c.seq.s_3"] = "4600003aVGH", ["c.ngl.s_2"] = "4600003bGH", ["c.ngl.s_3"] = "4600003bVGH", ["c.lt.s_2"] = "4600003cGH", ["c.lt.s_3"] = "4600003cVGH", ["c.nge.s_2"] = "4600003dGH", ["c.nge.s_3"] = "4600003dVGH", ["c.le.s_2"] = "4600003eGH", ["c.le.s_3"] = "4600003eVGH", ["c.ngt.s_2"] = "4600003fGH", ["c.ngt.s_3"] = "4600003fVGH", ["add.d_3"] = "46200000FGH", ["sub.d_3"] = "46200001FGH", ["mul.d_3"] = "46200002FGH", ["div.d_3"] = "46200003FGH", ["sqrt.d_2"] = "46200004FG", ["abs.d_2"] = "46200005FG", ["mov.d_2"] = "46200006FG", ["neg.d_2"] = "46200007FG", ["round.l.d_2"] = "46200008FG", ["trunc.l.d_2"] = "46200009FG", ["ceil.l.d_2"] = "4620000aFG", ["floor.l.d_2"] = "4620000bFG", ["round.w.d_2"] = "4620000cFG", ["trunc.w.d_2"] = "4620000dFG", ["ceil.w.d_2"] = "4620000eFG", ["floor.w.d_2"] = "4620000fFG", ["movf.d_2"] = "46200011FG", ["movf.d_3"] = "46200011FGC", ["movt.d_2"] = "46210011FG", ["movt.d_3"] = "46210011FGC", ["movz.d_3"] = "46200012FGT", ["movn.d_3"] = "46200013FGT", ["recip.d_2"] = "46200015FG", ["rsqrt.d_2"] = "46200016FG", ["cvt.s.d_2"] = "46200020FG", ["cvt.w.d_2"] = "46200024FG", ["cvt.l.d_2"] = "46200025FG", ["c.f.d_2"] = "46200030GH", ["c.f.d_3"] = "46200030VGH", ["c.un.d_2"] = "46200031GH", ["c.un.d_3"] = "46200031VGH", ["c.eq.d_2"] = "46200032GH", ["c.eq.d_3"] = "46200032VGH", ["c.ueq.d_2"] = "46200033GH", ["c.ueq.d_3"] = "46200033VGH", ["c.olt.d_2"] = "46200034GH", ["c.olt.d_3"] = "46200034VGH", ["c.ult.d_2"] = "46200035GH", ["c.ult.d_3"] = "46200035VGH", ["c.ole.d_2"] = "46200036GH", ["c.ole.d_3"] = "46200036VGH", ["c.ule.d_2"] = "46200037GH", ["c.ule.d_3"] = "46200037VGH", ["c.sf.d_2"] = "46200038GH", ["c.sf.d_3"] = "46200038VGH", ["c.ngle.d_2"] = "46200039GH", ["c.ngle.d_3"] = "46200039VGH", ["c.seq.d_2"] = "4620003aGH", ["c.seq.d_3"] = "4620003aVGH", ["c.ngl.d_2"] = "4620003bGH", ["c.ngl.d_3"] = "4620003bVGH", ["c.lt.d_2"] = "4620003cGH", ["c.lt.d_3"] = "4620003cVGH", ["c.nge.d_2"] = "4620003dGH", ["c.nge.d_3"] = "4620003dVGH", ["c.le.d_2"] = "4620003eGH", ["c.le.d_3"] = "4620003eVGH", ["c.ngt.d_2"] = "4620003fGH", ["c.ngt.d_3"] = "4620003fVGH", ["add.ps_3"] = "46c00000FGH", ["sub.ps_3"] = "46c00001FGH", ["mul.ps_3"] = "46c00002FGH", ["abs.ps_2"] = "46c00005FG", ["mov.ps_2"] = "46c00006FG", ["neg.ps_2"] = "46c00007FG", ["movf.ps_2"] = "46c00011FG", ["movf.ps_3"] = "46c00011FGC", ["movt.ps_2"] = "46c10011FG", ["movt.ps_3"] = "46c10011FGC", ["movz.ps_3"] = "46c00012FGT", ["movn.ps_3"] = "46c00013FGT", ["cvt.s.pu_2"] = "46c00020FG", ["cvt.s.pl_2"] = "46c00028FG", ["pll.ps_3"] = "46c0002cFGH", ["plu.ps_3"] = "46c0002dFGH", ["pul.ps_3"] = "46c0002eFGH", ["puu.ps_3"] = "46c0002fFGH", ["c.f.ps_2"] = "46c00030GH", ["c.f.ps_3"] = "46c00030VGH", ["c.un.ps_2"] = "46c00031GH", ["c.un.ps_3"] = "46c00031VGH", ["c.eq.ps_2"] = "46c00032GH", ["c.eq.ps_3"] = "46c00032VGH", ["c.ueq.ps_2"] = "46c00033GH", ["c.ueq.ps_3"] = "46c00033VGH", ["c.olt.ps_2"] = "46c00034GH", ["c.olt.ps_3"] = "46c00034VGH", ["c.ult.ps_2"] = "46c00035GH", ["c.ult.ps_3"] = "46c00035VGH", ["c.ole.ps_2"] = "46c00036GH", ["c.ole.ps_3"] = "46c00036VGH", ["c.ule.ps_2"] = "46c00037GH", ["c.ule.ps_3"] = "46c00037VGH", ["c.sf.ps_2"] = "46c00038GH", ["c.sf.ps_3"] = "46c00038VGH", ["c.ngle.ps_2"] = "46c00039GH", ["c.ngle.ps_3"] = "46c00039VGH", ["c.seq.ps_2"] = "46c0003aGH", ["c.seq.ps_3"] = "46c0003aVGH", ["c.ngl.ps_2"] = "46c0003bGH", ["c.ngl.ps_3"] = "46c0003bVGH", ["c.lt.ps_2"] = "46c0003cGH", ["c.lt.ps_3"] = "46c0003cVGH", ["c.nge.ps_2"] = "46c0003dGH", ["c.nge.ps_3"] = "46c0003dVGH", ["c.le.ps_2"] = "46c0003eGH", ["c.le.ps_3"] = "46c0003eVGH", ["c.ngt.ps_2"] = "46c0003fGH", ["c.ngt.ps_3"] = "46c0003fVGH", ["cvt.s.w_2"] = "46800020FG", ["cvt.d.w_2"] = "46800021FG", ["cvt.s.l_2"] = "46a00020FG", ["cvt.d.l_2"] = "46a00021FG", -- Opcode COP1X. lwxc1_2 = "4c000000FX", ldxc1_2 = "4c000001FX", luxc1_2 = "4c000005FX", swxc1_2 = "4c000008FX", sdxc1_2 = "4c000009FX", suxc1_2 = "4c00000dFX", prefx_2 = "4c00000fMX", ["alnv.ps_4"] = "4c00001eFGHS", ["madd.s_4"] = "4c000020FRGH", ["madd.d_4"] = "4c000021FRGH", ["madd.ps_4"] = "4c000026FRGH", ["msub.s_4"] = "4c000028FRGH", ["msub.d_4"] = "4c000029FRGH", ["msub.ps_4"] = "4c00002eFRGH", ["nmadd.s_4"] = "4c000030FRGH", ["nmadd.d_4"] = "4c000031FRGH", ["nmadd.ps_4"] = "4c000036FRGH", ["nmsub.s_4"] = "4c000038FRGH", ["nmsub.d_4"] = "4c000039FRGH", ["nmsub.ps_4"] = "4c00003eFRGH", } ------------------------------------------------------------------------------ local function parse_gpr(expr) local tname, ovreg = match(expr, "^([%w_]+):(r[1-3]?[0-9])$") local tp = map_type[tname or expr] if tp then local reg = ovreg or tp.reg if not reg then werror("type `"..(tname or expr).."' needs a register override") end expr = reg end local r = match(expr, "^r([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r, tp end end werror("bad register name `"..expr.."'") end local function parse_fpr(expr) local r = match(expr, "^f([1-3]?[0-9])$") if r then r = tonumber(r) if r <= 31 then return r end end werror("bad register name `"..expr.."'") end local function parse_imm(imm, bits, shift, scale, signed) local n = tonumber(imm) if n then local m = sar(n, scale) if shl(m, scale) == n then if signed then local s = sar(m, bits-1) if s == 0 then return shl(m, shift) elseif s == -1 then return shl(m + shl(1, bits), shift) end else if sar(m, bits) == 0 then return shl(m, shift) end end end werror("out of range immediate `"..imm.."'") elseif match(imm, "^[rf]([1-3]?[0-9])$") or match(imm, "^([%w_]+):([rf][1-3]?[0-9])$") then werror("expected immediate operand, got register") else waction("IMM", (signed and 32768 or 0)+scale*1024+bits*32+shift, imm) return 0 end end local function parse_disp(disp) local imm, reg = match(disp, "^(.*)%(([%w_:]+)%)$") if imm then local r = shl(parse_gpr(reg), 21) local extname = match(imm, "^extern%s+(%S+)$") if extname then waction("REL_EXT", map_extern[extname], nil, 1) return r else return r + parse_imm(imm, 16, 0, 0, true) end end local reg, tailr = match(disp, "^([%w_:]+)%s*(.*)$") if reg and tailr ~= "" then local r, tp = parse_gpr(reg) if tp then waction("IMM", 32768+16*32, format(tp.ctypefmt, tailr)) return shl(r, 21) end end werror("bad displacement `"..disp.."'") end local function parse_index(idx) local rt, rs = match(idx, "^(.*)%(([%w_:]+)%)$") if rt then rt = parse_gpr(rt) rs = parse_gpr(rs) return shl(rt, 16) + shl(rs, 21) end werror("bad index `"..idx.."'") end local function parse_label(label, def) local prefix = sub(label, 1, 2) -- =>label (pc label reference) if prefix == "=>" then return "PC", 0, sub(label, 3) end -- ->name (global label reference) if prefix == "->" then return "LG", map_global[sub(label, 3)] end if def then -- [1-9] (local label definition) if match(label, "^[1-9]$") then return "LG", 10+tonumber(label) end else -- [<>][1-9] (local label reference) local dir, lnum = match(label, "^([<>])([1-9])$") if dir then -- Fwd: 1-9, Bkwd: 11-19. return "LG", lnum + (dir == ">" and 0 or 10) end -- extern label (extern label reference) local extname = match(label, "^extern%s+(%S+)$") if extname then return "EXT", map_extern[extname] end end werror("bad label `"..label.."'") end ------------------------------------------------------------------------------ -- Handle opcodes defined with template strings. map_op[".template__"] = function(params, template, nparams) if not params then return sub(template, 9) end local op = tonumber(sub(template, 1, 8), 16) local n = 1 -- Limit number of section buffer positions used by a single dasm_put(). -- A single opcode needs a maximum of 2 positions (ins/ext). if secpos+2 > maxsecpos then wflush() end local pos = wpos() -- Process each character. for p in gmatch(sub(template, 9), ".") do if p == "D" then op = op + shl(parse_gpr(params[n]), 11); n = n + 1 elseif p == "T" then op = op + shl(parse_gpr(params[n]), 16); n = n + 1 elseif p == "S" then op = op + shl(parse_gpr(params[n]), 21); n = n + 1 elseif p == "F" then op = op + shl(parse_fpr(params[n]), 6); n = n + 1 elseif p == "G" then op = op + shl(parse_fpr(params[n]), 11); n = n + 1 elseif p == "H" then op = op + shl(parse_fpr(params[n]), 16); n = n + 1 elseif p == "R" then op = op + shl(parse_fpr(params[n]), 21); n = n + 1 elseif p == "I" then op = op + parse_imm(params[n], 16, 0, 0, true); n = n + 1 elseif p == "U" then op = op + parse_imm(params[n], 16, 0, 0, false); n = n + 1 elseif p == "O" then op = op + parse_disp(params[n]); n = n + 1 elseif p == "X" then op = op + parse_index(params[n]); n = n + 1 elseif p == "B" or p == "J" then local mode, n, s = parse_label(params[n], false) if p == "B" then n = n + 2048 end waction("REL_"..mode, n, s, 1) n = n + 1 elseif p == "A" then op = op + parse_imm(params[n], 5, 6, 0, false); n = n + 1 elseif p == "M" then op = op + parse_imm(params[n], 5, 11, 0, false); n = n + 1 elseif p == "N" then op = op + parse_imm(params[n], 5, 16, 0, false); n = n + 1 elseif p == "C" then op = op + parse_imm(params[n], 3, 18, 0, false); n = n + 1 elseif p == "V" then op = op + parse_imm(params[n], 3, 8, 0, false); n = n + 1 elseif p == "W" then op = op + parse_imm(params[n], 3, 0, 0, false); n = n + 1 elseif p == "Y" then op = op + parse_imm(params[n], 20, 6, 0, false); n = n + 1 elseif p == "Z" then op = op + parse_imm(params[n], 10, 6, 0, false); n = n + 1 elseif p == "=" then op = op + shl(band(op, 0xf800), 5) -- Copy D to T for clz, clo. else assert(false) end end wputpos(pos, op) end ------------------------------------------------------------------------------ -- Pseudo-opcode to mark the position where the action list is to be emitted. map_op[".actionlist_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeactions(out, name) end) end -- Pseudo-opcode to mark the position where the global enum is to be emitted. map_op[".globals_1"] = function(params) if not params then return "prefix" end local prefix = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobals(out, prefix) end) end -- Pseudo-opcode to mark the position where the global names are to be emitted. map_op[".globalnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeglobalnames(out, name) end) end -- Pseudo-opcode to mark the position where the extern names are to be emitted. map_op[".externnames_1"] = function(params) if not params then return "cvar" end local name = params[1] -- No syntax check. You get to keep the pieces. wline(function(out) writeexternnames(out, name) end) end ------------------------------------------------------------------------------ -- Label pseudo-opcode (converted from trailing colon form). map_op[".label_1"] = function(params) if not params then return "[1-9] | ->global | =>pcexpr" end if secpos+1 > maxsecpos then wflush() end local mode, n, s = parse_label(params[1], true) if mode == "EXT" then werror("bad label definition") end waction("LABEL_"..mode, n, s, 1) end ------------------------------------------------------------------------------ -- Pseudo-opcodes for data storage. map_op[".long_*"] = function(params) if not params then return "imm..." end for _,p in ipairs(params) do local n = tonumber(p) if not n then werror("bad immediate `"..p.."'") end if n < 0 then n = n + 2^32 end wputw(n) if secpos+2 > maxsecpos then wflush() end end end -- Alignment pseudo-opcode. map_op[".align_1"] = function(params) if not params then return "numpow2" end if secpos+1 > maxsecpos then wflush() end local align = tonumber(params[1]) if align then local x = align -- Must be a power of 2 in the range (2 ... 256). for i=1,8 do x = x / 2 if x == 1 then waction("ALIGN", align-1, nil, 1) -- Action byte is 2**n-1. return end end end werror("bad alignment") end ------------------------------------------------------------------------------ -- Pseudo-opcode for (primitive) type definitions (map to C types). map_op[".type_3"] = function(params, nparams) if not params then return nparams == 2 and "name, ctype" or "name, ctype, reg" end local name, ctype, reg = params[1], params[2], params[3] if not match(name, "^[%a_][%w_]*$") then werror("bad type name `"..name.."'") end local tp = map_type[name] if tp then werror("duplicate type `"..name.."'") end -- Add #type to defines. A bit unclean to put it in map_archdef. map_archdef["#"..name] = "sizeof("..ctype..")" -- Add new type and emit shortcut define. local num = ctypenum + 1 map_type[name] = { ctype = ctype, ctypefmt = format("Dt%X(%%s)", num), reg = reg, } wline(format("#define Dt%X(_V) (int)(ptrdiff_t)&(((%s *)0)_V)", num, ctype)) ctypenum = num end map_op[".type_2"] = map_op[".type_3"] -- Dump type definitions. local function dumptypes(out, lvl) local t = {} for name in pairs(map_type) do t[#t+1] = name end sort(t) out:write("Type definitions:\n") for _,name in ipairs(t) do local tp = map_type[name] local reg = tp.reg or "" out:write(format(" %-20s %-20s %s\n", name, tp.ctype, reg)) end out:write("\n") end ------------------------------------------------------------------------------ -- Set the current section. function _M.section(num) waction("SECTION", num) wflush(true) -- SECTION is a terminal action. end ------------------------------------------------------------------------------ -- Dump architecture description. function _M.dumparch(out) out:write(format("DynASM %s version %s, released %s\n\n", _info.arch, _info.version, _info.release)) dumpactions(out) end -- Dump all user defined elements. function _M.dumpdef(out, lvl) dumptypes(out, lvl) dumpglobals(out, lvl) dumpexterns(out, lvl) end ------------------------------------------------------------------------------ -- Pass callbacks from/to the DynASM core. function _M.passcb(wl, we, wf, ww) wline, werror, wfatal, wwarn = wl, we, wf, ww return wflush end -- Setup the arch-specific module. function _M.setup(arch, opt) g_arch, g_opt = arch, opt end -- Merge the core maps and the arch-specific maps. function _M.mergemaps(map_coreop, map_def) setmetatable(map_op, { __index = map_coreop }) setmetatable(map_def, { __index = map_archdef }) return map_op, map_def end return _M ------------------------------------------------------------------------------
apache-2.0
tltneon/NutScript
gamemode/core/derma/cl_intro.lua
5
3882
local gradient = nut.util.getMaterial("vgui/gradient-r.vtf") local glow = surface.GetTextureID("particle/Particle_Glow_04_Additive") local PANEL = {} function PANEL:Init() if (IsValid(nut.gui.intro)) then nut.gui.intro:Remove() end nut.gui.intro = self self:SetSize(ScrW(), ScrH()) self:SetZPos(9999) timer.Simple(0.1, function() if (!IsValid(self)) then return end self.sound = CreateSound(LocalPlayer(), "music/hl1_song20.mp3") self.sound:Play() self.sound:ChangePitch(80, 0) end) self.authors = self:Add("DLabel") self.authors:SetText(GAMEMODE.Author.." Presents") self.authors:SetFont("nutIntroMediumFont") self.authors:SetTextColor(color_white) self.authors:SetAlpha(0) self.authors:AlphaTo(255, 5, 1.5, function() self.authors:AlphaTo(0, 5, 3, function() self.authors:SetText("In collaboration with "..SCHEMA.author) self.authors:SizeToContents() self.authors:CenterHorizontal() self.authors:AlphaTo(255, 3, 0.5, function() if (self.sound) then self.sound:FadeOut(8) self.sound:FadeOut(8) end self.authors:AlphaTo(0, 3, 1, function() LocalPlayer():EmitSound("music/hl2_song10.mp3", 150, 70) self.cover:MoveTo(self.name:GetWide(), 0, 7.5, 5, nil, function() self.glow = true self.delta = 0 self.schema:AlphaTo(255, 5, 1) end) end) end) end) end) self.authors:SizeToContents() self.authors:Center() self.authors:SetZPos(99) self.name = self:Add("DLabel") self.name:SetText(GAMEMODE.Name) self.name:SetFont("nutIntroTitleFont") self.name:SetTextColor(color_white) self.name:SizeToContents() self.name:Center() self.name:SetPos(self.name.x, ScrH() * 0.4) self.name:SetExpensiveShadow(2, color_black) self.schema = self:Add("DLabel") self.schema:SetText(SCHEMA.introName and L(SCHEMA.introName) or L(SCHEMA.name)) self.schema:SetFont("nutIntroBigFont") self.schema:SizeToContents() self.schema:Center() self.schema:MoveBelow(self.name, 10) self.schema:SetAlpha(0) self.schema:SetExpensiveShadow(2, color_black) self.cover = self.name:Add("DPanel") self.cover:SetSize(ScrW(), self.name:GetTall()) self.cover.Paint = function(this, w, h) surface.SetDrawColor(0, 0, 0) surface.SetMaterial(gradient) surface.DrawTexturedRect(0, 0, 100, h) surface.DrawRect(100, 0, ScrW(), h) end self.cover:SetPos(-100, 0) timer.Simple(5, function() if (IsValid(self)) then self:addContinue() end end) end function PANEL:addContinue() self.info = self:Add("DLabel") self.info:Dock(BOTTOM) self.info:SetTall(36) self.info:DockMargin(0, 0, 0, 32) self.info:SetText("Press Space to continue...") self.info:SetFont("nutIntroSmallFont") self.info:SetContentAlignment(2) self.info:SetAlpha(0) self.info:AlphaTo(255, 1, 0, function() self.info.Paint = function(this) this:SetAlpha(math.abs(math.cos(RealTime() * 0.8) * 255)) end end) self.info:SetExpensiveShadow(1, color_black) end function PANEL:Think() if (IsValid(self.info) and input.IsKeyDown(KEY_SPACE) and !self.closing) then self.closing = true self:AlphaTo(0, 2.5, 0, function() self:Remove() end) end end function PANEL:OnRemove() if (self.sound) then self.sound:Stop() self.sound = nil if (IsValid(nut.gui.char)) then nut.gui.char:playMusic() end end end function PANEL:Paint(w, h) surface.SetDrawColor(0, 0, 0) surface.DrawRect(0, 0, w, h) if (self.glow) then self.delta = math.Approach(self.delta, 100, FrameTime() * 10) local x, y = ScrW()*0.5 - 700, ScrH()*0.5 - 340 surface.SetDrawColor(self.delta, self.delta, self.delta, self.delta + math.sin(RealTime() * 0.7)*10) surface.SetTexture(glow) surface.DrawTexturedRect(x, y, 1400, 680) end end vgui.Register("nutIntro", PANEL, "EditablePanel")
mit
EvPowerTeam/EV_OP
feeds/luci/applications/luci-openvpn/luasrc/model/cbi/openvpn-advanced.lua
71
20039
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> 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.ip") require("luci.model.uci") local knownParams = { -- -- Widget Name Default(s) Description Option(s) -- { "Service", { -- initialisation and daemon options { ListValue, "verb", { 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11 }, translate("Set output verbosity") }, { Flag, "mlock", 0, translate("Disable Paging") }, { Flag, "disable_occ", 0, translate("Disable options consistency check") }, -- { Value, "user", "root", translate("Set UID to user") }, -- { Value, "group", "root", translate("Set GID to group") }, { Value, "cd", "/etc/openvpn", translate("Change to directory before initialization") }, { Value, "chroot", "/var/run", translate("Chroot to directory after initialization") }, -- { Value, "daemon", "Instance-Name", translate("Daemonize after initialization") }, -- { Value, "syslog", "Instance-Name", translate("Output to syslog and do not daemonize") }, { Flag, "passtos", 0, translate("TOS passthrough (applies to IPv4 only)") }, -- { Value, "inetd", "nowait Instance-Name", translate("Run as an inetd or xinetd server") }, { Value, "log", "/var/log/openvpn.log", translate("Write log to file") }, { Value, "log_append", "/var/log/openvpn.log", translate("Append log to file") }, { Flag, "suppress_timestamps", 0, translate("Don't log timestamps") }, -- { Value, "writepid", "/var/run/openvpn.pid", translate("Write process ID to file") }, { Value, "nice", 0, translate("Change process priority") }, { Flag, "fast_io", 0, translate("Optimize TUN/TAP/UDP writes") }, { Value, "echo", "some params echoed to log", translate("Echo parameters to log") }, { ListValue, "remap_usr1", { "SIGHUP", "SIGTERM" }, translate("Remap SIGUSR1 signals") }, { Value, "status", "/var/run/openvpn.status 5", translate("Write status to file every n seconds") }, { Value, "status_version", { 1, 2 }, translate("Status file format version") }, -- status { Value, "mute", 5, translate("Limit repeated log messages") }, { Value, "up", "/usr/bin/ovpn-up", translate("Shell cmd to execute after tun device open") }, { Value, "up_delay", 5, translate("Delay tun/tap open and up script execution") }, { Value, "down", "/usr/bin/ovpn-down", translate("Shell cmd to run after tun device close") }, { Flag, "down_pre", 0, translate("Call down cmd/script before TUN/TAP close") }, { Flag, "up_restart", 0, translate("Run up/down scripts for all restarts") }, { Value, "route_up", "/usr/bin/ovpn-routeup", translate("Execute shell cmd after routes are added") }, { Value, "ipchange", "/usr/bin/ovpn-ipchange", translate("Execute shell command on remote ip change"), { mode="p2p" } }, { DynamicList, "setenv", { "VAR1 value1", "VAR2 value2" }, translate("Pass environment variables to script") }, { Value, "tls_verify", "/usr/bin/ovpn-tlsverify", translate("Shell command to verify X509 name") }, { Value, "client_connect", "/usr/bin/ovpn-clientconnect", translate("Run script cmd on client connection") }, { Flag, "client_disconnect", 0, translate("Run script cmd on client disconnection") }, { Value, "learn_address", "/usr/bin/ovpn-learnaddress", translate("Executed in server mode whenever an IPv4 address/route or MAC address is added to OpenVPN's internal routing table") }, { Value, "auth_user_pass_verify", "/usr/bin/ovpn-userpass via-env", translate("Executed in server mode on new client connections, when the client is still untrusted") }, { ListValue, "script_security", { 0, 1, 2, 3 }, translate("Policy level over usage of external programs and scripts"), {mode="server" } }, } }, { "Networking", { -- socket config { ListValue, "mode", { "p2p", "server" }, translate("Major mode") }, { Value, "local", "0.0.0.0", translate("Local host name or ip address") }, { Value, "port", 1194, translate("TCP/UDP port # for both local and remote") }, { Value, "lport", 1194, translate("TCP/UDP port # for local (default=1194)") }, { Value, "rport", 1194, translate("TCP/UDP port # for remote (default=1194)") }, { Flag, "float", 0, translate("Allow remote to change its IP or port") }, { Flag, "nobind", 0, translate("Do not bind to local address and port") }, { Value, "dev", "tun0", translate("tun/tap device") }, { ListValue, "dev_type", { "tun", "tap" }, translate("Type of used device") }, { Value, "dev_node", "/dev/net/tun", translate("Use tun/tap device node") }, { Flag, "tun_ipv6", 0, translate("Make tun device IPv6 capable") }, { Value, "ifconfig", "10.200.200.3 10.200.200.1", translate("Set tun/tap adapter parameters") }, { Flag, "ifconfig_noexec", 0, translate("Don't actually execute ifconfig") }, { Flag, "ifconfig_nowarn", 0, translate("Don't warn on ifconfig inconsistencies") }, { DynamicList, "route", "10.123.0.0 255.255.0.0", translate("Add route after establishing connection") }, { Value, "route_gateway", "10.234.1.1", translate("Specify a default gateway for routes") }, { Value, "route_delay", 0, translate("Delay n seconds after connection") }, { Flag, "route_noexec", 0, translate("Don't add routes automatically") }, { ListValue, "mtu_disc", { "yes", "maybe", "no" }, translate("Enable Path MTU discovery") }, { Flag, "mtu_test", 0, translate("Empirically measure MTU") }, { Flag, "comp_lzo", 0, translate("Use fast LZO compression") }, { Flag, "comp_noadapt", 0, translate("Don't use adaptive lzo compression"), { comp_lzo=1 } }, { Value, "link_mtu", 1500, translate("Set TCP/UDP MTU") }, { Value, "tun_mtu", 1500, translate("Set tun/tap device MTU") }, { Value, "tun_mtu_extra", 1500, translate("Set tun/tap device overhead") }, { Value, "fragment", 1500, translate("Enable internal datagram fragmentation"), { proto="udp" } }, { Value, "mssfix", 1500, translate("Set upper bound on TCP MSS"), { proto="udp" } }, { Value, "sndbuf", 65536, translate("Set the TCP/UDP send buffer size") }, { Value, "rcvbuf", 65536, translate("Set the TCP/UDP receive buffer size") }, { Value, "txqueuelen", 100, translate("Set tun/tap TX queue length") }, { Value, "shaper", 10240, translate("Shaping for peer bandwidth") }, { Value, "inactive", 240, translate("tun/tap inactivity timeout") }, { Value, "keepalive", "10 60", translate("Helper directive to simplify the expression of --ping and --ping-restart in server mode configurations") }, { Value, "ping", 30, translate("Ping remote every n seconds over TCP/UDP port") }, { Value, "ping_exit", 120, translate("Remote ping timeout") }, { Value, "ping_restart", 60, translate("Restart after remote ping timeout") }, { Flag, "ping_timer_rem", 0, translate("Only process ping timeouts if routes exist") }, { Flag, "persist_tun", 0, translate("Keep tun/tap device open on restart") }, { Flag, "persist_key", 0, translate("Don't re-read key on restart") }, { Flag, "persist_local_ip", 0, translate("Keep local IP address on restart") }, { Flag, "persist_remote_ip", 0, translate("Keep remote IP address on restart") }, -- management channel { Value, "management", "127.0.0.1 31194 /etc/openvpn/mngmt-pwds", translate("Enable management interface on <em>IP</em> <em>port</em>") }, { Flag, "management_query_passwords", 0, translate("Query management channel for private key") }, -- management { Flag, "management_hold", 0, translate("Start OpenVPN in a hibernating state") }, -- management { Value, "management_log_cache", 100, translate("Number of lines for log file history") }, -- management { ListValue, "topology", { "net30", "p2p", "subnet" }, translate("'net30', 'p2p', or 'subnet'"), {dev_type="tun" } }, } }, { "VPN", { { Value, "server", "10.200.200.0 255.255.255.0", translate("Configure server mode"), { server_mode="1" } }, { Value, "server_bridge", "10.200.200.1 255.255.255.0 10.200.200.200 10.200.200.250", translate("Configure server bridge"), { server_mode="1" } }, { DynamicList, "push", { "redirect-gateway", "comp-lzo" }, translate("Push options to peer"), { server_mode="1" } }, { Flag, "push_reset", 0, translate("Don't inherit global push options"), { server_mode="1" } }, { Flag, "disable", 0, translate("Client is disabled"), { server_mode="1" } }, { Value, "ifconfig_pool", "10.200.200.100 10.200.200.150 255.255.255.0", translate("Set aside a pool of subnets"), { server_mode="1" } }, { Value, "ifconfig_pool_persist", "/etc/openvpn/ipp.txt 600", translate("Persist/unpersist ifconfig-pool"), { server_mode="1" } }, -- { Flag, "ifconfig_pool_linear", 0, translate("Use individual addresses rather than /30 subnets"), { server_mode="1" } }, -- deprecated and replaced by --topology p2p { Value, "ifconfig_push", "10.200.200.1 255.255.255.255", translate("Push an ifconfig option to remote"), { server_mode="1" } }, { Value, "iroute", "10.200.200.0 255.255.255.0", translate("Route subnet to client"), { server_mode="1" } }, { Flag, "client_to_client", 0, translate("Allow client-to-client traffic"), { server_mode="1" } }, { Flag, "duplicate_cn", 0, translate("Allow multiple clients with same certificate"), { server_mode="1" } }, { Value, "client_config_dir", "/etc/openvpn/ccd", translate("Directory for custom client config files"), { server_mode="1" } }, { Flag, "ccd_exclusive", 0, translate("Refuse connection if no custom client config"), { server_mode="1" } }, { Value, "tmp_dir", "/var/run/openvpn", translate("Temporary directory for client-connect return file"), { server_mode="1" } }, { Value, "hash_size", "256 256", translate("Set size of real and virtual address hash tables"), { server_mode="1" } }, { Value, "bcast_buffers", 256, translate("Number of allocated broadcast buffers"), { server_mode="1" } }, { Value, "tcp_queue_limit", 64, translate("Maximum number of queued TCP output packets"), { server_mode="1" } }, { Value, "max_clients", 10, translate("Allowed maximum of connected clients"), { server_mode="1" } }, { Value, "max_routes_per_client", 256, translate("Allowed maximum of internal"), { server_mode="1" } }, { Value, "connect_freq", "3 10", translate("Allowed maximum of new connections"), { server_mode="1" } }, { Flag, "client_cert_not_required", 0, translate("Don't require client certificate"), { server_mode="1" } }, { Flag, "username_as_common_name", 0, translate("Use username as common name"), { server_mode="1" } }, { Flag, "client", 0, translate("Configure client mode"), { server_mode="0" }, { server_mode="" } }, { Flag, "pull", 0, translate("Accept options pushed from server"), { client="1" } }, { Value, "auth_user_pass", "/etc/openvpn/userpass.txt", translate("Authenticate using username/password"), { client="1" } }, { ListValue, "auth_retry", { "none", "nointeract", "interact" }, translate("Handling of authentication failures"), { client="1" } }, { Value, "explicit_exit_notify", 1, translate("Send notification to peer on disconnect"), { client="1" } }, { DynamicList, "remote", "1.2.3.4", translate("Remote host name or ip address"), { client="1" } }, { Flag, "remote_random", 1, translate("Randomly choose remote server"), { client="1" } }, { ListValue, "proto", { "udp", "tcp-client", "tcp-server" }, translate("Use protocol"), { client="1" } }, { Value, "connect_retry", 5, translate("Connection retry interval"), { proto="tcp-client" }, { client="1" } }, { Value, "http_proxy", "192.168.1.100 8080", translate("Connect to remote host through an HTTP proxy"), { client="1" } }, { Flag, "http_proxy_retry", 0, translate("Retry indefinitely on HTTP proxy errors"), { client="1" } }, { Value, "http_proxy_timeout", 5, translate("Proxy timeout in seconds"), { client="1" } }, { DynamicList, "http_proxy_option", { "VERSION 1.0", "AGENT OpenVPN/2.0.9" }, translate("Set extended HTTP proxy options"), { client="1" } }, { Value, "socks_proxy", "192.168.1.200 1080", translate("Connect through Socks5 proxy"), { client="1" } }, { Value, "socks_proxy_retry", 5, translate("Retry indefinitely on Socks proxy errors"), { client="1" } }, -- client && socks_proxy { Value, "resolv_retry", "infinite", translate("If hostname resolve fails, retry"), { client="1" } }, { ListValue, "redirect_gateway", { "", "local", "def1", "local def1" }, translate("Automatically redirect default route"), { client="1" } }, } }, { "Cryptography", { { Value, "secret", "/etc/openvpn/secret.key 1", translate("Enable Static Key encryption mode (non-TLS)") }, { Value, "auth", "SHA1", translate("HMAC authentication for packets") }, -- parse { Value, "cipher", "BF-CBC", translate("Encryption cipher for packets") }, -- parse { Value, "keysize", 1024, translate("Size of cipher key") }, -- parse { Value, "engine", "dynamic", translate("Enable OpenSSL hardware crypto engines") }, -- parse { Flag, "no_replay", 0, translate("Disable replay protection") }, { Value, "replay_window", "64 15", translate("Replay protection sliding window size") }, { Flag, "mute_replay_warnings", 0, translate("Silence the output of replay warnings") }, { Value, "replay_persist", "/var/run/openvpn-replay-state", translate("Persist replay-protection state") }, { Flag, "no_iv", 0, translate("Disable cipher initialisation vector") }, { Flag, "tls_server", 0, translate("Enable TLS and assume server role"), { tls_client="" }, { tls_client="0" } }, { Flag, "tls_client", 0, translate("Enable TLS and assume client role"), { tls_server="" }, { tls_server="0" } }, { FileUpload, "ca", "/etc/easy-rsa/keys/ca.crt", translate("Certificate authority") }, { FileUpload, "dh", "/etc/easy-rsa/keys/dh1024.pem", translate("Diffie Hellman parameters") }, { FileUpload, "cert", "/etc/easy-rsa/keys/some-client.crt", translate("Local certificate") }, { FileUpload, "key", "/etc/easy-rsa/keys/some-client.key", translate("Local private key") }, { FileUpload, "pkcs12", "/etc/easy-rsa/keys/some-client.pk12", translate("PKCS#12 file containing keys") }, { ListValue, "key_method", { 1, 2 }, translate("Enable TLS and assume client role") }, { Value, "tls_cipher", "DHE-RSA-AES256-SHA:DHE-DSS-AES256-SHA:AES256-SHA:EDH-RSA-DES-CBC3-SHA:EDH-DSS-DES-CBC3-SHA:DES-CBC3-SHA:DHE-RSA-AES128-SHA:DHE-DSS-AES128-SHA:AES128-SHA:RC4-SHA:RC4-MD5:EDH-RSA-DES-CBC-SHA:EDH-DSS-DES-CBC-SHA:DES-CBC-SHA:EXP-EDH-RSA-DES-CBC-SHA:EXP-EDH-DSS-DES-CBC-SHA:EXP-DES-CBC-SHA:EXP-RC2-CBC-MD5:EXP-RC4-MD5", translate("TLS cipher") }, { Value, "tls_timeout", 2, translate("Retransmit timeout on TLS control channel") }, { Value, "reneg_bytes", 1024, translate("Renegotiate data chan. key after bytes") }, { Value, "reneg_pkts", 100, translate("Renegotiate data chan. key after packets") }, { Value, "reneg_sec", 3600, translate("Renegotiate data chan. key after seconds") }, { Value, "hand_window", 60, translate("Timeframe for key exchange") }, { Value, "tran_window", 3600, translate("Key transition window") }, { Flag, "single_session", 0, translate("Allow only one session") }, { Flag, "tls_exit", 0, translate("Exit on TLS negotiation failure") }, { Value, "tls_auth", "/etc/openvpn/tlsauth.key 1", translate("Additional authentication over TLS") }, --{ Value, "askpass", "[file]", translate("Get PEM password from controlling tty before we daemonize") }, { Flag, "auth_nocache", 0, translate("Don't cache --askpass or --auth-user-pass passwords") }, { Value, "tls_remote", "remote_x509_name", translate("Only accept connections from given X509 name") }, { ListValue, "ns_cert_type", { "client", "server" }, translate("Require explicit designation on certificate") }, { ListValue, "remote_cert_tls", { "client", "server" }, translate("Require explicit key usage on certificate") }, { Value, "crl_verify", "/etc/easy-rsa/keys/crl.pem", translate("Check peer certificate against a CRL") }, } } } local cts = { } local params = { } local m = Map("openvpn") local p = m:section( SimpleSection ) p.template = "openvpn/pageswitch" p.mode = "advanced" p.instance = arg[1] p.category = arg[2] or "Service" for _, c in ipairs(knownParams) do cts[#cts+1] = c[1] if c[1] == p.category then params = c[2] end end p.categories = cts local s = m:section( NamedSection, arg[1], "openvpn", translate("%s" % arg[2]) ) s.title = translate("%s" % arg[2]) s.addremove = false s.anonymous = true for _, option in ipairs(params) do local o = s:option( option[1], option[2], option[2], option[4] ) if option[1] == DummyValue then o.value = option[3] else if option[1] == DynamicList then o.cast = nil function o.cfgvalue(...) local val = AbstractValue.cfgvalue(...) return ( val and type(val) ~= "table" ) and { val } or val end end o.optional = true if type(option[3]) == "table" then if o.optional then o:value("", "-- remove --") end for _, v in ipairs(option[3]) do v = tostring(v) o:value(v) end o.default = tostring(option[3][1]) else o.default = tostring(option[3]) end end for i=5,#option do if type(option[i]) == "table" then o:depends(option[i]) end end end return m
gpl-2.0
kengonakajima/luvit-mysql
test.lua
7
3819
-- make it looks like node-mysql semantics local timer = require( "timer" ) -- luvit built-in local MySQL = require( "./mysql" ) local client = MySQL.createClient( { database="test",user="passtestuser",port=3306,password="hoge", logfunc=nil } ) client:ping( function() print("ping received") end) client:query( "CREATE DATABASE luvit_mysql_testdb", function(err) if err then print("query error. code:", err.message, err.number, MySQL.ERROR_DB_CREATE_EXISTS ) end if err and err.number ~= MySQL.ERROR_DB_CREATE_EXISTS then error("cannot create db" ) end end) client:query( "USE luvit_mysql_testdb" ) client:query( "DROP TABLE IF EXISTS testtable", function(err,res,fields) assert(not err) end) client:query( "CREATE TABLE testtable (id INT(11) AUTO_INCREMENT, name VARCHAR(255), age INT(11), created DATETIME, PRIMARY KEY (id) )", function(err,res,fields) print("CREATE TABLE DONE") assert( not err ) client:query( "INSERT INTO testtable SET name = 'george', age = 20, created=now()", function(err) assert( not err ) print("INSERT DONE 1") end) client:query( "INSERT INTO testtable SET name = 'jack', age = 30, created=now()", function(err) assert( not err ) print("INSERT DONE 2") end) client:query( "INSERT INTO testtable SET name = 'ken', age = 40, created=now()", function(err) assert( not err ) print("INSERT DONE 3") end) end) client:query( "DROP TABLE IF EXISTS longstringtable", function(err,res,fields) assert(not err) function makestr(n) local out="" for i=1,n-1 do out = out .. "a" end out = out .. "b" return out end client:query( "CREATE TABLE longstringtable ( name mediumblob )", function(err) if err then print(err.message) end assert(not err) client:query( "INSERT INTO longstringtable set name = '" .. makestr(50*1000) .. "'", function(err) if err then print(err.message) end assert(not err) print("long insert done") end) end) end) -- use timer because we're not sure about above INSERT finishes before following SELECT. timer.setInterval( 1000, function() print("timer interval!") if not cnt then cnt = 1 end local q = client:query( "SELECT * FROM testtable", function(err,res,fields) assert(not err) assert( fields.id ) assert( fields.name ) assert( fields.age ) assert( fields.created ) assert( #res == 3 ) assert( res[1].id == 1 ) assert( res[1].name == "george" ) assert( res[1].age == 20 ) assert( res[1].created.year ) assert( res[1].created.month ) assert( res[1].created.day ) assert( res[1].created.hour ) assert( res[1].created.minute ) assert( res[1].created.second ) assert( res[2].id == 2 ) assert( res[2].name == "jack" ) assert( res[2].age == 30 ) assert( res[2].created.year ) assert( res[2].created.month ) assert( res[2].created.day ) assert( res[2].created.hour ) assert( res[2].created.minute ) assert( res[2].created.second ) assert( res[3].id == 3 ) assert( res[3].name == "ken" ) assert( res[3].age == 40 ) assert( res[3].created.year ) assert( res[3].created.month ) assert( res[3].created.day ) assert( res[3].created.hour ) assert( res[3].created.minute ) assert( res[3].created.second ) print("select done. cnt:",cnt) cnt = cnt + 1 if cnt > 10 then print("test success!") process.exit(0) end end) end)
apache-2.0
yangboz/petulant-octo-dubstep
HP_ID_Print_App/cocos2d-x-3.2/cocos/scripting/lua-bindings/auto/api/PhysicsShape.lua
1
4440
-------------------------------- -- @module PhysicsShape -- @extend Ref -------------------------------- -- @function [parent=#PhysicsShape] getFriction -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsShape] setGroup -- @param self -- @param #int int -------------------------------- -- @function [parent=#PhysicsShape] setDensity -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsShape] getMass -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsShape] getMaterial -- @param self -- @return PhysicsMaterial#PhysicsMaterial ret (return value: cc.PhysicsMaterial) -------------------------------- -- @function [parent=#PhysicsShape] getCollisionBitmask -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#PhysicsShape] getArea -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsShape] setCategoryBitmask -- @param self -- @param #int int -------------------------------- -- @function [parent=#PhysicsShape] getGroup -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#PhysicsShape] setMoment -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsShape] containsPoint -- @param self -- @param #vec2_table vec2 -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#PhysicsShape] getCategoryBitmask -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#PhysicsShape] getType -- @param self -- @return PhysicsShape::Type#PhysicsShape::Type ret (return value: cc.PhysicsShape::Type) -------------------------------- -- @function [parent=#PhysicsShape] getContactTestBitmask -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#PhysicsShape] getCenter -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- @function [parent=#PhysicsShape] getDensity -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsShape] setMass -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsShape] getTag -- @param self -- @return int#int ret (return value: int) -------------------------------- -- @function [parent=#PhysicsShape] calculateDefaultMoment -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsShape] setCollisionBitmask -- @param self -- @param #int int -------------------------------- -- @function [parent=#PhysicsShape] getMoment -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsShape] getOffset -- @param self -- @return vec2_table#vec2_table ret (return value: vec2_table) -------------------------------- -- @function [parent=#PhysicsShape] getRestitution -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsShape] setFriction -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsShape] setMaterial -- @param self -- @param #cc.PhysicsMaterial physicsmaterial -------------------------------- -- @function [parent=#PhysicsShape] setTag -- @param self -- @param #int int -------------------------------- -- @function [parent=#PhysicsShape] setContactTestBitmask -- @param self -- @param #int int -------------------------------- -- @function [parent=#PhysicsShape] setRestitution -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsShape] getBody -- @param self -- @return PhysicsBody#PhysicsBody ret (return value: cc.PhysicsBody) return nil
mit
telergybot/telergy2
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
mortezaand/tgpragramer
mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
alireza1998/mega
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
badboyam/boti
libs/mimetype.lua
3662
2922
-- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types do local mimetype = {} -- TODO: Add more? local types = { ["text/html"] = "html", ["text/css"] = "css", ["text/xml"] = "xml", ["image/gif"] = "gif", ["image/jpeg"] = "jpg", ["application/x-javascript"] = "js", ["application/atom+xml"] = "atom", ["application/rss+xml"] = "rss", ["text/mathml"] = "mml", ["text/plain"] = "txt", ["text/vnd.sun.j2me.app-descriptor"] = "jad", ["text/vnd.wap.wml"] = "wml", ["text/x-component"] = "htc", ["image/png"] = "png", ["image/tiff"] = "tiff", ["image/vnd.wap.wbmp"] = "wbmp", ["image/x-icon"] = "ico", ["image/x-jng"] = "jng", ["image/x-ms-bmp"] = "bmp", ["image/svg+xml"] = "svg", ["image/webp"] = "webp", ["application/java-archive"] = "jar", ["application/mac-binhex40"] = "hqx", ["application/msword"] = "doc", ["application/pdf"] = "pdf", ["application/postscript"] = "ps", ["application/rtf"] = "rtf", ["application/vnd.ms-excel"] = "xls", ["application/vnd.ms-powerpoint"] = "ppt", ["application/vnd.wap.wmlc"] = "wmlc", ["application/vnd.google-earth.kml+xml"] = "kml", ["application/vnd.google-earth.kmz"] = "kmz", ["application/x-7z-compressed"] = "7z", ["application/x-cocoa"] = "cco", ["application/x-java-archive-diff"] = "jardiff", ["application/x-java-jnlp-file"] = "jnlp", ["application/x-makeself"] = "run", ["application/x-perl"] = "pl", ["application/x-pilot"] = "prc", ["application/x-rar-compressed"] = "rar", ["application/x-redhat-package-manager"] = "rpm", ["application/x-sea"] = "sea", ["application/x-shockwave-flash"] = "swf", ["application/x-stuffit"] = "sit", ["application/x-tcl"] = "tcl", ["application/x-x509-ca-cert"] = "crt", ["application/x-xpinstall"] = "xpi", ["application/xhtml+xml"] = "xhtml", ["application/zip"] = "zip", ["application/octet-stream"] = "bin", ["audio/midi"] = "mid", ["audio/mpeg"] = "mp3", ["audio/ogg"] = "ogg", ["audio/x-m4a"] = "m4a", ["audio/x-realaudio"] = "ra", ["video/3gpp"] = "3gpp", ["video/mp4"] = "mp4", ["video/mpeg"] = "mpeg", ["video/quicktime"] = "mov", ["video/webm"] = "webm", ["video/x-flv"] = "flv", ["video/x-m4v"] = "m4v", ["video/x-mng"] = "mng", ["video/x-ms-asf"] = "asf", ["video/x-ms-wmv"] = "wmv", ["video/x-msvideo"] = "avi" } -- Returns the common file extension from a content-type function mimetype.get_mime_extension(content_type) return types[content_type] end -- Returns the mimetype and subtype function mimetype.get_content_type(extension) for k,v in pairs(types) do if v == extension then return k end end end -- Returns the mimetype without the subtype function mimetype.get_content_type_no_sub(extension) for k,v in pairs(types) do if v == extension then -- Before / return k:match('([%w-]+)/') end end end return mimetype end
gpl-2.0
sundream/gamesrv
script/card/neutral/card261016.lua
1
2315
--<<card 导表开始>> local super = require "script.card.neutral.card161016" ccard261016 = class("ccard261016",super,{ sid = 261016, race = 6, name = "伊利丹·怒风", type = 201, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 1, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 1, composechip = 100, decomposechip = 10, atk = 7, maxhp = 5, crystalcost = 6, targettype = 0, halo = nil, desc = "每当你使用一张牌时,召唤一个2/1的埃辛诺斯烈焰。", effect = { onuse = nil, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = {addfootman={sid=166020,num=1}}, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard261016:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard261016:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard261016:save() local data = super.save(self) -- todo: save data return data end return ccard261016
gpl-2.0
yangboz/petulant-octo-dubstep
HP_ID_Print_App/cocos2d-x-3.2/cocos/scripting/lua-bindings/auto/api/LabelBMFont.lua
1
3545
-------------------------------- -- @module LabelBMFont -- @extend Node,LabelProtocol,BlendProtocol -------------------------------- -- @function [parent=#LabelBMFont] setLineBreakWithoutSpace -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#LabelBMFont] getBlendFunc -- @param self -- @return BlendFunc#BlendFunc ret (return value: cc.BlendFunc) -------------------------------- -- @function [parent=#LabelBMFont] isOpacityModifyRGB -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#LabelBMFont] getLetter -- @param self -- @param #int int -- @return Sprite#Sprite ret (return value: cc.Sprite) -------------------------------- -- @function [parent=#LabelBMFont] getString -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#LabelBMFont] setBlendFunc -- @param self -- @param #cc.BlendFunc blendfunc -------------------------------- -- @function [parent=#LabelBMFont] setString -- @param self -- @param #string str -------------------------------- -- @function [parent=#LabelBMFont] initWithString -- @param self -- @param #string str -- @param #string str -- @param #float float -- @param #cc.TextHAlignment texthalignment -- @param #vec2_table vec2 -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#LabelBMFont] setOpacityModifyRGB -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#LabelBMFont] getFntFile -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#LabelBMFont] setFntFile -- @param self -- @param #string str -- @param #vec2_table vec2 -------------------------------- -- @function [parent=#LabelBMFont] setAlignment -- @param self -- @param #cc.TextHAlignment texthalignment -------------------------------- -- @function [parent=#LabelBMFont] setWidth -- @param self -- @param #float float -------------------------------- -- overload function: create() -- -- overload function: create(string, string, float, cc.TextHAlignment, vec2_table) -- -- @function [parent=#LabelBMFont] create -- @param self -- @param #string str -- @param #string str -- @param #float float -- @param #cc.TextHAlignment texthalignment -- @param #vec2_table vec2 -- @return LabelBMFont#LabelBMFont ret (retunr value: cc.LabelBMFont) -------------------------------- -- @function [parent=#LabelBMFont] getBoundingBox -- @param self -- @return rect_table#rect_table ret (return value: rect_table) -------------------------------- -- @function [parent=#LabelBMFont] getDescription -- @param self -- @return string#string ret (return value: string) -------------------------------- -- @function [parent=#LabelBMFont] setColor -- @param self -- @param #color3b_table color3b -------------------------------- -- @function [parent=#LabelBMFont] getChildByTag -- @param self -- @param #int int -- @return Node#Node ret (return value: cc.Node) -------------------------------- -- @function [parent=#LabelBMFont] getContentSize -- @param self -- @return size_table#size_table ret (return value: size_table) -------------------------------- -- @function [parent=#LabelBMFont] LabelBMFont -- @param self return nil
mit
sundream/gamesrv
script/card/golden/card112002.lua
1
2492
--<<card 导表开始>> local super = require "script.card.init" ccard112002 = class("ccard112002",super,{ sid = 112002, race = 1, name = "炎爆术", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 0, maxhp = 0, crystalcost = 10, targettype = 33, halo = nil, desc = "造成10点伤害", effect = { onuse = {magic_hurt=10}, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard112002:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard112002:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard112002:save() local data = super.save(self) -- todo: save data return data end function ccard112002:onuse(pos,targetid,choice) local owner = self:getowner() local target = owner:gettarget(targetid) local magic_hurt = ccard112002.effect.onuse.magic_hurt magic_hurt = self:get_magic_hurt(magic_hurt) target:addhp(-magic_hurt,self.id) end return ccard112002
gpl-2.0
rastin45/waqer12
plugins/sudo.lua
359
1878
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!cpu') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!cpu", patterns = {"^!cpu", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
spark0511/revolt_bot
plugins/sudo.lua
359
1878
function run_sh(msg) name = get_name(msg) text = '' -- if config.sh_enabled == false then -- text = '!sh command is disabled' -- else -- if is_sudo(msg) then -- bash = msg.text:sub(4,-1) -- text = run_bash(bash) -- else -- text = name .. ' you have no power here!' -- end -- end if is_sudo(msg) then bash = msg.text:sub(4,-1) text = run_bash(bash) else text = name .. ' you have no power here!' end return text end function run_bash(str) local cmd = io.popen(str) local result = cmd:read('*all') cmd:close() return result end function on_getting_dialogs(cb_extra,success,result) if success then local dialogs={} for key,value in pairs(result) do for chatkey, chat in pairs(value.peer) do print(chatkey,chat) if chatkey=="id" then table.insert(dialogs,chat.."\n") end if chatkey=="print_name" then table.insert(dialogs,chat..": ") end end end send_msg(cb_extra[1],table.concat(dialogs),ok_cb,false) end end function run(msg, matches) if not is_sudo(msg) then return "You aren't allowed!" end local receiver = get_receiver(msg) if string.match(msg.text, '!sh') then text = run_sh(msg) send_msg(receiver, text, ok_cb, false) return end if string.match(msg.text, '!cpu') then text = run_bash('uname -snr') .. ' ' .. run_bash('whoami') text = text .. '\n' .. run_bash('top -b |head -2') send_msg(receiver, text, ok_cb, false) return end if matches[1]=="Get dialogs" then get_dialog_list(on_getting_dialogs,{get_receiver(msg)}) return end end return { description = "shows cpuinfo", usage = "!cpu", patterns = {"^!cpu", "^!sh","^Get dialogs$"}, run = run }
gpl-2.0
REZATITAN/AntiSpamBot
plugins/ingroup.lua
45
56305
do -- Check Member local function check_member_autorealm(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Welcome to your new realm !') end end end local function check_member_realm_add(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Realm', settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes' } } save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = {} save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been added!') end end end function check_member_group(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'You have been promoted as the owner.') end end end local function check_member_modadd(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration data[tostring(msg.to.id)] = { group_type = 'Group', moderators = {}, set_owner = member_id , settings = { set_name = string.gsub(msg.to.print_name, '_', ' '), lock_name = 'yes', lock_photo = 'no', lock_member = 'no', flood = 'yes', } } save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = {} save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = msg.to.id save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group is added and you have been promoted as the owner ') end end end local function automodadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_group,{receiver=receiver, data=data, msg = msg}) end end local function autorealmadd(msg) local data = load_data(_config.moderation.data) if msg.action.type == 'chat_created' then receiver = get_receiver(msg) chat_info(receiver, check_member_autorealm,{receiver=receiver, data=data, msg = msg}) end end local function check_member_realmrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Realm configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local realms = 'realms' if not data[tostring(realms)] then data[tostring(realms)] = nil save_data(_config.moderation.data, data) end data[tostring(realms)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Realm has been removed!') end end end local function check_member_modrem(cb_extra, success, result) local receiver = cb_extra.receiver local data = cb_extra.data local msg = cb_extra.msg for k,v in pairs(result.members) do local member_id = v.id if member_id ~= our_id then -- Group configuration removal data[tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) local groups = 'groups' if not data[tostring(groups)] then data[tostring(groups)] = nil save_data(_config.moderation.data, data) end data[tostring(groups)][tostring(msg.to.id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, 'Group has been removed') end end end --End Check Member local function show_group_settingsmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 0 end end local bots_protection = "Yes" if data[tostring(msg.to.id)]['settings']['lock_bots'] then bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots'] end local lock_link = "no" if data[tostring(msg.to.id)]['settings']['lock_link'] then lock_link = data[tostring(msg.to.id)]['settings']['lock_link'] end local lock_adds= "no" if data[tostring(msg.to.id)]['settings']['lock_adds'] then lock_adds = data[tostring(msg.to.id)]['settings']['lock_adds'] end local lock_eng = "no" if data[tostring(msg.to.id)]['settings']['lock_eng'] then lock_eng = data[tostring(msg.to.id)]['settings']['lock_eng'] end local lock_badw = "no" if data[tostring(msg.to.id)]['settings']['lock_badw'] then lock_badw = data[tostring(msg.to.id)]['settings']['lock_badw'] end local lock_tag = "no" if data[tostring(msg.to.id)]['settings']['lock_tag'] then lock_tag = data[tostring(msg.to.id)]['settings']['lock_tag'] end local lock_leave = "no" if data[tostring(msg.to.id)]['settings']['lock_leave'] then lock_leave = data[tostring(msg.to.id)]['settings']['lock_leave'] end local lock_sticker = "no" if data[tostring(msg.to.id)]['settings']['sticker'] then lock_tag = data[tostring(msg.to.id)]['settings']['sticker'] end local settings = data[tostring(target)]['settings'] local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group tag : "..lock_tag.."\nLock group member : "..settings.lock_member.."\nLock group english 🗣 : "..lock_eng.."\n Lock group leave : "..lock_leave.."\nLock group bad words : "..lock_badw.."\nLock group links : "..lock_link.."\nLock group join : "..lock_adds.."\nLock group sticker : "..lock_sticker.."\nflood sensitivity : "..NUM_MSG_MAX.."\nBot protection : "..bots_protection--"\nPublic: "..public return text end local function set_descriptionmod(msg, data, target, about) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'description' data[tostring(target)][data_cat] = about save_data(_config.moderation.data, data) return 'Set group description to:\n'..about end local function get_description(msg, data) local data_cat = 'description' if not data[tostring(msg.to.id)][data_cat] then return 'No description available.' end local about = data[tostring(msg.to.id)][data_cat] local about = string.gsub(msg.to.print_name, "_", " ")..':\n\n'..about return 'About '..about end local function lock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'yes' then return 'Arabic is already locked' else data[tostring(target)]['settings']['lock_arabic'] = 'yes' save_data(_config.moderation.data, data) return 'Arabic has been locked' end end local function unlock_group_arabic(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_arabic_lock = data[tostring(target)]['settings']['lock_arabic'] if group_arabic_lock == 'no' then return 'Arabic is already unlocked' else data[tostring(target)]['settings']['lock_arabic'] = 'no' save_data(_config.moderation.data, data) return 'Arabic has been unlocked' end end local function lock_group_link(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'link is already locked!' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'link has been locked!' end end local function lock_group_sticker(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_sticker_lock = data[tostring(target)]['settings']['sticker'] if group_sticker_lock == 'kick' then return 'Sticker protection is already enabled!' else data[tostring(target)]['settings']['sticker'] = 'kick' save_data(_config.moderation.data, data) return 'Sticker protection has been enabled!' end end local function unlock_group_sticker(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_sticker_lock = data[tostring(target)]['settings']['sticker'] if group_sticker_lock == 'ok' then return 'Sticker protection is already disabled!' else data[tostring(target)]['settings']['sticker'] = 'ok' save_data(_config.moderation.data, data) return 'Sticker protection has been disabled!' end end local function unlock_group_link(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'link is already unlocked!' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'link has been unlocked!' end end local function lock_group_link(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'yes' then return 'link is already locked!' else data[tostring(target)]['settings']['lock_link'] = 'yes' save_data(_config.moderation.data, data) return 'link has been locked!' end end local function unlock_group_link(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_link_lock = data[tostring(target)]['settings']['lock_link'] if group_link_lock == 'no' then return 'link is already unlocked!' else data[tostring(target)]['settings']['lock_link'] = 'no' save_data(_config.moderation.data, data) return 'link has been unlocked!' end end local function lock_group_eng(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_eng_lock = data[tostring(target)]['settings']['lock_eng'] if group_eng_lock == 'yes' then return 'english is already locked!' else data[tostring(target)]['settings']['lock_eng'] = 'yes' save_data(_config.moderation.data, data) return 'english has been locked!' end end local function unlock_group_eng(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_eng_lock = data[tostring(target)]['settings']['lock_eng'] if group_eng_lock == 'no' then return 'english is already unlocked!' else data[tostring(target)]['settings']['lock_eng'] = 'no' save_data(_config.moderation.data, data) return 'english has been unlocked!' end end local function lock_group_eng(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_eng_lock = data[tostring(target)]['settings']['lock_eng'] if group_eng_lock == 'yes' then return 'english is already locked!' else data[tostring(target)]['settings']['lock_eng'] = 'yes' save_data(_config.moderation.data, data) return 'english has been locked!' end end local function unlock_group_eng(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_eng_lock = data[tostring(target)]['settings']['lock_eng'] if group_eng_lock == 'no' then return 'english is already unlocked!' else data[tostring(target)]['settings']['lock_eng'] = 'no' save_data(_config.moderation.data, data) return 'english has been unlocked!' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['lock_tag'] if group_tag_lock == 'yes' then return '# is already locked!' else data[tostring(target)]['settings']['lock_tag'] = 'yes' save_data(_config.moderation.data, data) return '# has been locked!' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['lock_tag'] if group_tag_lock == 'no' then return '# is already unlocked!' else data[tostring(target)]['settings']['lock_tag'] = 'no' save_data(_config.moderation.data, data) return '# has been unlocked!' end end local function lock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['lock_tag'] if group_tag_lock == 'yes' then return '# is already locked!' else data[tostring(target)]['settings']['lock_tag'] = 'yes' save_data(_config.moderation.data, data) return '# has been locked!' end end local function unlock_group_tag(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_tag_lock = data[tostring(target)]['settings']['lock_tag'] if group_tag_lock == 'no' then return '# is already unlocked!' else data[tostring(target)]['settings']['lock_tag'] = 'no' save_data(_config.moderation.data, data) return '# has been unlocked!' end end local function lock_group_badw(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'yes' then return 'bad words is already locked!' else data[tostring(target)]['settings']['lock_badw'] = 'yes' save_data(_config.moderation.data, data) return 'bad words has been locked!' end end local function unlock_group_badw(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'no' then return 'bad words is already unlocked!' else data[tostring(target)]['settings']['lock_badw'] = 'no' save_data(_config.moderation.data, data) return 'bad words has been unlocked!' end end local function lock_group_badw(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'yes' then return 'bad words is already locked!' else data[tostring(target)]['settings']['lock_badw'] = 'yes' save_data(_config.moderation.data, data) return 'bad words has been locked!' end end local function unlock_group_badw(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_badw_lock = data[tostring(target)]['settings']['lock_badw'] if group_badw_lock == 'no' then return 'bad words is already unlocked!' else data[tostring(target)]['settings']['lock_badw'] = 'no' save_data(_config.moderation.data, data) return 'bad words has been unlocked!' end end local function lock_group_adds(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local adds_ban = data[tostring(msg.to.id)]['settings']['adds_ban'] if adds_ban == 'yes' then return 'join by link has been locked!' else data[tostring(msg.to.id)]['settings']['adds_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'join by link is already locked!' end local function unlock_group_adds(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local adds_ban = data[tostring(msg.to.id)]['settings']['adds_ban'] if adds_ban == 'no' then return 'join by link hes been unlocked!' else data[tostring(msg.to.id)]['settings']['adds_ban'] = 'no' save_data(_config.moderation.data, data) return 'join by link is already unlocked!' end end local function lock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'yes' then return 'Leaving users will be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'yes' save_data(_config.moderation.data, data) end return 'Leaving users will be banned' end local function unlock_group_leave(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local leave_ban = data[tostring(msg.to.id)]['settings']['leave_ban'] if leave_ban == 'no' then return 'Leaving users will not be banned' else data[tostring(msg.to.id)]['settings']['leave_ban'] = 'no' save_data(_config.moderation.data, data) return 'Leaving users will not be banned' end end local function lock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'yes' then return 'Bots protection is already enabled' else data[tostring(target)]['settings']['lock_bots'] = 'yes' save_data(_config.moderation.data, data) return 'Bots protection has been enabled' end end local function unlock_group_bots(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_bots_lock = data[tostring(target)]['settings']['lock_bots'] if group_bots_lock == 'no' then return 'Bots protection is already disabled' else data[tostring(target)]['settings']['lock_bots'] = 'no' save_data(_config.moderation.data, data) return 'Bots protection has been disabled' end end local function lock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'yes' then return 'Group name is already locked' else data[tostring(target)]['settings']['lock_name'] = 'yes' save_data(_config.moderation.data, data) rename_chat('chat#id'..target, group_name_set, ok_cb, false) return 'Group name has been locked' end end local function unlock_group_namemod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_name_set = data[tostring(target)]['settings']['set_name'] local group_name_lock = data[tostring(target)]['settings']['lock_name'] if group_name_lock == 'no' then return 'Group name is already unlocked' else data[tostring(target)]['settings']['lock_name'] = 'no' save_data(_config.moderation.data, data) return 'Group name has been unlocked' end end local function lock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'yes' then return 'Group flood is locked' else data[tostring(target)]['settings']['flood'] = 'yes' save_data(_config.moderation.data, data) return 'Group flood has been locked' end end local function unlock_group_floodmod(msg, data, target) if not is_owner(msg) then return "Only admins can do it for now" end local group_flood_lock = data[tostring(target)]['settings']['flood'] if group_flood_lock == 'no' then return 'Group flood is not locked' else data[tostring(target)]['settings']['flood'] = 'no' save_data(_config.moderation.data, data) return 'Group flood has been unlocked' end end local function lock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'yes' then return 'Group members are already locked' else data[tostring(target)]['settings']['lock_member'] = 'yes' save_data(_config.moderation.data, data) end return 'Group members has been locked' end local function unlock_group_membermod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_member_lock = data[tostring(target)]['settings']['lock_member'] if group_member_lock == 'no' then return 'Group members are not locked' else data[tostring(target)]['settings']['lock_member'] = 'no' save_data(_config.moderation.data, data) return 'Group members has been unlocked' end end local function unlock_group_photomod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local group_photo_lock = data[tostring(target)]['settings']['lock_photo'] if group_photo_lock == 'no' then return 'Group photo is not locked' else data[tostring(target)]['settings']['lock_photo'] = 'no' save_data(_config.moderation.data, data) return 'Group photo has been unlocked' end end local function set_rulesmod(msg, data, target) if not is_momod(msg) then return "For moderators only!" end local data_cat = 'rules' data[tostring(target)][data_cat] = rules save_data(_config.moderation.data, data) return 'Set group rules to:\n'..rules end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function modadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_group(msg) then return 'Group is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modadd,{receiver=receiver, data=data, msg = msg}) end local function realmadd(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if is_realm(msg) then return 'Realm is already added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realm_add,{receiver=receiver, data=data, msg = msg}) end -- Global functions function modrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_group(msg) then return 'Group is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_modrem,{receiver=receiver, data=data, msg = msg}) end function realmrem(msg) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then return "You're not admin" end local data = load_data(_config.moderation.data) if not is_realm(msg) then return 'Realm is not added.' end receiver = get_receiver(msg) chat_info(receiver, check_member_realmrem,{receiver=receiver, data=data, msg = msg}) end local function get_rules(msg, data) local data_cat = 'rules' if not data[tostring(msg.to.id)][data_cat] then return 'No rules available.' end local rules = data[tostring(msg.to.id)][data_cat] local rules = 'Chat rules:\n'..rules return rules end local function set_group_photo(msg, success, result) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) if success then local file = 'data/photos/chat_photo_'..msg.to.id..'.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) chat_set_photo (receiver, file, ok_cb, false) data[tostring(msg.to.id)]['settings']['set_photo'] = file save_data(_config.moderation.data, data) data[tostring(msg.to.id)]['settings']['lock_photo'] = 'yes' save_data(_config.moderation.data, data) send_large_msg(receiver, 'Photo saved!', ok_cb, false) else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function promote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is already a moderator.') end data[group]['moderators'][tostring(member_id)] = member_username save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been promoted.') end local function promote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'.. msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return promote(get_receiver(msg), member_username, member_id) end end local function demote(receiver, member_username, member_id) local data = load_data(_config.moderation.data) local group = string.gsub(receiver, 'chat#id', '') if not data[group] then return send_large_msg(receiver, 'Group is not added.') end if not data[group]['moderators'][tostring(member_id)] then return send_large_msg(receiver, member_username..' is not a moderator.') end data[group]['moderators'][tostring(member_id)] = nil save_data(_config.moderation.data, data) return send_large_msg(receiver, member_username..' has been demoted.') end local function demote_by_reply(extra, success, result) local msg = result local full_name = (msg.from.first_name or '')..' '..(msg.from.last_name or '') if msg.from.username then member_username = '@'..msg.from.username else member_username = full_name end local member_id = msg.from.id if msg.to.type == 'chat' then return demote(get_receiver(msg), member_username, member_id) end end local function setowner_by_reply(extra, success, result) local msg = result local receiver = get_receiver(msg) local data = load_data(_config.moderation.data) local name_log = msg.from.print_name:gsub("_", " ") data[tostring(msg.to.id)]['set_owner'] = tostring(msg.from.id) save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] setted ["..msg.from.id.."] as owner") local text = msg.from.print_name:gsub("_", " ").." is the owner now" return send_large_msg(receiver, text) end local function promote_demote_res(extra, success, result) --vardump(result) --vardump(extra) local member_id = result.id local member_username = "@"..result.username local chat_id = extra.chat_id local mod_cmd = extra.mod_cmd local receiver = "chat#id"..chat_id if mod_cmd == 'promote' then return promote(receiver, member_username, member_id) elseif mod_cmd == 'demote' then return demote(receiver, member_username, member_id) end end local function modlist(msg) local data = load_data(_config.moderation.data) local groups = "groups" if not data[tostring(groups)][tostring(msg.to.id)] then return 'Group is not added.' end -- determine if table is empty if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local i = 1 local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do message = message ..i..' - '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function callbackres(extra, success, result) --vardump(result) local user = result.id local name = string.gsub(result.print_name, "_", " ") local chat = 'chat#id'..extra.chatid send_large_msg(chat, user..'\n'..name) return user end local function help() local help_text = tostring(_config.help_text) return help_text end local function cleanmember(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user(v.id, result.id) end end local function killchat(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function killrealm(cb_extra, success, result) local receiver = cb_extra.receiver local chat_id = "chat#id"..result.id local chatname = result.print_name for k,v in pairs(result.members) do kick_user_any(v.id, result.id) end end local function user_msgs(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 = tonumber(redis:get(um_hash) or 0) return user_info end local function kick_zero(cb_extra, success, result) local chat_id = cb_extra.chat_id local chat = "chat#id"..chat_id local ci_user local re_user for k,v in pairs(result.members) do local si = false ci_user = v.id local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) for i = 1, #users do re_user = users[i] if tonumber(ci_user) == tonumber(re_user) then si = true end end if not si then if ci_user ~= our_id then if not is_momod2(ci_user, chat_id) then chat_del_user(chat, 'user#id'..ci_user, ok_cb, true) end end end end end local function kick_inactive(chat_id, num, receiver) local hash = 'chat:'..chat_id..':users' local users = redis:smembers(hash) -- Get user info for i = 1, #users do local user_id = users[i] local user_info = user_msgs(user_id, chat_id) local nmsg = user_info if tonumber(nmsg) < tonumber(num) then if not is_momod2(user_id, chat_id) then chat_del_user('chat#id'..chat_id, 'user#id'..user_id, ok_cb, true) end end end return chat_info(receiver, kick_zero, {chat_id = chat_id}) end local function run(msg, matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local name_log = user_print_name(msg.from) local group = msg.to.id if msg.media then if msg.media.type == 'photo' and data[tostring(msg.to.id)]['settings']['set_photo'] == 'waiting' and is_chat_msg(msg) and is_momod(msg) then load_photo(msg.id, set_group_photo, msg) end end if matches[1] == 'add' and not matches[2] then if is_realm(msg) then return 'Error: Already a realm.' end print("group "..msg.to.print_name.."("..msg.to.id..") added") return modadd(msg) end if matches[1] == 'add' and matches[2] == 'realm' then if is_group(msg) then return 'Error: Already a group.' end print("group "..msg.to.print_name.."("..msg.to.id..") added as a realm") return realmadd(msg) end if matches[1] == 'rem' and not matches[2] then print("group "..msg.to.print_name.."("..msg.to.id..") removed") return modrem(msg) end if matches[1] == 'rem' and matches[2] == 'realm' then print("group "..msg.to.print_name.."("..msg.to.id..") removed as a realm") return realmrem(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "group" then return automodadd(msg) end if matches[1] == 'chat_created' and msg.from.id == 0 and group_type == "realm" then return autorealmadd(msg) end if msg.to.id and data[tostring(msg.to.id)] then local settings = data[tostring(msg.to.id)]['settings'] if matches[1] == 'chat_add_user' then if not msg.service then return "Are you trying to troll me?" end local group_member_lock = settings.lock_member local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id if group_member_lock == 'yes' and not is_owner2(msg.action.user.id, msg.to.id) then chat_del_user(chat, user, ok_cb, true) elseif group_member_lock == 'yes' and tonumber(msg.from.id) == tonumber(our_id) then return nil elseif group_member_lock == 'no' then return nil end end if matches[1] == 'chat_del_user' then if not msg.service then -- return "Are you trying to troll me?" end local user = 'user#id'..msg.action.user.id local chat = 'chat#id'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] deleted user "..user) end if matches[1] == 'chat_delete_photo' then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to deleted picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_change_photo' and msg.from.id ~= 0 then if not msg.service then return "Are you trying to troll me?" end local group_photo_lock = settings.lock_photo if group_photo_lock == 'yes' then local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:incr(picturehash) --- local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id local picprotectionredis = redis:get(picturehash) if picprotectionredis then if tonumber(picprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(picprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local picturehash = 'picture:changed:'..msg.to.id..':'..msg.from.id redis:set(picturehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change picture but failed ") chat_set_photo(receiver, settings.set_photo, ok_cb, false) elseif group_photo_lock == 'no' then return nil end end if matches[1] == 'chat_rename' then if not msg.service then return "Are you trying to troll me?" end local group_name_set = settings.set_name local group_name_lock = settings.lock_name local to_rename = 'chat#id'..msg.to.id if group_name_lock == 'yes' then if group_name_set ~= tostring(msg.to.print_name) then local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:incr(namehash) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id local nameprotectionredis = redis:get(namehash) if nameprotectionredis then if tonumber(nameprotectionredis) == 4 and not is_owner(msg) then kick_user(msg.from.id, msg.to.id) end if tonumber(nameprotectionredis) == 8 and not is_owner(msg) then ban_user(msg.from.id, msg.to.id) local namehash = 'name:changed:'..msg.to.id..':'..msg.from.id redis:set(namehash, 0) end end savelog(msg.to.id, name_log.." ["..msg.from.id.."] tried to change name but failed ") rename_chat(to_rename, group_name_set, ok_cb, false) end elseif group_name_lock == 'no' then return nil end end if matches[1] == 'setname' and is_momod(msg) then local new_name = string.gsub(matches[2], '_', ' ') data[tostring(msg.to.id)]['settings']['set_name'] = new_name save_data(_config.moderation.data, data) local group_name_set = data[tostring(msg.to.id)]['settings']['set_name'] local to_rename = 'chat#id'..msg.to.id rename_chat(to_rename, group_name_set, ok_cb, false) savelog(msg.to.id, "Group { "..msg.to.print_name.." } name changed to [ "..new_name.." ] by "..name_log.." ["..msg.from.id.."]") end if matches[1] == 'setphoto' and is_momod(msg) then data[tostring(msg.to.id)]['settings']['set_photo'] = 'waiting' save_data(_config.moderation.data, data) return 'Please send me new group photo now' end if matches[1] == 'promote' and not matches[2] then if not is_owner(msg) then return "Only the owner can prmote new moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, promote_by_reply, false) end end if matches[1] == 'promote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can promote" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] promoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'promote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'demote' and not matches[2] then if not is_owner(msg) then return "Only the owner can demote moderators" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, demote_by_reply, false) end end if matches[1] == 'demote' and matches[2] then if not is_momod(msg) then return end if not is_owner(msg) then return "Only owner can demote" end if string.gsub(matches[2], "@", "") == msg.from.username and not is_owner(msg) then return "You can't demote yourself" end local member = matches[2] savelog(msg.to.id, name_log.." ["..msg.from.id.."] demoted @".. member) local cbres_extra = { chat_id = msg.to.id, mod_cmd = 'demote', from_id = msg.from.id } local username = matches[2] local username = string.gsub(matches[2], '@', '') return res_user(username, promote_demote_res, cbres_extra) end if matches[1] == 'modlist' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group modlist") return modlist(msg) end if matches[1] == 'about' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group description") return get_description(msg, data) end if matches[1] == 'rules' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group rules") return get_rules(msg, data) end if matches[1] == 'set' then if matches[2] == 'rules' then rules = matches[3] local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]") return set_rulesmod(msg, data, target) end if matches[2] == 'about' then local data = load_data(_config.moderation.data) local target = msg.to.id local about = matches[3] savelog(msg.to.id, name_log.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]") return set_descriptionmod(msg, data, target, about) end end if matches[1] == 'lock' or matches[1] == 'l' then local target = msg.to.id if matches[2] == 'sticker' or matches[2] == 's' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked sticker ") return lock_group_sticker(msg, data, target) end if matches[2] == 'name' or matches[2] == 'n' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked name ") return lock_group_namemod(msg, data, target) end if matches[2] == 'member' or matches[2] == 'm' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked member ") return lock_group_membermod(msg, data, target) end if matches[2] == 'flood' or matches[2] == 'f' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked flood ") return lock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked arabic ") return lock_group_arabic(msg, data, target) end if matches[2] == 'adds' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked link ") return lock_group_link(msg, data, target) end if matches[2] == 'eng' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked eng ") return lock_group_eng(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked tag ") return lock_group_tag(msg, data, target) end if matches[2] == 'badw' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked badw ") return lock_group_badw(msg, data, target) end if matches[2] == 'join' or matches[2] == 'j' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked adds ") return lock_group_adds(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked leaving ") return lock_group_leave(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] locked bots ") return lock_group_bots(msg, data, target) end end if matches[1] == 'unlock' or matches[1] == 'u' then local target = msg.to.id if matches[2] == 'sticker' or matches[2] == 's' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked sticker ") return unlock_group_sticker(msg, data, target) end if matches[2] == 'name' or matches[2] == 'n' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked name ") return unlock_group_namemod(msg, data, target) end if matches[2] == 'member' or matches[2] == 'm' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked member ") return unlock_group_membermod(msg, data, target) end if matches[2] == 'photo' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked photo ") return unlock_group_photomod(msg, data, target) end if matches[2] == 'flood' or matches[2] == 'f' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked flood ") return unlock_group_floodmod(msg, data, target) end if matches[2] == 'arabic' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked arabic ") return unlock_group_arabic(msg, data, target) end if matches[2] == 'adds' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked link ") return unlock_group_link(msg, data, target) end if matches[2] == 'eng' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked eng ") return unlock_group_eng(msg, data, target) end if matches[2] == 'tag' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked tag ") return unlock_group_tag(msg, data, target) end if matches[2] == 'badw' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked badw ") return unlock_group_badw(msg, data, target) end if matches[2] == 'join' or matches[2] == 'j' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked adds ") return unlock_group_adds(msg, data, target) end if matches[2] == 'leave' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked leaving ") return unlock_group_leave(msg, data, target) end if matches[2] == 'bots' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] unlocked bots ") return unlock_group_bots(msg, data, target) end end if matches[1] == 'settings' then local target = msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group settings ") return show_group_settingsmod(msg, data, target) end --[[if matches[1] == 'public' then local target = msg.to.id if matches[2] == 'yes' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: public") return set_public_membermod(msg, data, target) end if matches[2] == 'no' then savelog(msg.to.id, name_log.." ["..msg.from.id.."] set group to: not public") return unset_public_membermod(msg, data, target) end end]] if matches[1] == 'newlink' and not is_realm(msg) then if not is_momod(msg) then return "For moderators only!" end local function callback (extra , success, result) local receiver = 'chat#'..msg.to.id if success == 0 then return send_large_msg(receiver, '*Error: Invite link failed* \nReason: Not creator.') end send_large_msg(receiver, "Created a new link") data[tostring(msg.to.id)]['settings']['set_link'] = result save_data(_config.moderation.data, data) end local receiver = 'chat#'..msg.to.id savelog(msg.to.id, name_log.." ["..msg.from.id.."] revoked group link ") return export_chat_link(receiver, callback, true) end if matches[1] == 'link' then if not is_momod(msg) then return "For moderators only!" end local group_link = data[tostring(msg.to.id)]['settings']['set_link'] if not group_link then return "Create a link using /newlink first !" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] requested group link ["..group_link.."]") return "Group link for ("..string.gsub(msg.to.print_name, "_", " ")..":\n"..group_link end if matches[1] == 'setowner' and matches[2] then if not is_owner(msg) then return "For owner only!" end data[tostring(msg.to.id)]['set_owner'] = matches[2] save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set ["..matches[2].."] as owner") local text = matches[2].." added as owner" return text end if matches[1] == 'setowner' and not matches[2] then if not is_owner(msg) then return "only for the owner!" end if type(msg.reply_id)~="nil" then msgr = get_message(msg.reply_id, setowner_by_reply, false) end end if matches[1] == 'mega' and matches[2] == 'satan' then return "W_SaTaN_W \n Advanced Bot Base On Seed\n@WilSoN_DeVeLoPeR[DeVeLoPeR] \n#Open_Source\n\n[@W_SaTaN](Https://telegra.me/W_SaTaN_W)" end if matches[1] == 'megasatan' then return "W_SaTaN_W \n Advanced Bot Base On Seed\n@WilSoN_DeVeLoPeR[DeVeLoPeR] \n#Open_Source\n\n[@W_SaTaN](Https://telegra.me/W_SaTaN_W)" end if matches[1] == 'owner' then local group_owner = data[tostring(msg.to.id)]['set_owner'] if not group_owner then return "no owner,ask admins in support groups to set owner for your group" end savelog(msg.to.id, name_log.." ["..msg.from.id.."] used /owner") return "Group owner is ["..group_owner..']' end if matches[1] == 'setgpowner' then local receiver = "chat#id"..matches[2] if not is_admin(msg) then return "For admins only!" end data[tostring(matches[2])]['set_owner'] = matches[3] save_data(_config.moderation.data, data) local text = matches[3].." added as owner" send_large_msg(receiver, text) return end if matches[1] == 'setflood' then if not is_momod(msg) then return "For moderators only!" end if tonumber(matches[2]) < 2 or tonumber(matches[2]) > 85 then return "Wrong number,range is [2-85]" end local flood_max = matches[2] data[tostring(msg.to.id)]['settings']['flood_msg_max'] = flood_max save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] set flood to ["..matches[2].."]") return 'Group flood has been set to '..matches[2] end if matches[1] == 'clean' then if not is_owner(msg) then return "Only owner can clean" end if matches[2] == 'member' then if not is_owner(msg) then return "Only admins can clean members" end local receiver = get_receiver(msg) chat_info(receiver, cleanmember, {receiver=receiver}) end if matches[2] == 'modlist' then if next(data[tostring(msg.to.id)]['moderators']) == nil then --fix way return 'No moderator in this group.' end local message = '\nList of moderators for ' .. string.gsub(msg.to.print_name, '_', ' ') .. ':\n' for k,v in pairs(data[tostring(msg.to.id)]['moderators']) do data[tostring(msg.to.id)]['moderators'][tostring(k)] = nil save_data(_config.moderation.data, data) end savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned modlist") end if matches[2] == 'rules' then local data_cat = 'rules' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned rules") end if matches[2] == 'about' then local data_cat = 'description' data[tostring(msg.to.id)][data_cat] = nil save_data(_config.moderation.data, data) savelog(msg.to.id, name_log.." ["..msg.from.id.."] cleaned about") end end if matches[1] == 'kill' and matches[2] == 'chat' then if not is_admin(msg) then return nil end if not is_realm(msg) then local receiver = get_receiver(msg) return modrem(msg), print("Closing Group..."), chat_info(receiver, killchat, {receiver=receiver}) else return 'This is a realm' end end if matches[1] == 'kill' and matches[2] == 'realm' then if not is_admin(msg) then return nil end if not is_group(msg) then local receiver = get_receiver(msg) return realmrem(msg), print("Closing Realm..."), chat_info(receiver, killrealm, {receiver=receiver}) else return 'This is a group' end end if matches[1] == 'help' then if not is_momod(msg) or is_realm(msg) then return end savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /help") return help() end if matches[1] == 'res' and is_momod(msg) then local cbres_extra = { chatid = msg.to.id } local username = matches[2] local username = username:gsub("@","") savelog(msg.to.id, name_log.." ["..msg.from.id.."] Used /res "..username) return res_user(username, callbackres, cbres_extra) end if matches[1] == 'kickinactive' then --send_large_msg('chat#id'..msg.to.id, 'I\'m in matches[1]') if not is_momod(msg) then return 'Only a moderator can kick inactive users' end local num = 1 if matches[2] then num = matches[2] end local chat_id = msg.to.id local receiver = get_receiver(msg) return kick_inactive(chat_id, num, receiver) end end end return { patterns = { "^[!/](add)$", "^[!/](add) (realm)$", "^[!/](rem)$", "^[!/](rem) (realm)$", "^[!/](rules)$", "^[!/](about)$", "^[!/](setname) (.*)$", "^[!/](setphoto)$", "^[!/](promote) (.*)$", "^[!/](promote)", "^[!/](help)$", "^[!/](clean) (.*)$", "^[!/](kill) (chat)$", "^[!/](kill) (realm)$", "^[!/](demote) (.*)$", "^[!/](demote)", "^[!/](set) ([^%s]+) (.*)$", "^[!/](lock) (.*)$", "^[!/](setowner) (%d+)$", "^[!/](setowner)", "^[!/](owner)$", "^[!/](res) (.*)$", "^[!/](setgpowner) (%d+) (%d+)$",-- (group id) (owner id) "^[!/](unlock) (.*)$", "^[!/](setflood) (%d+)$", "^[!/](settings)$", -- "^[!/](public) (.*)$", "^[!/](modlist)$", "^[!/](newlink)$", "^[!/](link)$", "^[!/](kickinactive)$", "^[!/](kickinactive) (%d+)$", "%[(photo)%]", "^!!tgservice (.+)$", }, run = run } end
gpl-2.0
kengonakajima/luvit-mysql
query.lua
2
4271
--[[ Copyright 2012 Kengo Nakajima. All Rights Reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS-IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. --]] local Parser = require("./parser") local Util = require("./util") local Constants = require("./constants") local table = require("table") local math = require("math") -- OK,RESULT_SET_HEADER, FIELD, EOF, ROW_DATA, ROW_DATA,EOF : 1,3,4,5,6,6,5, Query={} function Query:new(conf) local q = { sql = conf.sql, typeCast = conf.typeCast, log = conf.logfunc } q.callbacks = {} function q:on( evname, fn ) self.callbacks[evname] = fn end function q:emit( evname, a,b ) local cb = self.callbacks[evname] self.log("Query:emitting event. name:",evname, "func:", cb ) if cb then cb(a,b) end end function q:handlePacket(packet) self.log( "query.handlePacket called. type:", packet.type ) if packet.type == Constants.OK_PACKET then self:emit("end", Util.packetToUserObject(packet) ) elseif packet.type == Constants.ERROR_PACKET then packet.sql = self.sql self:emit( "error", Util.packetToUserObject(packet)) elseif packet.type == Constants.FIELD_PACKET then if not self.fields then self.fields = {} end table.insert( self.fields, packet) self:emit( "field", packet ) elseif packet.type == Constants.EOF_PACKET then if not self.eofs then self.eofs = 1 else self.eofs = self.eofs + 1 end if self.eofs == 2 then self:emit( "end", nil, self.rows, self.fields ) end elseif packet.type == Constants.ROW_DATA_PACKET then self.row = {} self.rowIndex = 1 -- it's lua! self.field = nil packet:on("data", function(buffer,remaining) self.log("query row_data_packet receives data. buffer:", buffer, "remaining:", remaining, "nfields:", #self.fields, "ri:", self.rowIndex, "f:", self.field ) if not self.field then self.field = self.fields[ self.rowIndex ] self.row[ self.field.name ] = "" end if buffer then self.row[ self.field.name ] = self.row[ self.field.name ] .. buffer else self.row[ self.field.name ] = nil end if remaining and remaining > 0 then return end self.rowIndex = self.rowIndex + 1 if self.typeCast and buffer then if self.field.fieldType == Constants.FIELD_TYPE_TIMESTAMP or self.field.fieldType == Constants.FIELD_TYPE_DATE or self.field.fieldType == Constants.FIELD_TYPE_DATETIME or self.field.fieldType == Constants.FIELD_TYPE_NEWDATE then self.row[self.field.name] = Util.convertStringDateToTable( self.row[self.field.name] ) elseif self.field.fieldType == Constants.FIELD_TYPE_TINY or self.field.fieldType == Constants.FIELD_TYPE_SHORT or self.field.fieldType == Constants.FIELD_TYPE_LONG or self.field.fieldType == Constants.FIELD_TYPE_LONGLONG or self.field.fieldType == Constants.FIELD_TYPE_INT24 or self.field.fieldType == Constants.FIELD_TYPE_YEAR then self.row[self.field.name] = math.floor(tonumber( self.row[self.field.name], 10) ) elseif self.field.fieldType == Constants.FIELD_TYPE_FLOAT or self.field.fieldType == Constants.FIELD_TYPE_DOUBLE then -- decimal types cannot be parsed as floats because -- V8 Numbers have less precision than some MySQL Decimals (lua too) self.row[self.field.name] = tonumber( self.row[self.field.name] ) end end if self.rowIndex == (#self.fields+1) then self:emit( "row", self.row ) return end self.field = nil end) end end return q end return Query
apache-2.0
ctozlm/Dato-Core
src/unity/python/graphlab/lua/pl/MultiMap.lua
36
1458
--- MultiMap, a Map which has multiple values per key. -- -- Dependencies: `pl.utils`, `pl.class`, `pl.tablex`, `pl.List` -- @classmod pl.MultiMap local classes = require 'pl.class' local tablex = require 'pl.tablex' local utils = require 'pl.utils' local List = require 'pl.List' local index_by,tsort,concat = tablex.index_by,table.sort,table.concat local append,extend,slice = List.append,List.extend,List.slice local append = table.insert local class = require 'pl.class' local Map = require 'pl.Map' -- MultiMap is a standard MT local MultiMap = utils.stdmt.MultiMap class(Map,nil,MultiMap) MultiMap._name = 'MultiMap' function MultiMap:_init (t) if not t then return end self:update(t) end --- update a MultiMap using a table. -- @param t either a Multimap or a map-like table. -- @return the map function MultiMap:update (t) utils.assert_arg(1,t,'table') if Map:class_of(t) then for k,v in pairs(t) do self[k] = List() self[k]:append(v) end else for k,v in pairs(t) do self[k] = List(v) end end end --- add a new value to a key. Setting a nil value removes the key. -- @param key the key -- @param val the value -- @return the map function MultiMap:set (key,val) if val == nil then self[key] = nil else if not self[key] then self[key] = List() end self[key]:append(val) end end return MultiMap
agpl-3.0
siggame/Joueur.lua
games/spiders/player.lua
1
3213
-- Player: A player in this game. Every AI controls one player. -- DO NOT MODIFY THIS FILE -- Never try to directly create an instance of this class, or modify its member variables. -- Instead, you should only be reading its variables and calling its functions. local class = require("joueur.utilities.class") local GameObject = require("games.spiders.gameObject") -- <<-- Creer-Merge: requires -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- you can add additional require(s) here -- <<-- /Creer-Merge: requires -->> --- A player in this game. Every AI controls one player. -- @classmod Player local Player = class(GameObject) -- initializes a Player with basic logic as provided by the Creer code generator function Player:init(...) GameObject.init(self, ...) -- The following values should get overridden when delta states are merged, but we set them here as a reference for you to see what variables this class has. --- This player's BroodMother. If it dies they lose the game. self.broodMother = nil --- What type of client this is, e.g. 'Python', 'JavaScript', or some other language. For potential data mining purposes. self.clientType = "" --- If the player lost the game or not. self.lost = false --- The max number of Spiderlings players can spawn. self.maxSpiderlings = 0 --- The name of the player. self.name = "Anonymous" --- The number of nests this player controls. self.numberOfNestsControlled = 0 --- This player's opponent in the game. self.opponent = nil --- The reason why the player lost the game. self.reasonLost = "" --- The reason why the player won the game. self.reasonWon = "" --- All the Spiders owned by this player. self.spiders = Table() --- The amount of time (in ns) remaining for this AI to send commands. self.timeRemaining = 0 --- If the player won the game or not. self.won = false --- (inherited) String representing the top level Class that this game object is an instance of. Used for reflection to create new instances on clients, but exposed for convenience should AIs want this data. -- @field[string] self.gameObjectName -- @see GameObject.gameObjectName --- (inherited) A unique id for each instance of a GameObject or a sub class. Used for client and server communication. Should never change value after being set. -- @field[string] self.id -- @see GameObject.id --- (inherited) Any strings logged will be stored here. Intended for debugging. -- @field[{string, ...}] self.logs -- @see GameObject.logs end --- (inherited) Adds a message to this GameObject's logs. Intended for your own debugging purposes, as strings stored here are saved in the gamelog. -- @function Player:log -- @see GameObject:log -- @tparam string message A string to add to this GameObject's log. Intended for debugging. -- <<-- Creer-Merge: functions -->> - Code you add between this comment and the end comment will be preserved between Creer re-runs. -- if you want to add any client side logic this is where you can add them -- <<-- /Creer-Merge: functions -->> return Player
mit
FizzerWL/ExampleMods
TanksMod/Server_AdvanceTurn.lua
1
2927
require('Utilities'); function Server_AdvanceTurn_Order(game, order, result, skipThisOrder, addNewOrder) if (order.proxyType == 'GameOrderCustom' and startsWith(order.Payload, 'BuyTank_')) then --look for the order that we inserted in Client_PresentCommercePurchaseUI --in Client_PresentMenuUI, we stuck the territory ID after BuyTank_. Break it out and parse it to a number. local targetTerritoryID = tonumber(string.sub(order.Payload, 9)); local targetTerritoryStanding = game.ServerGame.LatestTurnStanding.Territories[targetTerritoryID]; if (targetTerritoryStanding.OwnerPlayerID ~= order.PlayerID) then return; --can only buy a tank onto a territory you control end if (order.CostOpt == nil) then return; --shouldn't ever happen, unless another mod interferes end local costFromOrder = order.CostOpt[WL.ResourceType.Gold]; --this is the cost from the order. We can't trust this is accurate, as someone could hack their client and put whatever cost they want in there. Therefore, we must calculate it ourselves, and only do the purchase if they match local realCost = Mod.Settings.CostToBuyTank; if (realCost > costFromOrder) then return; --don't do the purchase if their cost didn't line up. This would only really happen if they hacked their client or another mod interfered end local numTanksAlreadyHave = 0; for _,ts in pairs(game.ServerGame.LatestTurnStanding.Territories) do if (ts.OwnerPlayerID == order.PlayerID) then numTanksAlreadyHave = numTanksAlreadyHave + NumTanksIn(ts.NumArmies); end end if (numTanksAlreadyHave >= Mod.Settings.MaxTanks) then addNewOrder(WL.GameOrderEvent.Create(order.PlayerID, 'Skipping tank purchase since max is ' .. Mod.Settings.MaxTanks .. ' and you have ' .. numTanksAlreadyHave)); return; --this player already has the maximum number of tanks possible, so skip adding a new one. end local tankPower = Mod.Settings.TankPower; local builder = WL.CustomSpecialUnitBuilder.Create(order.PlayerID); builder.Name = 'Tank'; builder.IncludeABeforeName = true; builder.ImageFilename = 'Tank.png'; builder.AttackPower = tankPower; builder.DefensePower = tankPower; builder.CombatOrder = 3415; --defends commanders builder.DamageToKill = tankPower; builder.DamageAbsorbedWhenAttacked = tankPower; builder.CanBeGiftedWithGiftCard = true; builder.CanBeTransferredToTeammate = true; builder.CanBeAirliftedToSelf = true; builder.CanBeAirliftedToTeammate = true; builder.IsVisibleToAllPlayers = false; local terrMod = WL.TerritoryModification.Create(targetTerritoryID); terrMod.AddSpecialUnits = {builder.Build()}; addNewOrder(WL.GameOrderEvent.Create(order.PlayerID, 'Purchased a tank', {}, {terrMod})); end end function NumTanksIn(armies) local ret = 0; for _,su in pairs(armies.SpecialUnits) do if (su.Name == 'Tank') then ret = ret + 1; end end return ret; end
mit
rhadamants/TowerScripts
TyrrWarrior.lua
1
11149
ShowToClient("Aviso","Ativando o Guerreiro Tyrr..."); Eu = GetMe(); ---------------------------------------------------------------------------------------------- ----Apresentação ---------------------------------------------------------------------------------------------- if(Eu:GetClass() == 140) then ShowToClient("Aviso","Eu sou seu Tyrr Warrior."); Sleep(500); elseif (Eu:GetClass() == 152) then ShowToClient("Aviso","Eu sou seu Tyrr Duelist."); Sleep(500); elseif (Eu:GetClass() == 153) then ShowToClient("Aviso","Eu sou seu Tyrr Dreadnought."); Sleep(500); elseif (Eu:GetClass() == 154) then ShowToClient("Aviso","Eu sou seu Tyrr Titan."); Sleep(500); elseif (Eu:GetClass() == 155) then ShowToClient("Aviso","Eu sou seu Tyrr Grand Khavatari."); Sleep(500); elseif (Eu:GetClass() == 156) then ShowToClient("Aviso","Eu sou seu Tyrr Maestro."); Sleep(500); elseif (Eu:GetClass() == 157) then ShowToClient("Aviso","Eu sou seu Tyrr Doombringer."); Sleep(500); end; ShowToClient("Aviso","Comecando as atividades do dia... ;)"); ---------------------------------------------------------------------------------------------- --FBC - Feral Bear Cry --FOC - Feral Ogre Cry --FPC - Feral Puma Cry --HC - Hawk Cry --FRC - Feral Rabbit Cry --CW - Cry of the Wolf --BST - Bison Spirit Toten --SS - Spirit of the Slayer --SH - Spitit of the Hunter ---------------------------------------------------------------------------------------------- Toten = "HC"; Spirit = "SS"; TipoAtk = "AOE"; -- S-> Single; AOE-> Area; function TBCry(tipos) local tipo = tipos; if(Eu:GetClass() == 155) then if (tipo == "FBC") then return 10291; elseif (tipo == "FOC") then return 10292; elseif (tipo == "FPC") then return 10293; elseif (tipo == "HC") then return 10295; elseif (tipo == "FRC") then return 10294; elseif (tipo == "CW") then return 10294; elseif (tipo == "BST") then return 10294; end; else if((tipo ~= "BST") or (tipo == "CW")) then if (tipo == "FBC") then return 10291; elseif (tipo == "FOC") then return 10292; elseif (tipo == "FPC") then return 10293; elseif (tipo == "HC") then return 10295; elseif (tipo == "FRC") then return 10294; end; else ShowToClient("Aviso","O Toten q foi solicitado pertence ao Tyrr Grand Khavatari..."); ShowToClient("Aviso","Trocando pelo 'Hawk Cry'. Boa Sorte"); return 10295; end; end; end; function TBSpirit(tipos) local tipo = tipos; if (tipo == "SS") then return 10297; elseif (tipo == "SH") then return 10296; end; end; function BaixadoHPSkill(skill) local tipo = skill; if (Eu:GetHpPercent() < 70) then return tipo; else return 0; end; end; function Distancia() return GetMe():GetRangeTo(GetTarget()); end; ---------------------------------------------------------------------------------------------- ----Reuso de Skills ---------------------------------------------------------------------------------------------- function ReusoSkills(IdSkill) --Ataques do Adventure local skill = IdSkill; if(GetSkills():FindById(skill):CanBeUsed()) then return skill; else return 0; end; end; ---------------------------------------------------------------------------------------------- ----Combo de skills ---------------------------------------------------------------------------------------------- function Combo() Alvo = GetTarget(); combo = { 10262, --PowerBomber 10266, --GiantPunch 10546, --Uppercut 11276, --DimensionalBinding 11050, --HellBinding 11051, --HellBinding2 11052, --MassHellBinding 11053 --MassHellBinding2 } for cb = 1, #combo do if(GetTarget() ~= nil) then if(GetTarget():GotBuff(combo[cb]) == true) then UseSkillRaw(10258, false, false); -- ArmorDestruction Sleep(500); end; end; end; end; ---------------------------------------------------------------------------------------------- ----Buffs por classe ---------------------------------------------------------------------------------------------- function TWBuffs() -- Tyrr Warrior if (Eu:GotBuff(1929) == false) then UseSkillRaw(1929, false, false); -- TyrrAura Sleep(500); end; if (Eu:GotBuff(1986) == false) then UseSkillRaw(1986, false, false); -- Dual Maximum HP Sleep(500); end; if (Eu:GotBuff(TBCry(Toten)) == false) then UseSkillRaw(ReusoSkills(TBCry(Toten)), false, false); -- Toten Sleep(500); end; if (Eu:GotBuff(TBSpirit(Spirit)) == false) then UseSkillRaw(ReusoSkills(TBSpirit(Spirit)), false, false); -- Spirit Sleep(500); end; if (Eu:GetLevel() >= 93) then if (Eu:GotBuff(10270) == false) then UseSkillRaw(ReusoSkills(10270), false, false); -- SecondWind Sleep(500); end; end; if (Eu:GotBuff(10276) == false) then UseSkillRaw(ReusoSkills(10276), false, false); -- ForceOfNature Sleep(500); end; if (Eu:GotBuff(1914) == false) then UseSkillRaw(ReusoSkills(1914), false, false); -- Savage Sleep(500); end; if (Eu:GotBuff(10289) == false) then UseSkillRaw(ReusoSkills(10289), false, false); -- Boost Sleep(500); end; end; function TDuelBuffs() -- Tyrr Duelist if (Eu:GotBuff(10274) == false) then UseSkillRaw(BaixadoHPSkill(ReusoSkills(10274)), false, false); -- Berserker Sleep(500); end; TWBuffs(); end; function TDoomBuffs() -- Tyrr Doombringer if (Eu:GotBuff(10274) == false) then UseSkillRaw(BaixadoHPSkill(ReusoSkills(10274)), false, false); -- Berserker Sleep(500); end; if (Eu:GetLevel() < 93) then if (Eu:GotBuff(20006) == false) then UseSkillRaw(ReusoSkills(20006), false, false); -- SoulRoar Sleep(500); end; end; TWBuffs(); end; function TGKhaBuffs() -- Tyrr Grand Khavatari if (Eu:GotBuff(10274) == false) then UseSkillRaw(BaixadoHPSkill(ReusoSkills(10274)), false, false); -- Berserker Sleep(500); end; TWBuffs(); end; function TTitaBuffs() -- Tyrr Titan TWBuffs(); end; function TMaesBuffs() -- Tyrr Maestro if (Eu:GotBuff(10274) == false) then UseSkillRaw(BaixadoHPSkill(ReusoSkills(10274)), false, false); -- Berserker Sleep(500); end; TWBuffs(); end; function TDreaBuffs() -- Tyrr Dreadnought if (Eu:GotBuff(10274) == false) then UseSkillRaw(BaixadoHPSkill(ReusoSkills(10274)), false, false); -- Berserker Sleep(500); end; TWBuffs(); end; function TyrrBuffs() if (Eu:GetClass() == 140) then -- Tyrr Warrior TWBuffs(); elseif (Eu:GetClass() == 152) then -- -- Tyrr Duelist TDuelBuffs(); elseif (Eu:GetClass() == 153) then -- Tyrr Dreadnought TDreaBuffs(); elseif (Eu:GetClass() == 154) then -- Tyrr Titan TTitaBuffs(); elseif (Eu:GetClass() == 155) then -- Tyrr Grand Khavatari TGKhaBuffs(); elseif (Eu:GetClass() == 156) then -- Tyrr Maestro TMaesBuffs(); elseif (Eu:GetClass() == 157) then -- Tyrr Doombringer TDoomBuffs(); end; end; ---------------------------------------------------------------------------------------------- ----Ataque por classe ---------------------------------------------------------------------------------------------- function Destruction() if(GetTarget() ~= nil) then if(GetTarget():GotBuff(10258) == false) then UseSkillRaw(ReusoSkills(10258), false, false); -- ArmorDestruction Sleep(500); end; end; end; function TWAtk() if(Distancia() > 200) then UseSkillRaw(ReusoSkills(10263), false, false); -- Hurricane Blaster Sleep(500); end; if(TipoAtk == "S") then if(Distancia() > 200) then UseSkillRaw(ReusoSkills(10267), false, false); -- Hurricane Rush Sleep(500); end; if(Distancia() > 200) then UseSkillRaw(ReusoSkills(10267), false, false); -- Hurricane Rush Sleep(500); end; Destruction(); UseSkillRaw(ReusoSkills(10260), false, false); -- MegaStrick Sleep(500); UseSkillRaw(ReusoSkills(10262), false, false); -- PowerBomber Sleep(500); UseSkillRaw(ReusoSkills(10273), false, false); -- LightningDisarm Sleep(500); elseif(TipoAtk == "AOE") then if(Distancia() > 200) then UseSkillRaw(ReusoSkills(10269), false, false); -- JumpAttack Sleep(500); end; if(Distancia() < 150) then Destruction(); UseSkillRaw(ReusoSkills(10265), false, false); -- Eruption Sleep(500); UseSkillRaw(ReusoSkills(10266), false, false); -- GiantPunch Sleep(500); UseSkillRaw(ReusoSkills(10262), false, false); -- PowerBomber Sleep(500); Combo(); UseSkillRaw(ReusoSkills(10288), false, false); -- HurricaneStorm Sleep(500); UseSkillRaw(ReusoSkills(10260), false, false); -- MegaStrick Sleep(500); UseSkillRaw(ReusoSkills(10273), false, false); -- LightningDisarm Sleep(7000); end; end; end; function TDuelAtk() TWAtk(); end; function TDreaAtk() TWAtk(); end; function TTitaAtk() TWAtk(); end; function TGKhaAtk() TWAtk(); end; function TMaesAtk() TWAtk(); end; function TDoomAtk() if(TipoAtk == "AOE") then if(Distancia() > 200) then UseSkillRaw(ReusoSkills(10263), false, false); -- Hurricane Blaster Sleep(500); end; if(Distancia() > 150) then UseSkillRaw(ReusoSkills(793), false, false); -- Rush Impact Sleep(500); end; else if(Distancia() > 200) then UseSkillRaw(ReusoSkills(10263), false, false); -- Hurricane Blaster Sleep(500); end; end; TWAtk(); end; function TyrrAtk() if (Eu:GetClass() == 140) then -- Tyrr Warrior TWAtk(); elseif (Eu:GetClass() == 152) then -- -- Tyrr Duelist TDuelAtk(); elseif (Eu:GetClass() == 153) then -- Tyrr Dreadnought TDreaAtk(); elseif (Eu:GetClass() == 154) then -- Tyrr Titan TTitaAtk(); elseif (Eu:GetClass() == 155) then -- Tyrr Grand Khavatari TGKhaAtk(); elseif (Eu:GetClass() == 156) then -- Tyrr Maestro TMaesAtk(); elseif (Eu:GetClass() == 157) then -- Tyrr Doombringer TDoomAtk(); end; end; ---------------------------------------------------------------------------------------------- ----Acao ---------------------------------------------------------------------------------------------- function Acao() TyrrBuffs(); Sleep(200); Combo(); TyrrAtk(); Sleep(200); Combo(); Destruction(); Command("/attack"); end; ----------------------------------------------------------------------------------------------------- ---função principal ----------------------------------------------------------------------------------------------------- function Main() --TyrrBuffs(); --usar skills de self buff ----------------------------------------------------------------------------------------------------- ---Regra de ataque ----------------------------------------------------------------------------------------------------- if (GetTarget() ~= nil) then if (GetTarget():IsMonster() == true) and (Eu:IsAlikeDeath() == false) and (GetTarget():IsAlikeDeath() == false) then Acao(); Sleep(100); Combo(); Command("/attack"); ClearTargets(); end; end; end; ----------------------------------------------------------------------------------------------------- ---execução do script ----------------------------------------------------------------------------------------------------- repeat if not CheckIfRunning or not IsPaused() then Main() end Sleep(100) until false
gpl-2.0
SeyedKia/alpha
libs/JSON.lua
3765
34843
-- -*- coding: utf-8 -*- -- -- Simple JSON encoding and decoding in pure Lua. -- -- Copyright 2010-2014 Jeffrey Friedl -- http://regex.info/blog/ -- -- Latest version: http://regex.info/blog/lua/json -- -- This code is released under a Creative Commons CC-BY "Attribution" License: -- http://creativecommons.org/licenses/by/3.0/deed.en_US -- -- It can be used for any purpose so long as the copyright notice above, -- the web-page links above, and the 'AUTHOR_NOTE' string below are -- maintained. Enjoy. -- local VERSION = 20141223.14 -- version history at end of file local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-" -- -- The 'AUTHOR_NOTE' variable exists so that information about the source -- of the package is maintained even in compiled versions. It's also -- included in OBJDEF below mostly to quiet warnings about unused variables. -- local OBJDEF = { VERSION = VERSION, AUTHOR_NOTE = AUTHOR_NOTE, } -- -- Simple JSON encoding and decoding in pure Lua. -- http://www.json.org/ -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- -- -- -- DECODING (from a JSON string to a Lua table) -- -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local lua_value = JSON:decode(raw_json_text) -- -- If the JSON text is for an object or an array, e.g. -- { "what": "books", "count": 3 } -- or -- [ "Larry", "Curly", "Moe" ] -- -- the result is a Lua table, e.g. -- { what = "books", count = 3 } -- or -- { "Larry", "Curly", "Moe" } -- -- -- The encode and decode routines accept an optional second argument, -- "etc", which is not used during encoding or decoding, but upon error -- is passed along to error handlers. It can be of any type (including nil). -- -- -- -- ERROR HANDLING -- -- With most errors during decoding, this code calls -- -- JSON:onDecodeError(message, text, location, etc) -- -- with a message about the error, and if known, the JSON text being -- parsed and the byte count where the problem was discovered. You can -- replace the default JSON:onDecodeError() with your own function. -- -- The default onDecodeError() merely augments the message with data -- about the text and the location if known (and if a second 'etc' -- argument had been provided to decode(), its value is tacked onto the -- message as well), and then calls JSON.assert(), which itself defaults -- to Lua's built-in assert(), and can also be overridden. -- -- For example, in an Adobe Lightroom plugin, you might use something like -- -- function JSON:onDecodeError(message, text, location, etc) -- LrErrors.throwUserError("Internal Error: invalid JSON data") -- end -- -- or even just -- -- function JSON.assert(message) -- LrErrors.throwUserError("Internal Error: " .. message) -- end -- -- If JSON:decode() is passed a nil, this is called instead: -- -- JSON:onDecodeOfNilError(message, nil, nil, etc) -- -- and if JSON:decode() is passed HTML instead of JSON, this is called: -- -- JSON:onDecodeOfHTMLError(message, text, nil, etc) -- -- The use of the fourth 'etc' argument allows stronger coordination -- between decoding and error reporting, especially when you provide your -- own error-handling routines. Continuing with the the Adobe Lightroom -- plugin example: -- -- function JSON:onDecodeError(message, text, location, etc) -- local note = "Internal Error: invalid JSON data" -- if type(etc) = 'table' and etc.photo then -- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName') -- end -- LrErrors.throwUserError(note) -- end -- -- : -- : -- -- for i, photo in ipairs(photosToProcess) do -- : -- : -- local data = JSON:decode(someJsonText, { photo = photo }) -- : -- : -- end -- -- -- -- -- -- DECODING AND STRICT TYPES -- -- Because both JSON objects and JSON arrays are converted to Lua tables, -- it's not normally possible to tell which original JSON type a -- particular Lua table was derived from, or guarantee decode-encode -- round-trip equivalency. -- -- However, if you enable strictTypes, e.g. -- -- JSON = assert(loadfile "JSON.lua")() --load the routines -- JSON.strictTypes = true -- -- then the Lua table resulting from the decoding of a JSON object or -- JSON array is marked via Lua metatable, so that when re-encoded with -- JSON:encode() it ends up as the appropriate JSON type. -- -- (This is not the default because other routines may not work well with -- tables that have a metatable set, for example, Lightroom API calls.) -- -- -- ENCODING (from a lua table to a JSON string) -- -- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines -- -- local raw_json_text = JSON:encode(lua_table_or_value) -- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability -- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false }) -- -- On error during encoding, this code calls: -- -- JSON:onEncodeError(message, etc) -- -- which you can override in your local JSON object. -- -- The 'etc' in the error call is the second argument to encode() -- and encode_pretty(), or nil if it wasn't provided. -- -- -- PRETTY-PRINTING -- -- An optional third argument, a table of options, allows a bit of -- configuration about how the encoding takes place: -- -- pretty = JSON:encode(val, etc, { -- pretty = true, -- if false, no other options matter -- indent = " ", -- this provides for a three-space indent per nesting level -- align_keys = false, -- see below -- }) -- -- encode() and encode_pretty() are identical except that encode_pretty() -- provides a default options table if none given in the call: -- -- { pretty = true, align_keys = false, indent = " " } -- -- For example, if -- -- JSON:encode(data) -- -- produces: -- -- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11} -- -- then -- -- JSON:encode_pretty(data) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- The following three lines return identical results: -- JSON:encode_pretty(data) -- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " }) -- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " }) -- -- An example of setting your own indent string: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " }) -- -- produces: -- -- { -- | "city": "Kyoto", -- | "climate": { -- | | "avg_temp": 16, -- | | "humidity": "high", -- | | "snowfall": "minimal" -- | }, -- | "country": "Japan", -- | "wards": 11 -- } -- -- An example of setting align_keys to true: -- -- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true }) -- -- produces: -- -- { -- "city": "Kyoto", -- "climate": { -- "avg_temp": 16, -- "humidity": "high", -- "snowfall": "minimal" -- }, -- "country": "Japan", -- "wards": 11 -- } -- -- which I must admit is kinda ugly, sorry. This was the default for -- encode_pretty() prior to version 20141223.14. -- -- -- AMBIGUOUS SITUATIONS DURING THE ENCODING -- -- During the encode, if a Lua table being encoded contains both string -- and numeric keys, it fits neither JSON's idea of an object, nor its -- idea of an array. To get around this, when any string key exists (or -- when non-positive numeric keys exist), numeric keys are converted to -- strings. -- -- For example, -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- produces the JSON object -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To prohibit this conversion and instead make it an error condition, set -- JSON.noKeyConversion = true -- -- -- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT -- -- assert -- onDecodeError -- onDecodeOfNilError -- onDecodeOfHTMLError -- onEncodeError -- -- If you want to create a separate Lua JSON object with its own error handlers, -- you can reload JSON.lua or use the :new() method. -- --------------------------------------------------------------------------- local default_pretty_indent = " " local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent } local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject function OBJDEF:newArray(tbl) return setmetatable(tbl or {}, isArray) end function OBJDEF:newObject(tbl) return setmetatable(tbl or {}, isObject) end local function unicode_codepoint_as_utf8(codepoint) -- -- codepoint is a number -- if codepoint <= 127 then return string.char(codepoint) elseif codepoint <= 2047 then -- -- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8 -- local highpart = math.floor(codepoint / 0x40) local lowpart = codepoint - (0x40 * highpart) return string.char(0xC0 + highpart, 0x80 + lowpart) elseif codepoint <= 65535 then -- -- 1110yyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x1000) local remainder = codepoint - 0x1000 * highpart local midpart = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midpart highpart = 0xE0 + highpart midpart = 0x80 + midpart lowpart = 0x80 + lowpart -- -- Check for an invalid character (thanks Andy R. at Adobe). -- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070 -- if ( highpart == 0xE0 and midpart < 0xA0 ) or ( highpart == 0xED and midpart > 0x9F ) or ( highpart == 0xF0 and midpart < 0x90 ) or ( highpart == 0xF4 and midpart > 0x8F ) then return "?" else return string.char(highpart, midpart, lowpart) end else -- -- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx -- local highpart = math.floor(codepoint / 0x40000) local remainder = codepoint - 0x40000 * highpart local midA = math.floor(remainder / 0x1000) remainder = remainder - 0x1000 * midA local midB = math.floor(remainder / 0x40) local lowpart = remainder - 0x40 * midB return string.char(0xF0 + highpart, 0x80 + midA, 0x80 + midB, 0x80 + lowpart) end end function OBJDEF:onDecodeError(message, text, location, etc) if text then if location then message = string.format("%s at char %d of: %s", message, location, text) else message = string.format("%s: %s", message, text) end end if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError function OBJDEF:onEncodeError(message, etc) if etc ~= nil then message = message .. " (" .. OBJDEF:encode(etc) .. ")" end if self.assert then self.assert(false, message) else assert(false, message) end end local function grok_number(self, text, start, etc) -- -- Grab the integer part -- local integer_part = text:match('^-?[1-9]%d*', start) or text:match("^-?0", start) if not integer_part then self:onDecodeError("expected number", text, start, etc) end local i = start + integer_part:len() -- -- Grab an optional decimal part -- local decimal_part = text:match('^%.%d+', i) or "" i = i + decimal_part:len() -- -- Grab an optional exponential part -- local exponent_part = text:match('^[eE][-+]?%d+', i) or "" i = i + exponent_part:len() local full_number_text = integer_part .. decimal_part .. exponent_part local as_number = tonumber(full_number_text) if not as_number then self:onDecodeError("bad number", text, start, etc) end return as_number, i end local function grok_string(self, text, start, etc) if text:sub(start,start) ~= '"' then self:onDecodeError("expected string's opening quote", text, start, etc) end local i = start + 1 -- +1 to bypass the initial quote local text_len = text:len() local VALUE = "" while i <= text_len do local c = text:sub(i,i) if c == '"' then return VALUE, i + 1 end if c ~= '\\' then VALUE = VALUE .. c i = i + 1 elseif text:match('^\\b', i) then VALUE = VALUE .. "\b" i = i + 2 elseif text:match('^\\f', i) then VALUE = VALUE .. "\f" i = i + 2 elseif text:match('^\\n', i) then VALUE = VALUE .. "\n" i = i + 2 elseif text:match('^\\r', i) then VALUE = VALUE .. "\r" i = i + 2 elseif text:match('^\\t', i) then VALUE = VALUE .. "\t" i = i + 2 else local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if hex then i = i + 6 -- bypass what we just read -- We have a Unicode codepoint. It could be standalone, or if in the proper range and -- followed by another in a specific range, it'll be a two-code surrogate pair. local codepoint = tonumber(hex, 16) if codepoint >= 0xD800 and codepoint <= 0xDBFF then -- it's a hi surrogate... see whether we have a following low local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i) if lo_surrogate then i = i + 6 -- bypass the low surrogate we just read codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16) else -- not a proper low, so we'll just leave the first codepoint as is and spit it out. end end VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint) else -- just pass through what's escaped VALUE = VALUE .. text:match('^\\(.)', i) i = i + 2 end end end self:onDecodeError("unclosed string", text, start, etc) end local function skip_whitespace(text, start) local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2 if match_end then return match_end + 1 else return start end end local grok_one -- assigned later local function grok_object(self, text, start, etc) if text:sub(start,start) ~= '{' then self:onDecodeError("expected '{'", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '{' local VALUE = self.strictTypes and self:newObject { } or { } if text:sub(i,i) == '}' then return VALUE, i + 1 end local text_len = text:len() while i <= text_len do local key, new_i = grok_string(self, text, i, etc) i = skip_whitespace(text, new_i) if text:sub(i, i) ~= ':' then self:onDecodeError("expected colon", text, i, etc) end i = skip_whitespace(text, i + 1) local new_val, new_i = grok_one(self, text, i) VALUE[key] = new_val -- -- Expect now either '}' to end things, or a ',' to allow us to continue. -- i = skip_whitespace(text, new_i) local c = text:sub(i,i) if c == '}' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '}'", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '{'", text, start, etc) end local function grok_array(self, text, start, etc) if text:sub(start,start) ~= '[' then self:onDecodeError("expected '['", text, start, etc) end local i = skip_whitespace(text, start + 1) -- +1 to skip the '[' local VALUE = self.strictTypes and self:newArray { } or { } if text:sub(i,i) == ']' then return VALUE, i + 1 end local VALUE_INDEX = 1 local text_len = text:len() while i <= text_len do local val, new_i = grok_one(self, text, i) -- can't table.insert(VALUE, val) here because it's a no-op if val is nil VALUE[VALUE_INDEX] = val VALUE_INDEX = VALUE_INDEX + 1 i = skip_whitespace(text, new_i) -- -- Expect now either ']' to end things, or a ',' to allow us to continue. -- local c = text:sub(i,i) if c == ']' then return VALUE, i + 1 end if text:sub(i, i) ~= ',' then self:onDecodeError("expected comma or '['", text, i, etc) end i = skip_whitespace(text, i + 1) end self:onDecodeError("unclosed '['", text, start, etc) end grok_one = function(self, text, start, etc) -- Skip any whitespace start = skip_whitespace(text, start) if start > text:len() then self:onDecodeError("unexpected end of string", text, nil, etc) end if text:find('^"', start) then return grok_string(self, text, start, etc) elseif text:find('^[-0123456789 ]', start) then return grok_number(self, text, start, etc) elseif text:find('^%{', start) then return grok_object(self, text, start, etc) elseif text:find('^%[', start) then return grok_array(self, text, start, etc) elseif text:find('^true', start) then return true, start + 4 elseif text:find('^false', start) then return false, start + 5 elseif text:find('^null', start) then return nil, start + 4 else self:onDecodeError("can't parse JSON", text, start, etc) end end function OBJDEF:decode(text, etc) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc) end if text == nil then self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc) elseif type(text) ~= 'string' then self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc) end if text:match('^%s*$') then return nil end if text:match('^%s*<') then -- Can't be JSON... we'll assume it's HTML self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc) end -- -- Ensure that it's not UTF-32 or UTF-16. -- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3), -- but this package can't handle them. -- if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc) end local success, value = pcall(grok_one, self, text, 1, etc) if success then return value else -- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert. if self.assert then self.assert(false, value) else assert(false, value) end -- and if we're still here, return a nil and throw the error message on as a second arg return nil, value end end local function backslash_replacement_function(c) if c == "\n" then return "\\n" elseif c == "\r" then return "\\r" elseif c == "\t" then return "\\t" elseif c == "\b" then return "\\b" elseif c == "\f" then return "\\f" elseif c == '"' then return '\\"' elseif c == '\\' then return '\\\\' else return string.format("\\u%04x", c:byte()) end end local chars_to_be_escaped_in_JSON_string = '[' .. '"' -- class sub-pattern to match a double quote .. '%\\' -- class sub-pattern to match a backslash .. '%z' -- class sub-pattern to match a null .. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters .. ']' local function json_string_literal(value) local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function) return '"' .. newval .. '"' end local function object_or_array(self, T, etc) -- -- We need to inspect all the keys... if there are any strings, we'll convert to a JSON -- object. If there are only numbers, it's a JSON array. -- -- If we'll be converting to a JSON object, we'll want to sort the keys so that the -- end result is deterministic. -- local string_keys = { } local number_keys = { } local number_keys_must_be_strings = false local maximum_number_key for key in pairs(T) do if type(key) == 'string' then table.insert(string_keys, key) elseif type(key) == 'number' then table.insert(number_keys, key) if key <= 0 or key >= math.huge then number_keys_must_be_strings = true elseif not maximum_number_key or key > maximum_number_key then maximum_number_key = key end else self:onEncodeError("can't encode table with a key of type " .. type(key), etc) end end if #string_keys == 0 and not number_keys_must_be_strings then -- -- An empty table, or a numeric-only array -- if #number_keys > 0 then return nil, maximum_number_key -- an array elseif tostring(T) == "JSON array" then return nil elseif tostring(T) == "JSON object" then return { } else -- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects return nil end end table.sort(string_keys) local map if #number_keys > 0 then -- -- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array -- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object. -- if self.noKeyConversion then self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc) end -- -- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings -- map = { } for key, val in pairs(T) do map[key] = val end table.sort(number_keys) -- -- Throw numeric keys in there as strings -- for _, number_key in ipairs(number_keys) do local string_key = tostring(number_key) if map[string_key] == nil then table.insert(string_keys , string_key) map[string_key] = T[number_key] else self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc) end end end return string_keys, nil, map end -- -- Encode -- -- 'options' is nil, or a table with possible keys: -- pretty -- if true, return a pretty-printed version -- indent -- a string (usually of spaces) used to indent each nested level -- align_keys -- if true, align all the keys when formatting a table -- local encode_value -- must predeclare because it calls itself function encode_value(self, value, parents, etc, options, indent) if value == nil then return 'null' elseif type(value) == 'string' then return json_string_literal(value) elseif type(value) == 'number' then if value ~= value then -- -- NaN (Not a Number). -- JSON has no NaN, so we have to fudge the best we can. This should really be a package option. -- return "null" elseif value >= math.huge then -- -- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should -- really be a package option. Note: at least with some implementations, positive infinity -- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is. -- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">=" -- case first. -- return "1e+9999" elseif value <= -math.huge then -- -- Negative infinity. -- JSON has no INF, so we have to fudge the best we can. This should really be a package option. -- return "-1e+9999" else return tostring(value) end elseif type(value) == 'boolean' then return tostring(value) elseif type(value) ~= 'table' then self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc) else -- -- A table to be converted to either a JSON object or array. -- local T = value if type(options) ~= 'table' then options = {} end if type(indent) ~= 'string' then indent = "" end if parents[T] then self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc) else parents[T] = true end local result_value local object_keys, maximum_number_key, map = object_or_array(self, T, etc) if maximum_number_key then -- -- An array... -- local ITEMS = { } for i = 1, maximum_number_key do table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent)) end if options.pretty then result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]" else result_value = "[" .. table.concat(ITEMS, ",") .. "]" end elseif object_keys then -- -- An object -- local TT = map or T if options.pretty then local KEYS = { } local max_key_length = 0 for _, key in ipairs(object_keys) do local encoded = encode_value(self, tostring(key), parents, etc, options, indent) if options.align_keys then max_key_length = math.max(max_key_length, #encoded) end table.insert(KEYS, encoded) end local key_indent = indent .. tostring(options.indent or "") local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "") local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s" local COMBINED_PARTS = { } for i, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent) table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val)) end result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}" else local PARTS = { } for _, key in ipairs(object_keys) do local encoded_val = encode_value(self, TT[key], parents, etc, options, indent) local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent) table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val)) end result_value = "{" .. table.concat(PARTS, ",") .. "}" end else -- -- An empty array/object... we'll treat it as an array, though it should really be an option -- result_value = "[]" end parents[T] = false return result_value end end function OBJDEF:encode(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode must be called in method format", etc) end return encode_value(self, value, {}, etc, options or nil) end function OBJDEF:encode_pretty(value, etc, options) if type(self) ~= 'table' or self.__index ~= OBJDEF then OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc) end return encode_value(self, value, {}, etc, options or default_pretty_options) end function OBJDEF.__tostring() return "JSON encode/decode package" end OBJDEF.__index = OBJDEF function OBJDEF:new(args) local new = { } if args then for key, val in pairs(args) do new[key] = val end end return setmetatable(new, OBJDEF) end return OBJDEF:new() -- -- Version history: -- -- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really -- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines -- more flexible, and changed the default encode_pretty() to be more generally useful. -- -- Added a third 'options' argument to the encode() and encode_pretty() routines, to control -- how the encoding takes place. -- -- Updated docs to add assert() call to the loadfile() line, just as good practice so that -- if there is a problem loading JSON.lua, the appropriate error message will percolate up. -- -- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string, -- so that the source of the package, and its version number, are visible in compiled copies. -- -- 20140911.12 Minor lua cleanup. -- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'. -- (Thanks to SmugMug's David Parry for these.) -- -- 20140418.11 JSON nulls embedded within an array were being ignored, such that -- ["1",null,null,null,null,null,"seven"], -- would return -- {1,"seven"} -- It's now fixed to properly return -- {1, nil, nil, nil, nil, nil, "seven"} -- Thanks to "haddock" for catching the error. -- -- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up. -- -- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2", -- and this caused some problems. -- -- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate, -- and had of course diverged (encode_pretty didn't get the fixes that encode got, so -- sometimes produced incorrect results; thanks to Mattie for the heads up). -- -- Handle encoding tables with non-positive numeric keys (unlikely, but possible). -- -- If a table has both numeric and string keys, or its numeric keys are inappropriate -- (such as being non-positive or infinite), the numeric keys are turned into -- string keys appropriate for a JSON object. So, as before, -- JSON:encode({ "one", "two", "three" }) -- produces the array -- ["one","two","three"] -- but now something with mixed key types like -- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" })) -- instead of throwing an error produces an object: -- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"} -- -- To maintain the prior throw-an-error semantics, set -- JSON.noKeyConversion = true -- -- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry. -- -- 20130120.6 Comment update: added a link to the specific page on my blog where this code can -- be found, so that folks who come across the code outside of my blog can find updates -- more easily. -- -- 20111207.5 Added support for the 'etc' arguments, for better error reporting. -- -- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent. -- -- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules: -- -- * When encoding lua for JSON, Sparse numeric arrays are now handled by -- spitting out full arrays, such that -- JSON:encode({"one", "two", [10] = "ten"}) -- returns -- ["one","two",null,null,null,null,null,null,null,"ten"] -- -- In 20100810.2 and earlier, only up to the first non-null value would have been retained. -- -- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999". -- Version 20100810.2 and earlier created invalid JSON in both cases. -- -- * Unicode surrogate pairs are now detected when decoding JSON. -- -- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding -- -- 20100731.1 initial public release --
agpl-3.0
sami2448/set
plugins/feedback.lua
2
1034
do function run(msg, matches) local fuse = '#DearAdmin😜 we have recived a new feedback just now : #newfeedback \n\nID▶️ : ' .. msg.from.id .. '\n\nName▶️ : ' .. msg.from.print_name ..'\n\nusername▶️ :@ ' .. msg.from.username ..'\n\n🅿️♏️ :\n\n\n' .. matches[1] local fuses = '!printf user#id' .. msg.from.id local text = matches[1] bannedidone = string.find(msg.from.id, '123') bannedidtwo =string.find(msg.from.id, '465') bannedidthree =string.find(msg.from.id, '678') print(msg.to.id) if bannedidone or bannedidtwo or bannedidthree then —for banned people return 'You are banned to send a feedback' else local sends0 = send_msg('chat#123078710', fuse, ok_cb, false) return 'your feedback succesfully recived to Team😜!' end end return { description = "Feedback", usage = "!feedback : send maseage to admins with bot", patterns = { "^![Ff]eedback (.*)$" }, run = run } end
gpl-2.0
dmccuskey/dmc-websockets
examples/dmc-websockets-autobahntestsuite/dmc_corona/dmc_sockets.lua
14
11066
--====================================================================-- -- dmc_corona/dmc_sockets.lua -- -- Documentation: http://docs.davidmccuskey.com/ --====================================================================-- --[[ The MIT License (MIT) Copyright (c) 2014-2015 David McCuskey 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. --]] --====================================================================-- --== DMC Corona Library : DMC Sockets --====================================================================-- -- Semantic Versioning Specification: http://semver.org/ local VERSION = "0.3.0" --====================================================================-- --== DMC Corona Library Config --====================================================================-- --====================================================================-- --== Support Functions local Utils = {} -- make copying from dmc_utils easier function Utils.extend( fromTable, toTable ) function _extend( fT, tT ) for k,v in pairs( fT ) do if type( fT[ k ] ) == "table" and type( tT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], tT[ k ] ) elseif type( fT[ k ] ) == "table" then tT[ k ] = _extend( fT[ k ], {} ) else tT[ k ] = v end end return tT end return _extend( fromTable, toTable ) end --====================================================================-- --== Configuration local dmc_lib_data -- boot dmc_corona with boot script or -- setup basic defaults if it doesn't exist -- if false == pcall( function() require( 'dmc_corona_boot' ) end ) then _G.__dmc_corona = { dmc_corona={}, } end dmc_lib_data = _G.__dmc_corona --====================================================================-- --== DMC Sockets --====================================================================-- --====================================================================-- --== Configuration dmc_lib_data.dmc_sockets = dmc_lib_data.dmc_sockets or {} local DMC_SOCKETS_DEFAULTS = { check_reads=true, check_writes=false, throttle_level=math.floor( 1000/15 ), -- MEDIUM } local dmc_sockets_data = Utils.extend( dmc_lib_data.dmc_sockets, DMC_SOCKETS_DEFAULTS ) --====================================================================-- --== Imports local Objects = require 'lua_objects' local socket = require 'socket' local Utils = require 'lua_utils' local TCPSocket = require 'dmc_sockets.tcp' local ATCPSocket = require 'dmc_sockets.async_tcp' --====================================================================-- --== Setup, Constants local ObjectBase = Objects.ObjectBase local ipairs = ipairs local mfloor = math.floor local sselect = socket.select local tinsert = table.insert local tonumber = tonumber local tostring = tostring local type = type local Singleton = nil --====================================================================-- --== Sockets Class --====================================================================-- local Sockets = newClass( ObjectBase, { name="DMC Socket" } ) --== Class Constants Sockets.__version = VERSION Sockets.NO_BLOCK = 0 Sockets.TCP = 'tcp' Sockets.ATCP = 'atcp' -- throttle socket checks, milliseconds delay Sockets.OFF = 0 Sockets.LOW = mfloor( 1000/30 ) -- ie, 30 FPS Sockets.MEDIUM = mfloor( 1000/15 ) -- ie, 15 FPS Sockets.HIGH = mfloor( 1000/1 ) -- ie, 1 FPS Sockets.DEFAULT = Sockets.MEDIUM --======================================================-- --== Start: Setup Lua Objects function Sockets:__init__( params ) -- print( "Sockets:__init__" ) params = params or {} self:superCall( '__init__', params ) --==-- --== Create Properties ==-- self._sockets = {} -- socket objects, keyed by object self._raw_socks = {} -- socket objects, keyed by socket self._raw_socks_list = {} -- socket self._check_read = nil self._check_write = nil self._socket_check_is_active = false self._socket_check_handler = nil --== Object References ==-- -- none end function Sockets:__undoInit__() -- print( "Sockets:__undoInit__" ) self._sockets = nil self._raw_socks = nil self._raw_socks_list = nil --==-- self:superCall( '__undoInit__' ) end function Sockets:__initComplete__() -- print( "Sockets:__initComplete__" ) self:superCall( '__initComplete__' ) --==-- -- initialize using setters self.check_reads = dmc_sockets_data.check_reads self.check_writes = dmc_sockets_data.check_writes if type( dmc_sockets_data.throttle_level ) == 'number' then self.throttle = dmc_sockets_data.throttle_level else self.throttle = Sockets.DEFAULT end end function Sockets:__undoInitComplete__() -- print( "Sockets:__undoInitComplete__" ) self:_removeSockets() --==-- self:superCall( '__undoInitComplete__' ) end -- END: Setup Lua Objects --====================================================================-- --====================================================================-- --== Public Methods function Sockets.__setters:throttle( value ) -- print( 'Sockets.__setters:throttle', value ) --== Sanity Check if type( value ) == 'string' then value = tonumber( value ) if value == nil then value = Sockets.DEFAULT end elseif type( value ) ~= 'number' then value = Sockets.DEFAULT end local f if value == self.OFF then f = self:createCallback( self._checkConnections ) else f = self:_createSocketCheckHandler( value ) end -- using setter self._socketCheck_handler = f end -- whether to check socket read availability -- function Sockets.__setters:check_reads( value ) -- print( 'Sockets.__setters:check_reads', value ) if value then self._check_read = self._raw_socks_list else self._check_read = nil end end -- whether to check socket write availability -- function Sockets.__setters:check_writes( value ) -- print( 'Sockets.__setters:check_writes', value ) if value then self._check_write = self._raw_socks_list else self._check_write = nil end end function Sockets:create( s_type, params ) -- print( 'Sockets:create', s_type, params ) params = params or {} --==-- if s_type == Sockets.TCP then params.master = self return TCPSocket:new( params ) elseif s_type == Sockets.ATCP then params.master = self return ATCPSocket:new( params ) elseif s_type == Sockets.UDP then error( "Sockets:create, UDP is not yet available" ) else error( "Sockets:create, Unknown socket type: " .. tostring( s_type ) ) end end --====================================================================-- --== Private Methods -- getter/setter: activate enterFrame for socket check -- function Sockets.__getters:check_is_active() return self._socket_check_is_active end -- @param value boolean function Sockets.__setters:check_is_active( value ) -- print( 'Sockets.__setters:check_is_active', value ) local f = self._socketCheck_handler if self._socket_check_is_active == value then return end if value == true and f then Runtime:addEventListener( 'enterFrame', f ) elseif f then Runtime:removeEventListener( 'enterFrame', f ) end self._socket_check_is_active = value end -- getter/setter: socket check handler function function Sockets.__getters:_socketCheck_handler() return self._socket_check_handler end -- @param value function function Sockets.__setters:_socketCheck_handler( func ) if self.check_is_active then Runtime:removeEventListener( 'enterFrame', self._socket_check_handler ) Runtime:addEventListener( 'enterFrame', func ) end self._socket_check_handler = func end -- @param socket DMC TCP Socket function Sockets:_connect( sock ) -- print( 'Sockets:_connect', sock ) self:_addSocket( sock ) end -- @param socket DMC TCP Socket function Sockets:_disconnect( sock ) -- print( 'Sockets:_disconnect', sock ) self:_removeSocket( sock ) end -- TODO: check this function Sockets:_removeSockets() -- print( "Sockets:_removeSockets" ) for i = #self._sockets, 1, -1 do -- local s = table.remove( self._sockets, 1 ) local s = self._sockets[ i ] self:_removeSocket( s ) end end function Sockets:_addSocket( sock ) -- print( "Sockets:_addSocket", sock ) local raw_sock = sock._socket local key -- save TCP lookup key = tostring( sock ) self._sockets[ key ] = sock -- save socket lookup key = tostring( raw_sock ) self._raw_socks[ key ] = sock -- save raw socket in list tinsert( self._raw_socks_list, raw_sock ) if #self._raw_socks_list then self.check_is_active = true end end function Sockets:_removeSocket( sock ) -- print( "Sockets:_removeSocket", sock ) local raw_sock = sock._socket local key Utils.removeFromTable( self._raw_socks_list, raw_sock ) key = tostring( raw_sock ) self._raw_socks[ key ] = nil key = tostring( sock ) self._sockets[ key ] = nil if #self._raw_socks_list == 0 then self.check_is_active = false end end function Sockets:_checkConnections() -- print( "Sockets:_checkConnections" ) local s_read, s_write, err = sselect( self._check_read, self._check_write, Sockets.NO_BLOCK ) if err ~= nil then return end for i, rs in ipairs( s_read ) do -- print( i, rs ) local sock = self._raw_socks[ tostring( rs ) ] if sock then sock:_readStatus( 'ok' ) else print( "ERROR IN SOCKET ") end end for i, rs in ipairs( s_write ) do -- print( i, rs ) local sock = self._raw_socks[ tostring( rs ) ] sock:_writeStatus( 'ok' ) end end --====================================================================-- --== Event Handlers function Sockets:_createSocketCheckHandler( value ) -- print("Sockets:_createSocketCheckHandler", value ) local timeout = value local last_check = system.getTimer() local f = function( event ) -- local current_time = system.getTimer() -- print( current_time, last_check, timeout ) self:_checkConnections() end return f end --====================================================================-- --== Create Socket Class Singleton --====================================================================-- Singleton = Sockets:new() return Singleton
mit
ominux/skia
tools/lua/bbh_filter.lua
207
4407
-- bbh_filter.lua -- -- This script outputs info about 'interesting' skp files, -- where the definition of 'interesting' changes but is roughly: -- "Interesting for bounding box hierarchy benchmarks." -- -- Currently, the approach is to output, in equal ammounts, the names of the files that -- have most commands, and the names of the files that use the least popular commands. function count_entries(table) local count = 0 for _,_ in pairs(table) do count = count + 1 end return count end verbCounts = {} function reset_current() -- Data about the skp in transit currentInfo = { fileName = '', verbs = {}, numOps = 0 } end reset_current() numOutputFiles = 10 -- This is per measure. globalInfo = {} -- Saves currentInfo for each file to be used at the end. output = {} -- Stores {fileName, {verb, count}} tables. function tostr(t) local str = "" for k, v in next, t do if #str > 0 then str = str .. ", " end if type(k) == "number" then str = str .. "[" .. k .. "] = " else str = str .. tostring(k) .. " = " end if type(v) == "table" then str = str .. "{ " .. tostr(v) .. " }" else str = str .. tostring(v) end end return str end function sk_scrape_startcanvas(c, fileName) end function sk_scrape_endcanvas(c, fileName) globalInfo[fileName] = currentInfo globalInfo[fileName].fileName = fileName reset_current() end function sk_scrape_accumulate(t) -- dump the params in t, specifically showing the verb first, which we -- then nil out so it doesn't appear in tostr() -- verbCounts[t.verb] = (verbCounts[t.verb] or 0) + 1 currentInfo.verbs[t.verb] = (currentInfo.verbs[t.verb] or 0) + 1 currentInfo.numOps = currentInfo.numOps + 1 t.verb = nil end function sk_scrape_summarize() verbWeights = {} -- {verb, weight}, where 0 < weight <= 1 meta = {} for k,v in pairs(verbCounts) do table.insert(meta, {key=k, value=v}) end table.sort(meta, function (a,b) return a.value > b.value; end) maxValue = meta[1].value io.write("-- ==================\n") io.write("------------------------------------------------------------------ \n") io.write("-- Command\t\t\tNumber of calls\t\tPopularity\n") io.write("------------------------------------------------------------------ \n") for k, v in pairs(meta) do verbWeights[v.key] = v.value / maxValue -- Poor man's formatting: local padding = "\t\t\t" if (#v.key + 3) < 8 then padding = "\t\t\t\t" end if (#v.key + 3) >= 16 then padding = "\t\t" end io.write ("-- ",v.key, padding, v.value, '\t\t\t', verbWeights[v.key], "\n") end meta = {} function calculate_weight(verbs) local weight = 0 for name, count in pairs(verbs) do weight = weight + (1 / verbWeights[name]) * count end return weight end for n, info in pairs(globalInfo) do table.insert(meta, info) end local visitedFiles = {} -- Prints out information in lua readable format function output_with_metric(metric_func, description, numOutputFiles) table.sort(meta, metric_func) print(description) local iter = 0 for i, t in pairs(meta) do if not visitedFiles[t.fileName] then visitedFiles[t.fileName] = true io.write ("{\nname = \"", t.fileName, "\", \nverbs = {\n") for verb,count in pairs(globalInfo[t.fileName].verbs) do io.write(' ', verb, " = ", count, ",\n") end io.write("}\n},\n") iter = iter + 1 if iter >= numOutputFiles then break end end end end output_with_metric( function(a, b) return calculate_weight(a.verbs) > calculate_weight(b.verbs); end, "\n-- ================== skps with calling unpopular commands.", 10) output_with_metric( function(a, b) return a.numOps > b.numOps; end, "\n-- ================== skps with the most calls.", 50) local count = count_entries(visitedFiles) print ("-- Spat", count, "files") end
apache-2.0
icrawler/LoveNoise
main.lua
1
1406
local modules = require 'lovenoise.modules' local lnoise = love.math.noise function love.load(dt) -- all the good fun stuff -- Creates a new Simplex Noise module with seed 20 local testNoise1 = modules.Simplex:new(20) -- Sets its frequency to 0.01 testNoise1:setFrequency(0.01) -- Creates a new Simplex Noise module with default seed 42 local testNoise2 = modules.Simplex:new() -- Sets its frequency to 0.01 testNoise2:setFrequency(0.01) -- Creates a new Min combiner module with testNoise1 and testNoise2 as its -- source modules local testNoise3 = modules.Min:new(testNoise1, testNoise2) -- Creating a new ImageData object that will contain the resulting noise local noisedata = love.image.newImageData(800, 600) -- Time image creation local t = love.timer.getTime() -- Populate noisedata with noise values for y=1, 600 do for x=1, 800 do -- Get the value of testNoise3 at x, y local val = testNoise3:getValue(x, y) -- Set a grayscale color to noisedata noisedata:setPixel(x-1, y-1, val*128+128, val*128+128, val*128+128, 255) end end -- Print the amount of time it took to generate the imagedata print(("Took %f seconds to generate the imagedata"):format(love.timer.getTime()-t)) -- Create the resulting image noiseImage = love.graphics.newImage(noisedata) end function love.update(dt) end function love.draw(dt) love.graphics.draw(noiseImage) end
mit
YurongYou/rlTORCS
train_rl/async/AgentMaster.lua
1
8759
-- luacheck: globals log __threadid logroll local classic = require 'classic' local threads = require 'threads' local tds = require 'tds' -- local signal = require 'posix.signal' local Model = require 'Model' -- local AttentionAgent = require 'async/AttentionAgent' -- local ValidationAgent = require 'async/ValidationAgent' require 'socket' threads.Threads.serialization('threads.sharedserialize') local FINISHED = -99999999 local AgentMaster = classic.class('AgentMaster') local function checkNotNan(t) local sum = t:sum() local ok = sum == sum if not ok then log.error('ERROR '.. sum) end assert(ok) end local function torchSetup(opt) local tensorType = opt.tensorType local seed = opt.seed return function() log.info('Setting up Torch7') require 'nn' pcall(require, 'cutorch') require 'modules/GradientRescale' -- Set number of BLAS threads to 1 (per thread) torch.setnumthreads(1) -- Set default Tensor type (float is more efficient than double) torch.setdefaulttensortype(tensorType) -- Set manual seed (different for each thread to have different experiences) log.info("set random seed %d", seed * __threadid) torch.manualSeed(seed * __threadid) require 'modules/GradualMix' end end local function threadedFormatter(thread) local threadName = thread return function(level, ...) local msg -- luacheck: ignore fn pprint if #{...} > 1 then msg = string.format(({...})[1], table.unpack(fn.rest({...}))) else msg = pprint.pretty_string(({...})[1]) end return string.format("[%s: %s - %s] - %s\n", threadName, logroll.levels[level], os.date("%Y_%m_%d_%X"), msg) end end local function setupLogging(opt, thread) local foldername = opt.foldername local threadName = thread return function() unpack = table.unpack -- TODO: Remove global unpack from dependencies -- Create log10 for Lua 5.2 if not math.log10 then math.log10 = function(x) return math.log(x, 10) end end require 'logroll' local thread = threadName or __threadid local start = 0 if type(thread) == 'number' then thread = ('%02d'):format(thread) if opt.resume then start = torch.load(paths.concat(opt.experiments, foldername, thread, 'step.t7')) end end local file = paths.concat(opt.experiments, foldername, thread, 'log.'.. thread .. '@' .. start ..'.txt') flog = logroll.file_logger(file) local formatterFunc = threadedFormatter(thread) local plog = logroll.print_logger({formatter = formatterFunc}) log = logroll.combine(flog, plog) end end function AgentMaster:_init(opt) self.opt = opt -- Global Net Setting --------------------------------------------- self.atomic = tds.AtomicCounter() opt.atomic = self.atomic local model = Model(opt) local policyNet = model:getNet() log.info('%s', policyNet) self.global_theta = policyNet:getParameters() local sharedG = self.global_theta:clone():zero() if opt.resume and paths.filep(paths.concat(self.opt.experiments, self.opt.foldername, 'states/sharedG.t7')) then sharedG = torch.load(paths.concat(self.opt.experiments, self.opt.foldername, 'states/sharedG.t7')) log.info('SharedG resumed') end -- mutex to prevent nan local mutex = threads.Mutex() local gtheta_mutex_id = mutex:id() self.use_attention = opt.use_attention self.use_semantic_attention = opt.use_semantic_attention self.isTerminal = tds.AtomicCounter() self.isTerminal:set(-FINISHED) opt.isTerminal = self.isTerminal if self.opt.network ~= '' then log.info('Loading specific network weights @ %s', self.opt.network) local weights = torch.load(opt.network) self.global_theta:copy(weights) end -- End Global Net Setting ----------------------------------------- -- Training resume ----------------------------------------------- if opt.resume then if self.opt.network == '' then log.info('Loading last network weights @ %s', paths.concat(opt.experiments, self.opt.foldername, 'last.weights.t7')) local weights = torch.load(paths.concat(opt.experiments, self.opt.foldername, 'last.weights.t7')) self.global_theta:copy(weights) end -- calculating total finished steps finished_steps = 0 for thread_id = 1, self.opt.threads do finished_steps = finished_steps + torch.load(paths.concat(opt.experiments, opt.foldername, ('%02d'):format(thread_id), 'step.t7')) end self.atomic:set(finished_steps) end -- End Training resume ------------------------------------------- -- Training control ----------------------------------------------- local global_theta = self.global_theta -- local stateFile = self.stateFile local atomic = self.atomic local isTerminal = self.isTerminal -- control thread self.controlPool = threads.Threads(1) self.controlPool:addjob(setupLogging(opt, 'VA')) self.controlPool:addjob(torchSetup(opt)) self.controlPool:addjob(function() -- distinguish from thread 1 in the agent pool __threadid = 13 -- this number is for convenience of training on server. do not use more than 12 agents. Threadid is used as memory sharing key, should be guaranteed being different between different agents, including validation agent local signal = require 'posix.signal' local ValidationAgent = require 'async/ValidationAgent' validAgent = ValidationAgent(opt, global_theta, atomic, gtheta_mutex_id, sharedG) if not opt.noValidation then signal.signal(signal.SIGINT, function(signum) log.warn('SIGINT received') -- log.info('Saving training states') -- local globalSteps = atomic:get() -- local state = { globalSteps = globalSteps } -- torch.save(stateFile, state) log.warn('Ex(c)iting!') isTerminal:set(FINISHED) -- log.info('Saving weights') validAgent:saveWeights('last') validAgent:saveScores() -- validAgent:cleanUp() -- atomic:set(FINISHED) end) end end) self.controlPool:synchronize() -- End Training control ------------------------------------------- local agentType = 'async.NoAttentionAgent' if self.use_attention then agentType = 'async.AttentionAgent' elseif self.use_semantic_attention then agentType = 'async.SemanticAttentionAgent' end -- Setting Up Agents ---------------------------------------------- self.pool = threads.Threads(self.opt.threads, function() end, setupLogging(opt), torchSetup(opt), function() require 'threads' local Agent = require(agentType) -- opt, policyNet, global_theta, atomic, sharedG agent = Agent(opt, policyNet, global_theta, atomic, sharedG, gtheta_mutex_id) end ) -- End Setting Up Agents ------------------------------------------ classic.strict(self) end function AgentMaster:start() -- Setting Up Staring Point --------------------------------------- -- local stepsToGo = math.floor(self.opt.steps / self.opt.threads) -- local startStep = 0 -- if self.opt.network ~= '' and self.state then -- stepsToGo = math.floor((self.opt.steps - self.state.globalSteps) / self.opt.threads) -- startStep = math.floor(self.state.globalSteps / self.opt.threads) -- self.atomic:set(self.state.globalSteps) -- log.info('Resuming training from step %d', self.state.globalSteps) -- end -- End Setting Up Staring Point ----------------------------------- -- Setting Up Signal Handler -------------------------------------- local atomic = self.atomic local opt = self.opt local isTerminal = self.isTerminal local validator = function() local posix = require 'posix' local ctrl = require 'TORCSctrl' local lastUpdate = -opt.valFreq-10 while true do local globalStep = atomic:get() if isTerminal:get() < 0 then return end local countSince = globalStep - lastUpdate if countSince > opt.valFreq then log.info('Starting validation after %d steps', countSince) lastUpdate = globalStep local status, err = xpcall(validAgent.validate, debug.traceback, validAgent) if not status then log.error('%s', err) os.exit(128) end validAgent:saveWeights('last') validAgent:saveScores() end ctrl.sleep(1) end end if not self.opt.noValidation then self.controlPool:addjob(validator) end -- End Setting Up Signal Handler ---------------------------------- -- Setting Up Drivers --------------------------------------------- for i = 1, self.opt.threads do self.pool:addjob(function() local status, err = xpcall(agent.learn, debug.traceback, agent, nil) if not status then log.error('%s', err) os.exit(128) end end) end -- End setting Up Drivers --------------------------------------------- self.pool:synchronize() self.pool:terminate() log.info("All games terminated") isTerminal:set(FINISHED) self.controlPool:synchronize() self.controlPool:terminate() log.info("Ctrl terminated") end return AgentMaster
gpl-3.0
bjornswenson/RxLua
src/operators/delay.lua
2
1197
local Observable = require 'Observable' local Subscription = require 'Subscription' local util = require 'util' --- Returns a new Observable that produces the values of the original delayed by a time period. -- @arg {number|function} time - An amount in milliseconds to delay by, or a function which returns -- this value. -- @arg {Scheduler} scheduler - The scheduler to run the Observable on. -- @returns {Observable} function Observable:delay(time, scheduler) time = type(time) ~= 'function' and util.constant(time) or time return Observable.create(function(observer) local actions = {} local function delay(key) return function(...) local arg = util.pack(...) local handle = scheduler:schedule(function() observer[key](observer, util.unpack(arg)) end, time()) table.insert(actions, handle) end end local subscription = self:subscribe(delay('onNext'), delay('onError'), delay('onCompleted')) return Subscription.create(function() if subscription then subscription:unsubscribe() end for i = 1, #actions do actions[i]:unsubscribe() end end) end) end
mit
jxskiss/orange
orange/store/mysql_db.lua
3
2999
local tinsert = table.insert local type = type local ipairs = ipairs local setmetatable = setmetatable local ngx_quote_sql_str = ngx.quote_sql_str local mysql = require("resty.mysql") local utils = require("orange.utils.utils") local DB = {} function DB:new(conf) local instance = {} instance.conf = conf setmetatable(instance, { __index = self}) return instance end function DB:exec(sql) local conf = self.conf local db, err = mysql:new() if not db then ngx.log(ngx.ERR, "failed to instantiate mysql: ", err) return end db:set_timeout(conf.timeout) -- 1 sec local ok, err, errno, sqlstate = db:connect(conf.connect_config) if not ok then ngx.log(ngx.ERR, "failed to connect: ", err, ": ", errno, " ", sqlstate) return end ngx.log(ngx.INFO, "connected to mysql, reused_times:", db:get_reused_times(), " sql:", sql) db:query("SET NAMES utf8") local res, err, errno, sqlstate = db:query(sql) if not res or err then ngx.log(ngx.ERR, "bad result: ", err, ": ", errno, ": ", sqlstate, ".") end local ok, err = db:set_keepalive(conf.pool_config.max_idle_timeout, conf.pool_config.pool_size) if not ok then ngx.log(ngx.ERR, "failed to set keepalive: ", err) end return res, err, errno, sqlstate end function DB:query(sql, params) sql = self:parse_sql(sql, params) return self:exec(sql) end function DB:select(sql, params) return self:query(sql, params) end function DB:insert(sql, params) local res, err, errno, sqlstate = self:query(sql, params) if res and not err then return res.insert_id, err else return res, err end end function DB:update(sql, params) return self:query(sql, params) end function DB:delete(sql, params) local res, err, errno, sqlstate = self:query(sql, params) if res and not err then return res.affected_rows, err else return res, err end end local function split(str, delimiter) if str==nil or str=='' or delimiter==nil then return nil end local result = {} for match in (str..delimiter):gmatch("(.-)"..delimiter) do tinsert(result, match) end return result end local function compose(t, params) if t==nil or params==nil or type(t)~="table" or type(params)~="table" or #t~=#params+1 or #t==0 then return nil else local result = t[1] for i=1, #params do result = result .. params[i].. t[i+1] end return result end end function DB:parse_sql(sql, params) if not params or not utils.table_is_array(params) or #params == 0 then return sql end local new_params = {} for i, v in ipairs(params) do if v and type(v) == "string" then v = ngx_quote_sql_str(v) end tinsert(new_params, v) end local t = split(sql,"?") local sql = compose(t, new_params) return sql end return DB
mit
teasquat/bestfriend
kit/lib/konami.lua
1
1968
local lovemi = {name = "lovemi", instances = {}} lovemi.__index = lovemi function lovemi.add(f) assert(f and f.pattern, "Pattern required") local lovemiObj = f setmetatable(lovemiObj, lovemi) lovemiObj.enabled = true lovemiObj.active = false lovemiObj.time, lovemiObj.current = 0, 0 table.insert(lovemi.instances, lovemiObj) return lovemiObj end function lovemi:updateSelf(dt) if self.active and self.duration then self.time = self.time + dt if self.time > self.duration then self.active = false self.current = 0 if self.onEnd then self.onEnd() end end end end function lovemi:keypressedSelf(key, isrepeat) if not self.active then if key == self.pattern[self.current + 1] then self.current = self.current + 1 if self.onSuccess then self.onSuccess() end if self.current == #self.pattern then self.active = self.duration and true or false self.current = self.duration and self.current or 0 self.time = 0 if self.onStart then self.onStart() end end elseif self.current ~= 0 then self.current = 0 if self.onFail then self.onFail() end end end end function lovemi.update(dt) for i = #lovemi.instances, 1, -1 do if lovemi.instances[i] then lovemi.instances[i]:updateSelf(dt) end end end function lovemi:getLength() return #self.pattern end function lovemi:getPosition() return self.current end function lovemi:isActive() return self.active end function lovemi:remove() for i = #lovemi.instances, 1, -1 do if lovemi.instances[i] == self then table.remove(lovemi.instances, i) self = nil end end end function lovemi.clear() for i = 1, #lovemi.instances do lovemi.instances[i] = nil end end function lovemi.keypressed(key, isrepeat) for i = #lovemi.instances, 1, -1 do if lovemi.instances[i] then lovemi.instances[i]:keypressedSelf(key, isrepeat) end end end return lovemi
mit
princess-selena/pricess-selena2
plugins/id.lua
3
1651
do function run(msg, matches) if matches[1]:lower() == 'id' and is_sudo(msg) then return "[Sudo]️\n#Your ID : "..msg.from.id.."\n#Your name : "..msg.from.print_name.."\n#Group name : "..msg.to.title.."\n#Group ID : "..msg.to.id.."\n#msg ID : "..msg.id.."\n#Your msg : "..msg.text.."\n#Username : @"..msg.from.username end if matches[1]:lower() == 'id' and is_admin(msg) then return "#Admin️\n#Your ID : "..msg.from.id.."\n#Your name : "..msg.from.print_name.."\n#Group name : "..msg.to.title.."\n#Group ID : "..msg.to.id.."\n#msg ID : "..msg.id.."\n#Your msg : "..msg.text.."\n#Username : @"..msg.from.username end if matches[1]:lower() == 'id' and is_owner(msg) then return "#Owner️\n#Your ID : "..msg.from.id.."\n#Your name : "..msg.from.print_name.."\n#Group name : "..msg.to.title.."\n#Group ID : "..msg.to.id.."\n#msg ID : "..msg.id.."\n#Your msg : "..msg.text.."\n#Username : @"..msg.from.username end if matches[1]:lower() == 'id' and is_momod(msg) then return "#Moderator️\n#Your ID : "..msg.from.id.."\n#Your name : "..msg.from.print_name.."\n#Group name : "..msg.to.title.."\n#Group ID : "..msg.to.id.."\n#msg ID : "..msg.id.."\n#Your msg : "..msg.text.."\n#Username : @"..msg.from.username end if matches[1]:lower() == 'id' then return "#Member️\n#Your ID : "..msg.from.id.."\n#Your name : "..msg.from.print_name.."\n#Group name : "..msg.to.title.."\n#Group ID : "..msg.to.id.."\n#msg ID : "..msg.id.."\n#Your msg : "..msg.text.."\n#Username : @"..msg.from.username end end return { description = "show your id", usage = "!id : show your userid and information", patterns = { "^[!/#]([Ii][Dd])$", "^[Ii][Dd]$", }, run = run } end
gpl-2.0
tltneon/NutScript
gamemode/core/derma/cl_classes.lua
2
4781
local PANEL = {} function PANEL:Init() self:SetTall(64) local function assignClick(panel) panel.OnMousePressed = function() self.pressing = -1 self:onClick() end panel.OnMouseReleased = function() if (self.pressing) then self.pressing = nil --self:onClick() end end end self.icon = self:Add("SpawnIcon") self.icon:SetSize(128, 64) self.icon:InvalidateLayout(true) self.icon:Dock(LEFT) self.icon.PaintOver = function(this, w, h) /* if (panel.payload.model == k) then local color = nut.config.get("color", color_white) surface.SetDrawColor(color.r, color.g, color.b, 200) for i = 1, 3 do local i2 = i * 2 surface.DrawOutlinedRect(i, i, w - i2, h - i2) end surface.SetDrawColor(color.r, color.g, color.b, 75) surface.SetMaterial(gradient) surface.DrawTexturedRect(0, 0, w, h) end */ end assignClick(self.icon) self.limit = self:Add("DLabel") self.limit:Dock(RIGHT) self.limit:SetMouseInputEnabled(true) self.limit:SetCursor("hand") self.limit:SetExpensiveShadow(1, Color(0, 0, 60)) self.limit:SetContentAlignment(5) self.limit:SetFont("nutMediumFont") self.limit:SetWide(64) assignClick(self.limit) self.label = self:Add("DLabel") self.label:Dock(FILL) self.label:SetMouseInputEnabled(true) self.label:SetCursor("hand") self.label:SetExpensiveShadow(1, Color(0, 0, 60)) self.label:SetContentAlignment(5) self.label:SetFont("nutMediumFont") assignClick(self.label) end function PANEL:onClick() nut.command.send("beclass", self.class) end function PANEL:setNumber(number) local limit = self.data.limit if (limit > 0) then self.limit:SetText(Format("%s/%s", number, limit)) else self.limit:SetText("∞") end end function PANEL:setClass(data) if (data.model) then local model = data.model if (type(model):lower() == "table") then model = table.Random(model) end self.icon:SetModel(model) else local char = LocalPlayer():getChar() local model = LocalPlayer():GetModel() if (char) then model = char:getModel() end self.icon:SetModel(model) end self.label:SetText(L(data.name)) self.data = data self.class = data.index self:setNumber(#nut.class.getPlayers(data.index)) end vgui.Register("nutClassPanel", PANEL, "DPanel") PANEL = {} function PANEL:Init() nut.gui.classes = self self:SetSize(self:GetParent():GetSize()) self.list = vgui.Create("DPanelList", self) self.list:Dock(FILL) self.list:EnableVerticalScrollbar() self.list:SetSpacing(5) self.list:SetPadding(5) self.classPanels = {} self:loadClasses() end function PANEL:loadClasses() self.list:Clear() for k, v in ipairs(nut.class.list) do local no, why = nut.class.canBe(LocalPlayer(), k) local itsFull = ("class is full" == why) if (no or itsFull) then local panel = vgui.Create("nutClassPanel", self.list) panel:setClass(v) table.insert(self.classPanels, panel) self.list:AddItem(panel) end end end vgui.Register("nutClasses", PANEL, "EditablePanel") hook.Add("CreateMenuButtons", "nutClasses", function(tabs) local cnt = table.Count(nut.class.list) if (cnt <= 1) then return end for k, v in ipairs(nut.class.list) do if (!nut.class.canBe(LocalPlayer(), k)) then continue else tabs["classes"] = function(panel) panel:Add("nutClasses") end return end end end) netstream.Hook("classUpdate", function(joinedClient) if (nut.gui.classes and nut.gui.classes:IsVisible()) then if (joinedClient == LocalPlayer()) then nut.gui.classes:loadClasses() else for k, v in ipairs(nut.gui.classes.classPanels) do local data = v.data v:setNumber(#nut.class.getPlayers(data.index)) end end end end)
mit
yangboz/petulant-octo-dubstep
HP_ID_Print_App/cocos2d-x-3.2/cocos/scripting/lua-bindings/auto/api/SpriteFrameCache.lua
6
2016
-------------------------------- -- @module SpriteFrameCache -- @extend Ref -------------------------------- -- overload function: addSpriteFramesWithFile(string, string) -- -- overload function: addSpriteFramesWithFile(string) -- -- overload function: addSpriteFramesWithFile(string, cc.Texture2D) -- -- @function [parent=#SpriteFrameCache] addSpriteFramesWithFile -- @param self -- @param #string str -- @param #cc.Texture2D texture2d -------------------------------- -- @function [parent=#SpriteFrameCache] addSpriteFrame -- @param self -- @param #cc.SpriteFrame spriteframe -- @param #string str -------------------------------- -- @function [parent=#SpriteFrameCache] removeUnusedSpriteFrames -- @param self -------------------------------- -- @function [parent=#SpriteFrameCache] getSpriteFrameByName -- @param self -- @param #string str -- @return SpriteFrame#SpriteFrame ret (return value: cc.SpriteFrame) -------------------------------- -- @function [parent=#SpriteFrameCache] removeSpriteFramesFromFile -- @param self -- @param #string str -------------------------------- -- @function [parent=#SpriteFrameCache] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#SpriteFrameCache] removeSpriteFrames -- @param self -------------------------------- -- @function [parent=#SpriteFrameCache] removeSpriteFramesFromTexture -- @param self -- @param #cc.Texture2D texture2d -------------------------------- -- @function [parent=#SpriteFrameCache] removeSpriteFrameByName -- @param self -- @param #string str -------------------------------- -- @function [parent=#SpriteFrameCache] destroyInstance -- @param self -------------------------------- -- @function [parent=#SpriteFrameCache] getInstance -- @param self -- @return SpriteFrameCache#SpriteFrameCache ret (return value: cc.SpriteFrameCache) return nil
mit
sundream/gamesrv
script/card/neutral/card266015.lua
1
2221
--<<card 导表开始>> local super = require "script.card.neutral.card166015" ccard266015 = class("ccard266015",super,{ sid = 266015, race = 6, name = "芬克·恩霍尔", type = 202, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 1, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 0, composechip = 0, decomposechip = 0, atk = 3, maxhp = 3, crystalcost = 3, targettype = 0, halo = nil, desc = "None", effect = { onuse = nil, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard266015:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard266015:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard266015:save() local data = super.save(self) -- todo: save data return data end return ccard266015
gpl-2.0
sundream/gamesrv
script/card/fire/card142003.lua
1
2505
--<<card 导表开始>> local super = require "script.card.init" ccard142003 = class("ccard142003",super,{ sid = 142003, race = 4, name = "狂野怒火", type = 101, magic_immune = 0, assault = 0, sneer = 0, atkcnt = 0, shield = 0, warcry = 0, dieeffect = 0, sneak = 0, magic_hurt_adden = 0, cure_to_hurt = 0, recoverhp_multi = 1, magic_hurt_multi = 1, max_amount = 2, composechip = 100, decomposechip = 10, atk = 0, maxhp = 0, crystalcost = 1, targettype = 22, halo = nil, desc = "在本回合内,使1个野兽获得+2攻击和免疫。", effect = { onuse = {addbuff={addatk=2,immune=1,lifecircle=1}}, ondie = nil, onhurt = nil, onrecoverhp = nil, onbeginround = nil, onendround = nil, ondelsecret = nil, onputinwar = nil, onremovefromwar = nil, onaddweapon = nil, onputinhand = nil, before_die = nil, after_die = nil, before_hurt = nil, after_hurt = nil, before_recoverhp = nil, after_recoverhp = nil, before_beginround = nil, after_beginround = nil, before_endround = nil, after_endround = nil, before_attack = nil, after_attack = nil, before_playcard = nil, after_playcard = nil, before_putinwar = nil, after_putinwar = nil, before_removefromwar = nil, after_removefromwar = nil, before_addsecret = nil, after_addsecret = nil, before_delsecret = nil, after_delsecret = nil, before_addweapon = nil, after_addweapon = nil, before_delweapon = nil, after_delweapon = nil, before_putinhand = nil, after_putinhand = nil, before_removefromhand = nil, after_removefromhand = nil, }, }) function ccard142003:init(conf) super.init(self,conf) --<<card 导表结束>> end --导表生成 function ccard142003:load(data) if not data or not next(data) then return end super.load(self,data) -- todo: load data end function ccard142003:save() local data = super.save(self) -- todo: save data return data end function ccard142003:onuse(pos,targetid,choice) local owner = self:getowner() local target = owner:gettarget(targetid) local buff = self:newbuff(ccard142003.effect.onuse.addbuff) target:addbuff(buff) end return ccard142003
gpl-2.0
magnum357i/Magnum-s-Aegisub-Scripts
automation/autoload/mag.translation_status.lua
1
12650
function lang_switch_keys(lang) local in_lang = {} local langs = { [1] = {lang_key = "tr", lang_name = "Türkçe", script_name = "Çeviri Durumu"}, [2] = {lang_key = "en", lang_name = "English", script_name = "Translation Status"} } local lang_list = {} local script_name_list = {} for i = 1, #langs do lang_list[langs[i].lang_key] = langs[i].lang_name script_name_list[langs[i].lang_key] = langs[i].script_name end if lang == langs[1].lang_key then in_lang["module_incompatible"] = "Mag modülünün kurulu sürümü bu lua dosyası ile uyumsuz!\n\nModül dosyasının en az \"%s\" sürümü veya daha üstü gerekiyor.\n\n\nŞimdi indirme sayfasına gitmek ister misiniz?" in_lang["module_not_found"] = "Mag modülü bulunamadı!\n\nBu lua dosyasını kullanmak için Mag modülünü indirip Aegisub programı kapalıyken\n\"Aegisub/automation/include/\" dizinine taşımanız gerekiyor.\n\n\nŞimdi indirme sayfasına gitmek ister misiniz?" in_lang["module_yes"] = "Git" in_lang["module_no"] = "Daha Sonra" in_lang["s_name"] = langs[1].script_name in_lang["s_desc"] = "Çeviri durumunu gösterir." in_lang["buttonKey1"] = "İşaretle" in_lang["buttonKey2"] = "Durum" in_lang["buttonKey3"] = "Kapat" in_lang["buttonKey4"] = "Düşük" in_lang["buttonKey5"] = "Orta" in_lang["buttonKey6"] = "Yüksek" in_lang["buttonKey7"] = "Temizle" in_lang["signtext"] = "çevrilecek" in_lang["guiLabelKey1"] = "İşaret yazısı:" in_lang["percentFormat"] = "{%s}{%s} - %{%s} -> {%s}" in_lang["headerKey1"] = "DURUMUNUZ" in_lang["messageKey1"] = "Düşük" in_lang["messageKey2"] = "Orta" in_lang["messageKey3"] = "Yüksek" in_lang["messageKey4"] = "Tüm satırlar çevrilmiş." in_lang["messageLineFormat"] = "#{%s} - {%s}" in_lang["hintKey1"] = "Olabildiğince eşsiz bir şey girmeye özen gösterin." in_lang["tabKey1"] = "Talimatlar" in_lang["notes"] = "KULLANIM" .."\n1. İşaretle butonuna basın. Uygulanacak satırlara bir işaret koyar." .."\n2. Çevirdikçe bu işaretleri silin veya zorluk seviyesini (düşük, orta, yüksek) değiştirin." .."\n3. Çevrilmemiş satırları görmek için durum butonuna basın." elseif lang == langs[2].lang_key then in_lang["module_incompatible"] = "The installed version of the Mag module is incompatible with this lua file!\n\nAt least \"%s\" version or higher of the module file is required.\n\n\nWould you like to go to the download page now?" in_lang["module_not_found"] = "The module named Mag could not be found!\n\nTo use this file, you need to download the module named mag\nand move it to \"Aegisub/automation/include/\" directory when Aegisub is off.\n\n\nDo you want to go to download page now?" in_lang["module_yes"] = "Go" in_lang["module_no"] = "Later" in_lang["s_name"] = langs[2].script_name in_lang["s_desc"] = "Shows the status of your translation." in_lang["buttonKey1"] = "Mark" in_lang["buttonKey2"] = "Status" in_lang["buttonKey3"] = "Close" in_lang["buttonKey4"] = "Low" in_lang["buttonKey5"] = "Medium" in_lang["buttonKey6"] = "High" in_lang["buttonKey7"] = "Clear" in_lang["signtext"] = "not translated" in_lang["guiLabelKey1"] = "Sign text:" in_lang["percentFormat"] = "{%s}{%s} - %{%s} -> {%s}" in_lang["headerKey1"] = "YOUR STATUS" in_lang["messageKey1"] = "Low" in_lang["messageKey2"] = "Medium" in_lang["messageKey3"] = "High" in_lang["messageKey4"] = "All lines translated" in_lang["messageLineFormat"] = "#{%s} - {%s}" in_lang["hintKey1"] = "Try to enter a unique thing as possible." in_lang["tabKey1"] = "Instructions" in_lang["notes"] = "HOW TO USE?" .."\n1. Click the mark button. Puts a mark on the lines to be apply." .."\n2. Delete these marks or change the difficulty (to low, medium, high) as you translate." .."\n3. Click the status button to view the untranslated lines." end return in_lang, lang_list, script_name_list end c_lang_switch = "en" c_lang, c_lang_list, c_script_name_list = lang_switch_keys(c_lang_switch) script_name = c_lang.s_name script_description = c_lang.s_desc script_version = "1.0.0" script_author = "Magnum357" script_mag_version = "1.1.5.0" script_file_name = "mag.translation_status" script_file_ext = ".lua" include_unicode = true include_clipboard = true include_karaskel = true mag_import, mag = pcall(require, "mag") if mag_import then mag.lang = c_lang_switch c_lock_gui = false c_buttons1 = {c_lang.buttonKey1, c_lang.buttonKey4, c_lang.buttonKey5, c_lang.buttonKey6, c_lang.buttonKey7, c_lang.buttonKey2, c_lang.buttonKey3} c = {} c.comment_mode = true c.empty_mode = true c.apply = mag.window.lang.message("select") c.signtext = c_lang.signtext gui = { main1 = { {class = "label", x = 0, y = 0, width = 1, height = 1, label = c_lang.guiLabelKey1}, signtext = {class = "edit", name = "signtext", x = 1, y = 0, width = 1, height = 1, hint = c_lang.hintKey1}, {class = "label", x = 0, y = 1, width = 1, height = 1, label = mag.window.lang.message("apply")}, apply = {class = "dropdown", name = "apply", x = 1, y = 1, width = 1, height = 1, hint = mag.window.lang.message("style_hint1")}, comment_mode = {class = "checkbox", name = "comment_mode", x = 1, y = 2, width = 1, height = 1, label = mag.window.lang.message("comment_mode")}, empty_mode = {class = "checkbox", name = "empty_mode", x = 1, y = 3, width = 1, height = 1, label = mag.window.lang.message("empty_mode")}, } } end function marklines(subs,sel) local line, index local pcs = false local lines_index = mag.line.index(subs, sel, c.apply, c.comment_mode, c.empty_mode) local signtext_org = c.signtext local signtext_ct = mag.convert.esc(signtext_org) for i = 1, #lines_index do mag.window.progress(i, #lines_index) local cancel = aegisub.progress.is_cancelled() if cancel then break end index = lines_index[i] line = subs[index] if not mag.match(line.text, "{"..signtext_ct..".?.?}") then if not pcs then pcs = true end line.text = line.text.."{"..signtext_org.."}" end if pcs then subs[index] = line end end mag.show.no_op(pcs) end function clearlines(subs,sel) local line, index local pcs = false local lines_index = mag.line.index(subs, sel, mag.window.lang.message("all_lines"), false, c.empty_mode) local signtext_org = c.signtext local signtext_ct = mag.convert.esc(signtext_org) for i = 1, #lines_index do mag.window.progress(i, #lines_index) local cancel = aegisub.progress.is_cancelled() if cancel then break end index = lines_index[i] line = subs[index] if mag.match(line.text, "{"..signtext_ct..".?.?}") then if not pcs then pcs = true end line.text = mag.gsub(line.text, "{"..signtext_ct..".?.?}", "") end if pcs then subs[index] = line end end mag.show.no_op(pcs) end function setlines(subs,sel,mode) local line, index local pcs = false local lines_index = mag.line.index(subs, sel, mag.window.lang.message("selected_lines"), c.comment_mode, c.empty_mode) local signtext_org = c.signtext local signtext_ct = mag.convert.esc(signtext_org) local outputkey = c.signtext if mode == 2 then outputkey = outputkey..":2" end if mode == 3 then outputkey = outputkey..":3" end for i = 1, #lines_index do mag.window.progress(i, #lines_index) local cancel = aegisub.progress.is_cancelled() if cancel then break end index = lines_index[i] line = subs[index] local matched = mag.match(line.text, "{("..signtext_ct..".?.?)}") if matched then if matched ~= outputkey then if not pcs then pcs = true end line.text = mag.gsub(line.text, "{"..mag.convert.esc(matched).."}", "{"..outputkey.."}", 1) end else if not pcs then pcs = true end line.text = line.text.."{"..outputkey.."}" end if pcs then subs[index] = line end end mag.show.no_op(pcs) end function getstatus(subs,sel) local line, index local first_index = mag.index.first(subs) - 1 local pcs = false local lines_index = mag.line.index(subs, sel, c.apply, c.comment_mode, c.empty_mode) local signtext_org = c.signtext local signtext_ct = mag.convert.esc(signtext_org) local counts = {low = 0, medium = 0, high = 0, untranslated = 0} for i = 1, #lines_index do mag.window.progress(i, #lines_index) local cancel = aegisub.progress.is_cancelled() if cancel then break end if not pcs then pcs = true end index = lines_index[i] line = subs[index] local passed = false if mag.match(line.text, "{"..signtext_ct.."}") then counts.untranslated = counts.untranslated + 1 counts.low = counts.low + 1 passed = true elseif mag.match(line.text, "{"..signtext_ct..":2}") then counts.untranslated = counts.untranslated + 1 counts.medium = counts.medium + 1 passed = true elseif mag.match(line.text, "{"..signtext_ct..":3}") then counts.untranslated = counts.untranslated + 1 counts.high = counts.high + 1 passed = true end if passed then mag.show.basic_log(mag.string.format(c_lang.messageLineFormat,index - first_index, mag.strip.all(line.text)).."\n", "nobreak") end end if pcs and counts.untranslated > 0 then mag.show.log("\n\n"..c_lang.headerKey1) for i, key in pairs({"low", "medium", "high"}) do if counts[key] > 0 then local percent = calc_percent(counts[key], counts.untranslated) mag.show.basic_log(mag.string.format(c_lang["percentFormat"], progresschart(percent), counts[key], percent, c_lang["messageKey"..i]), "autobreak") end end else mag.show.log(3, c_lang.messageKey4) end mag.show.no_op(pcs) end function add_macro1(subs, sel) local apply_items = mag.list.full_apply(subs, sel, "comment") c.apply = mag.array.search_apply(apply_items, c.apply) gui.main1.apply.items = apply_items local ok, config repeat mag.config.put(gui.main1) ok, config = mag.window.dialog(gui.main1, c_buttons1) mag.config.take(config) until ok == mag.convert.ascii(c_buttons1[1]) and c.apply ~= mag.window.lang.message("select") or ok ~= mag.convert.ascii(c_buttons1[1]) if ok == mag.convert.ascii(c_buttons1[1]) then marklines(subs, sel) elseif ok == mag.convert.ascii(c_buttons1[2]) then setlines(subs, sel, 1) elseif ok == mag.convert.ascii(c_buttons1[3]) then setlines(subs, sel, 2) elseif ok == mag.convert.ascii(c_buttons1[4]) then setlines(subs, sel, 3) elseif ok == mag.convert.ascii(c_buttons1[5]) then clearlines(subs, sel) elseif ok == mag.convert.ascii(c_buttons1[6]) then getstatus(subs, sel) end end function add_macro2() mag.show.log(c_lang.notes) end function check_macro1(subs,sel) mag.window.task() if c_lock_gui then mag.show.log(1, mag.window.lang.message("restart_aegisub")) else mag.config.get(c) local fe, fee = pcall(add_macro1, subs, sel) mag.window.funce(fe, fee) mag.window.undo_point() mag.config.set(c) end end function progresschart(percent) percent = mag.ceil(percent) local space = "" if mag.n(percent) > 0 then space = " " end return mag.string.wall("▎", percent)..space end function calc_percent(a,b) return mag.gsub((a / b) * 100, "%.(%d%d)%d+", ".%1") end function mag_redirect_gui() local mag_module_link = "https://github.com/magnum357i/Magnum-s-Aegisub-Scripts" local k = aegisub.dialog.display({{class = "label", label = mag_gui_message}}, {c_lang.module_yes, c_lang.module_no}) if k == c_lang.module_yes then os.execute("start "..mag_module_link) end end if mag_import then if mag_module_version:gsub("%.", "") < script_mag_version:gsub("%.", "") then mag_gui_message = string.format(c_lang.module_incompatible, script_mag_version) aegisub.register_macro(script_name, script_desription, mag_redirect_gui) else mag.window.register(script_name.."/"..mag.window.lang.message("gui_tabname"), check_macro1) mag.window.register(script_name.."/"..c_lang.tabKey1, add_macro2) mag.window.lang.register() end else mag_gui_message = c_lang.module_not_found aegisub.register_macro(script_name, script_desription, mag_redirect_gui) end
mit
sami2448/set
plugins/isup.lua
741
3095
do local socket = require("socket") local cronned = load_from_file('data/isup.lua') local function save_cron(msg, url, delete) local origin = get_receiver(msg) if not cronned[origin] then cronned[origin] = {} end if not delete then table.insert(cronned[origin], url) else for k,v in pairs(cronned[origin]) do if v == url then table.remove(cronned[origin], k) end end end serialize_to_file(cronned, 'data/isup.lua') return 'Saved!' end local function is_up_socket(ip, port) print('Connect to', ip, port) local c = socket.try(socket.tcp()) c:settimeout(3) local conn = c:connect(ip, port) if not conn then return false else c:close() return true end end local function is_up_http(url) -- Parse URL from input, default to http local parsed_url = URL.parse(url, { scheme = 'http', authority = '' }) -- Fix URLs without subdomain not parsed properly if not parsed_url.host and parsed_url.path then parsed_url.host = parsed_url.path parsed_url.path = "" end -- Re-build URL local url = URL.build(parsed_url) local protocols = { ["https"] = https, ["http"] = http } local options = { url = url, redirect = false, method = "GET" } local response = { protocols[parsed_url.scheme].request(options) } local code = tonumber(response[2]) if code == nil or code >= 400 then return false end return true end local function isup(url) local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$' local ip,port = string.match(url, pattern) local result = nil -- !isup 8.8.8.8:53 if ip then port = port or '80' result = is_up_socket(ip, port) else result = is_up_http(url) end return result end local function cron() for chan, urls in pairs(cronned) do for k,url in pairs(urls) do print('Checking', url) if not isup(url) then local text = url..' looks DOWN from here. 😱' send_msg(chan, text, ok_cb, false) end end end end local function run(msg, matches) if matches[1] == 'cron delete' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2], true) elseif matches[1] == 'cron' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2]) elseif isup(matches[1]) then return matches[1]..' looks UP from here. 😃' else return matches[1]..' looks DOWN from here. 😱' end end return { description = "Check if a website or server is up.", usage = { "!isup [host]: Performs a HTTP request or Socket (ip:port) connection", "!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)", "!isup cron delete [host]: Disable checking that host." }, patterns = { "^!isup (cron delete) (.*)$", "^!isup (cron) (.*)$", "^!isup (.*)$", "^!ping (.*)$", "^!ping (cron delete) (.*)$", "^!ping (cron) (.*)$" }, run = run, cron = cron } end
gpl-2.0
EvPowerTeam/EV_OP
feeds/packages/lang/luaexpat/files/compat-5.1r5/compat-5.1.lua
251
6391
-- -- Compat-5.1 -- Copyright Kepler Project 2004-2006 (http://www.keplerproject.org/compat) -- According to Lua 5.1 -- $Id: compat-5.1.lua,v 1.22 2006/02/20 21:12:47 carregal Exp $ -- _COMPAT51 = "Compat-5.1 R5" local LUA_DIRSEP = '/' local LUA_OFSEP = '_' local OLD_LUA_OFSEP = '' local POF = 'luaopen_' local LUA_PATH_MARK = '?' local LUA_IGMARK = ':' local assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type = assert, error, getfenv, ipairs, loadfile, loadlib, pairs, setfenv, setmetatable, type local find, format, gfind, gsub, sub = string.find, string.format, string.gfind, string.gsub, string.sub -- -- avoid overwriting the package table if it's already there -- package = package or {} local _PACKAGE = package package.path = LUA_PATH or os.getenv("LUA_PATH") or ("./?.lua;" .. "/usr/local/share/lua/5.0/?.lua;" .. "/usr/local/share/lua/5.0/?/?.lua;" .. "/usr/local/share/lua/5.0/?/init.lua" ) package.cpath = LUA_CPATH or os.getenv("LUA_CPATH") or "./?.so;" .. "./l?.so;" .. "/usr/local/lib/lua/5.0/?.so;" .. "/usr/local/lib/lua/5.0/l?.so" -- -- make sure require works with standard libraries -- package.loaded = package.loaded or {} package.loaded.debug = debug package.loaded.string = string package.loaded.math = math package.loaded.io = io package.loaded.os = os package.loaded.table = table package.loaded.base = _G package.loaded.coroutine = coroutine local _LOADED = package.loaded -- -- avoid overwriting the package.preload table if it's already there -- package.preload = package.preload or {} local _PRELOAD = package.preload -- -- looks for a file `name' in given path -- local function findfile (name, pname) name = gsub (name, "%.", LUA_DIRSEP) local path = _PACKAGE[pname] assert (type(path) == "string", format ("package.%s must be a string", pname)) for c in gfind (path, "[^;]+") do c = gsub (c, "%"..LUA_PATH_MARK, name) local f = io.open (c) if f then f:close () return c end end return nil -- not found end -- -- check whether library is already loaded -- local function loader_preload (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) assert (type(_PRELOAD) == "table", "`package.preload' must be a table") return _PRELOAD[name] end -- -- Lua library loader -- local function loader_Lua (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local filename = findfile (name, "path") if not filename then return false end local f, err = loadfile (filename) if not f then error (format ("error loading module `%s' (%s)", name, err)) end return f end local function mkfuncname (name) name = gsub (name, "^.*%"..LUA_IGMARK, "") name = gsub (name, "%.", LUA_OFSEP) return POF..name end local function old_mkfuncname (name) --name = gsub (name, "^.*%"..LUA_IGMARK, "") name = gsub (name, "%.", OLD_LUA_OFSEP) return POF..name end -- -- C library loader -- local function loader_C (name) assert (type(name) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local filename = findfile (name, "cpath") if not filename then return false end local funcname = mkfuncname (name) local f, err = loadlib (filename, funcname) if not f then funcname = old_mkfuncname (name) f, err = loadlib (filename, funcname) if not f then error (format ("error loading module `%s' (%s)", name, err)) end end return f end local function loader_Croot (name) local p = gsub (name, "^([^.]*).-$", "%1") if p == "" then return end local filename = findfile (p, "cpath") if not filename then return end local funcname = mkfuncname (name) local f, err, where = loadlib (filename, funcname) if f then return f elseif where ~= "init" then error (format ("error loading module `%s' (%s)", name, err)) end end -- create `loaders' table package.loaders = package.loaders or { loader_preload, loader_Lua, loader_C, loader_Croot, } local _LOADERS = package.loaders -- -- iterate over available loaders -- local function load (name, loaders) -- iterate over available loaders assert (type (loaders) == "table", "`package.loaders' must be a table") for i, loader in ipairs (loaders) do local f = loader (name) if f then return f end end error (format ("module `%s' not found", name)) end -- sentinel local sentinel = function () end -- -- new require -- function _G.require (modname) assert (type(modname) == "string", format ( "bad argument #1 to `require' (string expected, got %s)", type(name))) local p = _LOADED[modname] if p then -- is it there? if p == sentinel then error (format ("loop or previous error loading module '%s'", modname)) end return p -- package is already loaded end local init = load (modname, _LOADERS) _LOADED[modname] = sentinel local actual_arg = _G.arg _G.arg = { modname } local res = init (modname) if res then _LOADED[modname] = res end _G.arg = actual_arg if _LOADED[modname] == sentinel then _LOADED[modname] = true end return _LOADED[modname] end -- findtable local function findtable (t, f) assert (type(f)=="string", "not a valid field name ("..tostring(f)..")") local ff = f.."." local ok, e, w = find (ff, '(.-)%.', 1) while ok do local nt = rawget (t, w) if not nt then nt = {} t[w] = nt elseif type(t) ~= "table" then return sub (f, e+1) end t = nt ok, e, w = find (ff, '(.-)%.', e+1) end return t end -- -- new package.seeall function -- function _PACKAGE.seeall (module) local t = type(module) assert (t == "table", "bad argument #1 to package.seeall (table expected, got "..t..")") local meta = getmetatable (module) if not meta then meta = {} setmetatable (module, meta) end meta.__index = _G end -- -- new module function -- function _G.module (modname, ...) local ns = _LOADED[modname] if type(ns) ~= "table" then ns = findtable (_G, modname) if not ns then error (string.format ("name conflict for module '%s'", modname)) end _LOADED[modname] = ns end if not ns._NAME then ns._NAME = modname ns._M = ns ns._PACKAGE = gsub (modname, "[^.]*$", "") end setfenv (2, ns) for i, f in ipairs (arg) do f (ns) end end
gpl-2.0
mortezaand/tgpragramer
isup.lua
741
3095
do local socket = require("socket") local cronned = load_from_file('data/isup.lua') local function save_cron(msg, url, delete) local origin = get_receiver(msg) if not cronned[origin] then cronned[origin] = {} end if not delete then table.insert(cronned[origin], url) else for k,v in pairs(cronned[origin]) do if v == url then table.remove(cronned[origin], k) end end end serialize_to_file(cronned, 'data/isup.lua') return 'Saved!' end local function is_up_socket(ip, port) print('Connect to', ip, port) local c = socket.try(socket.tcp()) c:settimeout(3) local conn = c:connect(ip, port) if not conn then return false else c:close() return true end end local function is_up_http(url) -- Parse URL from input, default to http local parsed_url = URL.parse(url, { scheme = 'http', authority = '' }) -- Fix URLs without subdomain not parsed properly if not parsed_url.host and parsed_url.path then parsed_url.host = parsed_url.path parsed_url.path = "" end -- Re-build URL local url = URL.build(parsed_url) local protocols = { ["https"] = https, ["http"] = http } local options = { url = url, redirect = false, method = "GET" } local response = { protocols[parsed_url.scheme].request(options) } local code = tonumber(response[2]) if code == nil or code >= 400 then return false end return true end local function isup(url) local pattern = '^(%d%d?%d?%.%d%d?%d?%.%d%d?%d?%.%d%d?%d?):?(%d?%d?%d?%d?%d?)$' local ip,port = string.match(url, pattern) local result = nil -- !isup 8.8.8.8:53 if ip then port = port or '80' result = is_up_socket(ip, port) else result = is_up_http(url) end return result end local function cron() for chan, urls in pairs(cronned) do for k,url in pairs(urls) do print('Checking', url) if not isup(url) then local text = url..' looks DOWN from here. 😱' send_msg(chan, text, ok_cb, false) end end end end local function run(msg, matches) if matches[1] == 'cron delete' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2], true) elseif matches[1] == 'cron' then if not is_sudo(msg) then return 'This command requires privileged user' end return save_cron(msg, matches[2]) elseif isup(matches[1]) then return matches[1]..' looks UP from here. 😃' else return matches[1]..' looks DOWN from here. 😱' end end return { description = "Check if a website or server is up.", usage = { "!isup [host]: Performs a HTTP request or Socket (ip:port) connection", "!isup cron [host]: Every 5mins check if host is up. (Requires privileged user)", "!isup cron delete [host]: Disable checking that host." }, patterns = { "^!isup (cron delete) (.*)$", "^!isup (cron) (.*)$", "^!isup (.*)$", "^!ping (.*)$", "^!ping (cron delete) (.*)$", "^!ping (cron) (.*)$" }, run = run, cron = cron } end
gpl-2.0
spark0511/revolt_bot
plugins/channels.lua
356
1732
-- Checks if bot was disabled on specific chat local function is_channel_disabled( receiver ) if not _config.disabled_channels then return false end if _config.disabled_channels[receiver] == nil then return false end return _config.disabled_channels[receiver] end local function enable_channel(receiver) if not _config.disabled_channels then _config.disabled_channels = {} end if _config.disabled_channels[receiver] == nil then return 'Channel isn\'t disabled' end _config.disabled_channels[receiver] = false save_config() return "Channel re-enabled" end local function disable_channel( receiver ) if not _config.disabled_channels then _config.disabled_channels = {} end _config.disabled_channels[receiver] = true save_config() return "Channel disabled" end local function pre_process(msg) local receiver = get_receiver(msg) -- If sender is moderator then re-enable the channel --if is_sudo(msg) then if is_momod(msg) then if msg.text == "!channel enable" then enable_channel(receiver) end end if is_channel_disabled(receiver) then msg.text = "" end return msg end local function run(msg, matches) local receiver = get_receiver(msg) -- Enable a channel if matches[1] == 'enable' then return enable_channel(receiver) end -- Disable a channel if matches[1] == 'disable' then return disable_channel(receiver) end end return { description = "Plugin to manage channels. Enable or disable channel.", usage = { "!channel enable: enable current channel", "!channel disable: disable current channel" }, patterns = { "^!channel? (enable)", "^!channel? (disable)" }, run = run, --privileged = true, moderated = true, pre_process = pre_process }
gpl-2.0
weera00/nodemcu-firmware
lua_modules/email/imap.lua
81
6275
--- -- Working Example: https://www.youtube.com/watch?v=PDxTR_KJLhc -- IMPORTANT: run node.compile("imap.lua") after uploading this script -- to create a compiled module. Then run file.remove("imap.lua") -- @name imap -- @description An IMAP 4rev1 module that can be used to read email. -- Tested on NodeMCU 0.9.5 build 20150213. -- @date March 12, 2015 -- @author Miguel -- GitHub: https://github.com/AllAboutEE -- YouTube: https://www.youtube.com/user/AllAboutEE -- Website: http://AllAboutEE.com -- -- Visit the following URLs to learn more about IMAP: -- "How to test an IMAP server by using telnet" http://www.anta.net/misc/telnet-troubleshooting/imap.shtml -- "RFC 2060 - Internet Message Access Protocol - Version 4rev1" http://www.faqs.org/rfcs/rfc2060.html ------------------------------------------------------------------------------------------------------------- local moduleName = ... local M = {} _G[moduleName] = M local USERNAME = "" local PASSWORD = "" local SERVER = "" local PORT = "" local TAG = "" local DEBUG = false local body = "" -- used to store an email's body / main text local header = "" -- used to store an email's last requested header field e.g. SUBJECT, FROM, DATA etc. local most_recent_num = 1 -- used to store the latest/newest email number/id local response_processed = false -- used to know if the last IMAP response has been processed --- -- @name response_processed -- @returns The response process status of the last IMAP command sent function M.response_processed() return response_processed end --- -- @name display -- @description A generic IMAP response processing function. -- Can disply the IMAP response if DEBUG is set to true. -- Sets the reponse processed variable to true when the string "complete" -- is found in the IMAP reply/response local function display(socket, response) -- If debuggins is enabled print the IMAP response if(DEBUG) then print(response) end -- Some IMAP responses are long enough that they will cause the display -- function to be called several times. One thing is certain, IMAP will replay with -- "<tag> OK <command> complete" when it's done sending data back. if(string.match(response,'complete') ~= nil) then response_processed = true end end --- -- @name config -- @description Initiates the IMAP settings function M.config(username,password,tag,debug) USERNAME = username PASSWORD = password TAG = tag DEBUG = debug end --- -- @name login -- @descrpiton Logs into a new email session function M.login(socket) response_processed = false -- we are sending a new command -- which means that the response for it has not been processed socket:send(TAG .. " LOGIN " .. USERNAME .. " " .. PASSWORD .. "\r\n") socket:on("receive",display) end --- -- @name get_most_recent_num -- @returns The most recent email number. Should only be called after examine() function M.get_most_recent_num() return most_recent_num end --- -- @name set_most_recent_num -- @description Gets the most recent email number from the EXAMINE command. -- i.e. if EXAMINE returns "* 4 EXISTS" this means that there are 4 emails, -- so the latest/newest will be identified by the number 4 local function set_most_recent_num(socket,response) if(DEBUG) then print(response) end local _, _, num = string.find(response,"([0-9]+) EXISTS(\.)") -- the _ and _ keep the index of the string found -- but we don't care about that. if(num~=nil) then most_recent_num = num end if(string.match(response,'complete') ~= nil) then response_processed = true end end --- -- @name examine -- @description IMAP examines the given mailbox/folder. Sends the IMAP EXAMINE command function M.examine(socket,mailbox) response_processed = false socket:send(TAG .. " EXAMINE " .. mailbox .. "\r\n") socket:on("receive",set_most_recent_num) end --- -- @name get_header -- @returns The last fetched header field function M.get_header() return header end --- -- @name set_header -- @description Records the IMAP header field response in a variable -- so that it may be read later local function set_header(socket,response) if(DEBUG) then print(response) end header = header .. response if(string.match(response,'complete') ~= nil) then response_processed = true end end --- -- @name fetch_header -- @description Fetches an emails header field e.g. SUBJECT, FROM, DATE -- @param socket The IMAP socket to use -- @param msg_number The email number to read e.g. 1 will read fetch the latest/newest email -- @param field A header field such as SUBJECT, FROM, or DATE function M.fetch_header(socket,msg_number,field) header = "" -- we are getting a new header so clear this variable response_processed = false socket:send(TAG .. " FETCH " .. msg_number .. " BODY[HEADER.FIELDS (" .. field .. ")]\r\n") socket:on("receive",set_header) end --- -- @name get_body -- @return The last email read's body function M.get_body() return body end --- -- @name set_body -- @description Records the IMAP body response in a variable -- so that it may be read later local function set_body(socket,response) if(DEBUG) then print(response) end body = body .. response if(string.match(response,'complete') ~= nil) then response_processed = true end end --- -- @name fetch_body_plain_text -- @description Sends the IMAP command to fetch a plain text version of the email's body -- @param socket The IMAP socket to use -- @param msg_number The email number to obtain e.g. 1 will obtain the latest email function M.fetch_body_plain_text(socket,msg_number) response_processed = false body = "" -- clear the body variable since we'll be fetching a new email socket:send(TAG .. " FETCH " .. msg_number .. " BODY[1]\r\n") socket:on("receive",set_body) end --- -- @name logout -- @description Sends the IMAP command to logout of the email session function M.logout(socket) response_processed = false socket:send(TAG .. " LOGOUT\r\n") socket:on("receive",display) end
mit
jxskiss/orange
orange/orange.lua
3
5265
local ipairs = ipairs local table_insert = table.insert local table_sort = table.sort local pcall = pcall local require = require require("orange.lib.globalpatches")() local utils = require("orange.utils.utils") local config_loader = require("orange.utils.config_loader") local dao = require("orange.store.dao") local HEADERS = { PROXY_LATENCY = "X-Orange-Proxy-Latency", UPSTREAM_LATENCY = "X-Orange-Upstream-Latency", } local loaded_plugins = {} local function load_node_plugins(config, store) ngx.log(ngx.DEBUG, "Discovering used plugins") local sorted_plugins = {} local plugins = config.plugins for _, v in ipairs(plugins) do local loaded, plugin_handler = utils.load_module_if_exists("orange.plugins." .. v .. ".handler") if not loaded then ngx.log(ngx.WARN, "The following plugin is not installed or has no handler: " .. v) else ngx.log(ngx.DEBUG, "Loading plugin: " .. v) table_insert(sorted_plugins, { name = v, handler = plugin_handler(store), }) end end table_sort(sorted_plugins, function(a, b) local priority_a = a.handler.PRIORITY or 0 local priority_b = b.handler.PRIORITY or 0 return priority_a > priority_b end) return sorted_plugins end -- ms local function now() return ngx.now() * 1000 end -- ########################### Orange ############################# local Orange = {} -- 执行过程: -- 加载配置 -- 实例化存储store -- 加载插件 -- 插件排序 function Orange.init(options) options = options or {} local store, config local status, err = pcall(function() local conf_file_path = options.config config = config_loader.load(conf_file_path) store = require("orange.store.mysql_store")(config.store_mysql) loaded_plugins = load_node_plugins(config, store) ngx.update_time() config.orange_start_at = ngx.now() end) if not status or err then ngx.log(ngx.ERR, "Startup error: " .. err) os.exit(1) end Orange.data = { store = store, config = config } return config, store end function Orange.init_worker() -- 仅在 init_worker 阶段调用,初始化随机因子,仅允许调用一次 math.randomseed() -- 初始化定时器,清理计数器等 if Orange.data and Orange.data.store and Orange.data.config.store == "mysql" then local worker_id = ngx.worker.id() if worker_id == 0 then local ok, err = ngx.timer.at(0, function(premature, store, config) local available_plugins = config.plugins for _, v in ipairs(available_plugins) do local load_success = dao.load_data_by_mysql(store, v) if not load_success then os.exit(1) end end end, Orange.data.store, Orange.data.config) if not ok then ngx.log(ngx.ERR, "failed to create the timer: ", err) return os.exit(1) end end end for _, plugin in ipairs(loaded_plugins) do plugin.handler:init_worker() end end function Orange.redirect() ngx.ctx.ORANGE_REDIRECT_START = now() for _, plugin in ipairs(loaded_plugins) do plugin.handler:redirect() end local now_time = now() ngx.ctx.ORANGE_REDIRECT_TIME = now_time - ngx.ctx.ORANGE_REDIRECT_START ngx.ctx.ORANGE_REDIRECT_ENDED_AT = now_time end function Orange.rewrite() ngx.ctx.ORANGE_REWRITE_START = now() for _, plugin in ipairs(loaded_plugins) do plugin.handler:rewrite() end local now_time = now() ngx.ctx.ORANGE_REWRITE_TIME = now_time - ngx.ctx.ORANGE_REWRITE_START ngx.ctx.ORANGE_REWRITE_ENDED_AT = now_time end function Orange.access() ngx.ctx.ORANGE_ACCESS_START = now() for _, plugin in ipairs(loaded_plugins) do plugin.handler:access() end local now_time = now() ngx.ctx.ORANGE_ACCESS_TIME = now_time - ngx.ctx.ORANGE_ACCESS_START ngx.ctx.ORANGE_ACCESS_ENDED_AT = now_time ngx.ctx.ORANGE_PROXY_LATENCY = now_time - ngx.req.start_time() * 1000 ngx.ctx.ACCESSED = true end function Orange.header_filter() if ngx.ctx.ACCESSED then local now_time = now() ngx.ctx.ORANGE_WAITING_TIME = now_time - ngx.ctx.ORANGE_ACCESS_ENDED_AT -- time spent waiting for a response from upstream ngx.ctx.ORANGE_HEADER_FILTER_STARTED_AT = now_time end for _, plugin in ipairs(loaded_plugins) do plugin.handler:header_filter() end if ngx.ctx.ACCESSED then ngx.header[HEADERS.UPSTREAM_LATENCY] = ngx.ctx.ORANGE_WAITING_TIME ngx.header[HEADERS.PROXY_LATENCY] = ngx.ctx.ORANGE_PROXY_LATENCY end end function Orange.body_filter() for _, plugin in ipairs(loaded_plugins) do plugin.handler:body_filter() end if ngx.ctx.ACCESSED then ngx.ctx.ORANGE_RECEIVE_TIME = now() - ngx.ctx.ORANGE_HEADER_FILTER_STARTED_AT end end function Orange.log() for _, plugin in ipairs(loaded_plugins) do plugin.handler:log() end end return Orange
mit
sev-/scummvm
devtools/create_ultima/files/ultima6/scripts/md/init.lua
18
10512
local lua_file = nil --load common functions lua_file = nuvie_load("common/common.lua"); lua_file(); OBJLIST_OFFSET_HOURS_TILL_NEXT_HEALING = 0x1cf2 OBJLIST_OFFSET_PREV_PLAYER_X = 0x1d03 OBJLIST_OFFSET_PREV_PLAYER_Y = 0x1d04 OBJLIST_OFFSET_1D22_UNK = 0x1d22 OBJLIST_OFFSET_DREAM_MODE_FLAG = 0x1d29 OBJLIST_OFFSET_BERRY_COUNTERS = 0x1d2f OBJLIST_OFFSET_DREAM_STAGE = 0x1d53 function dbg(msg_string) --io.stderr:write(msg_string) end g_hours_till_next_healing = 0 g_in_dream_mode = false local g_selected_obj local g_attack_target function update_watch_tile() local anim_index = get_anim_index_for_tile(616) --616 = watch tile if anim_index ~= nil then local new_watch_tile = 416 + clock_get_hour() % 12 anim_set_first_frame(anim_index, new_watch_tile) end end function load_game() g_selected_obj = nil g_attack_target = nil objlist_seek(OBJLIST_OFFSET_HOURS_TILL_NEXT_HEALING) g_hours_till_next_healing = objlist_read1() objlist_seek(OBJLIST_OFFSET_DREAM_MODE_FLAG) g_in_dream_mode = bit32.btest(objlist_read2(), 0x10) map_enable_temp_actor_cleaning(not g_in_dream_mode) if g_in_dream_mode then lock_inventory_view(Actor.get(0)) end objlist_seek(OBJLIST_OFFSET_DREAM_STAGE) g_current_dream_stage = objlist_read2() objlist_seek(OBJLIST_OFFSET_PREV_PLAYER_X) g_prev_player_x = objlist_read1() objlist_seek(OBJLIST_OFFSET_PREV_PLAYER_Y) g_prev_player_y = objlist_read1() objlist_seek(OBJLIST_OFFSET_1D22_UNK) g_objlist_1d22_unk = objlist_read1() update_watch_tile() end function save_game() objlist_seek(OBJLIST_OFFSET_HOURS_TILL_NEXT_HEALING) objlist_write1(g_hours_till_next_healing) objlist_seek(OBJLIST_OFFSET_DREAM_MODE_FLAG) local bytes = objlist_read2() if g_in_dream_mode then bytes = bit32.bor(bytes, 0x10) else bytes = bit32.band(bytes, 0xFFEF) end objlist_seek(OBJLIST_OFFSET_DREAM_MODE_FLAG) objlist_write2(bytes) objlist_seek(OBJLIST_OFFSET_DREAM_STAGE) objlist_write2(g_current_dream_stage) objlist_seek(OBJLIST_OFFSET_PREV_PLAYER_X) objlist_write1(g_prev_player_x) objlist_seek(OBJLIST_OFFSET_PREV_PLAYER_Y) objlist_write1(g_prev_player_y) objlist_seek(OBJLIST_OFFSET_1D22_UNK) objlist_write1(g_objlist_1d22_unk) end local g_container_obj_tbl = { [80]=1, [81]=1, [82]=1, [83]=1, [85]=1, [86]=1, [87]=1, [89]=1,[304]=1, [139]=1,[341]=1,[257]=1, [104]=1,[284]=1,[285]=1 } function is_blood(obj_num) if obj_num == 334 or obj_num == 335 or obj_num == 336 then --OBJ_BLOOD, OBJ_ICHOR, OBJ_SAP return true end return false end function is_container_obj(obj_num) if g_container_obj_tbl[obj_num] ~= nil then return true end return false end --OBJ_CLOSED_DOOR, OBJ_GLOW_WORM, OBJ_DEVIL_POD, OBJ_DEVIL_PLANT, OBJ_GLASS_PITCHER local attackable_obj_tbl = { [0xB3]=1, [0x184]=1, [0x133]=1, [0x12C]=1, [0xD9]=1, } function is_obj_attackable(obj) return attackable_obj_tbl[obj.obj_n] ~= nil end --OBJ_VINE, OBJ_TREE, OBJ_PORCUPOD, OBJ_FLOWER, OBJ_HARD_SHELLED_PLANT --OBJ_DEVIL_PLANT, OBJ_DEVIL_POD, OBJ_HEDGE local plant_obj_tbl = { [0xCD]=1, [0x198]=1, [0xA8]=1, [0xAA]=1, [0xAB]=1, [0x12C]=1, [0x133]=1, [0x12B]=1, } function is_plant_obj(obj) return plant_obj_tbl[obj.obj_n] ~= nil end --OBJ_DOLLAR, OBJ_RUBLE, OBJ_PHOTOGRAPH, OBJ_THREAD, OBJ_BOX_OF_CIGARS --OBJ_MATCH, OBJ_BOOK, OBJ_MAP, OBJ_NOTE, OBJ_WORMSBANE_SEED --OBJ_SCROLL, OBJ_LIVE_MARTIAN_SEED, OBJ_PILE_OF_COAL --OBJ_HUGE_LUMP_OF_COAL, OBJ_CHUNK_OF_ICE local burnable_obj_tbl = { [0x18]=1, [0x84]=1, [0x0B9]=1, [0x3E]=1, [0x65]=1, [0x6B]=1, [0x94]=1, [0x96]=1, [0x97]=1, [0x9E]=1, [0x0F3]=1, [0x0FC]=1, [0x1BC]=1, [0x1BF]=1, [0x100]=1, } function is_obj_burnable(obj) return burnable_obj_tbl[obj.obj_n] ~= nil end function is_open_water_at_loc(x, y, z) local tile_num = map_get_tile_num(x, y, z) local is_water = tile_get_flag(tile_num, 1, 0) if not is_water then return false end if not tile_get_flag(tile_num, 1, 1) then -- not blocked return false end for obj in objs_at_loc(location) do tile_num = obj.tile_num --FIXME original does this too -- sub ax, word_40FA2 if tile_get_flag(tile_num, 3, 1) or tile_get_flag(tile_num, 3, 2) then --SUPPORT_OBJECT or FORCE_PASSABLE return false end end return true end function search(obj) if obj.on_map == false then return end local found_obj = false local child local first_loop = true local prev_obj = nil for child in container_objs(obj) do if prev_obj ~= nil then printfl("SEARCH_NEXT_OBJ", prev_obj.look_string) Obj.moveToMap(prev_obj, obj.x, obj.y, obj.z) end if first_loop == true then found_obj = true printfl("SEARCHING_HERE_YOU_FIND", child.look_string) Obj.moveToMap(child, obj.x, obj.y, obj.z) else prev_obj = child end script_wait(50) first_loop = false end if prev_obj ~= nil then printfl("SEARCH_LAST_OBJ", prev_obj.look_string) Obj.moveToMap(prev_obj, obj.x, obj.y, obj.z) end if found_obj == false then printl("SEARCHING_HERE_YOU_FIND_NOTHING") else print(".\n") end end --tile_num, readied location local g_readiable_objs_tbl = { -- 0 = head [512] = 0, --cap [513] = 0, --cowboy hat [514] = 0, --pith hat [515] = 0, --military hat [516] = 0, --derby -- 1 = neck [517] = 1, --kerchief [518] = 1, --silk scarf [519] = 1, --muffler [1048] = 1, --martian jewelry [1049] = 1, --martian jewelry [1050] = 1, --martian jewelry [1051] = 1, --martian jewelry [1052] = 1, --martian jewelry [1053] = 1, --martian jewelry [1054] = 1, --martian jewelry [1055] = 1, --martian jewelry -- 3 = 1 handed [527] = 3, --bloody saber [552] = 3, --derringer [553] = 3, --revolver [560] = 3, --hatchet [561] = 3, --axe [562] = 3, --ball-peen hammer [565] = 3, --knife [566] = 3, --machete [567] = 3, --saber [622] = 3, --pry bar [650] = 3, --weed sprayer [667] = 3, --tongs [1068] = 3, --martian ritual pod knife -- 2 = torso [528] = 2, --cloth jacket [529] = 2, --wool sweater [530] = 2, --cape [531] = 2, --duster [532] = 2, --wool overcoat [533] = 2, --sheepskin jacket [534] = 2, --artic parka [608] = 2, --electric belt -- 3 = shield hand [630] = 3, --torch [631] = 3, --lit torch [632] = 3, --candlestick [633] = 3, --lit candlestick [634] = 3, --candelabra [635] = 3, --lit candelabra [636] = 3, --oil lamp [637] = 3, --lit oil lamp [638] = 3, --lantern [639] = 3, --lit lantern -- 6 = UNK pants or dress FIXME: putting this here for now [536] = 6, --cotton pants [537] = 6, --cotton dress [538] = 6, --denim jeans [539] = 6, --wool pants [540] = 6, --wool dress [541] = 6, --chaps and jeans -- 7 = feet [520] = 7, --man's shoes [521] = 7, --woman's shoes [522] = 7, --riding boots [523] = 7, --ruby slippers [524] = 7, --thigh boots [525] = 7, --hip boots [526] = 7, --winged shoes [542] = 7, --man's shoes -- 4 = two handed [551] = 4, --Cupid's bow and arrows [554] = 4, --shotgun [555] = 4, --rifle [556] = 4, --Belgian combine [557] = 4, --elephant gun [558] = 4, --sling [559] = 4, --bow [563] = 4, --sledge hammer [576] = 4, --pick [577] = 4, --shovel [578] = 4, --hoe [579] = 4, --rake [580] = 4, --pitchfork [581] = 4, --cultivator [582] = 4, --scythe [583] = 4, --saw [717] = 4, --throw rug [718] = 4, --red cape [1066] = 4, --heat ray gun [1067] = 4, --freeze ray gun [1093] = 4, --spray gun [1095] = 4, --martian hoe (couldn't be equipped in original) [1096] = 4, --martian scythe (couldn't be equipped in original) [1097] = 4, --martian pitchfork (couldn't be equipped in original) [1098] = 4, --martian rake (couldn't be equipped in original) [1099] = 4, --martian shovel (couldn't be equipped in original) [1188] = 4, --M60 machine gun [1206] = 4, --martian pick (couldn't be equipped in original) [1897] = 4, --pool cue -- 5 = finger gloves and bracelets FIXME: putting this here for now [544] = 5, --lady's silk gloves [545] = 5, --driving gloves [546] = 5, --cotton work gloves [547] = 5, --work gloves [548] = 5, --wool mittens [549] = 5, --rubber gloves [550] = 5 --welding gloves } function wrap_coord(coord, level) local map_stride = 1024 if level ~= 0 then map_stride = 256 end if coord < 0 then return map_stride + coord end return coord % map_stride end function can_move_obj(obj, rel_x, rel_y) local z = obj.z return map_can_put_obj(wrap_coord(obj.x+rel_x,z), wrap_coord(obj.y+rel_y,z), z) end function obj_get_readiable_location(obj) if g_readiable_objs_tbl[obj.tile_num] ~= nil then return g_readiable_objs_tbl[obj.tile_num] end return -1 end function update_lamp_posts() --Turn lamps on/off if we have power and it is dark. local frame_n = 3 local hour = clock_get_hour() if Actor.get_talk_flag(0x73, 4) and (hour < 6 or hour > 17) then frame_n = 7 end local loc = player_get_location() for obj in find_obj(loc.z, 228) do --OBJ_LAMP_POST if obj ~= nil then obj.frame_n = frame_n end end end local PLAY_ASYNC = true function play_md_sfx(sfx_id, play_async) --FIXME end function play_door_sfx() --FIXME end function create_object_needs_quan(obj_n) -- obj.stackable is already checked if obj_n == 196 or obj_n == 311 or obj_n == 312 then --OBJ_LEVER, OBJ_SWITCH, OBJ_SWITCH1 return true else return false end end function input_select_obj_qty(obj) if not obj.stackable then return 1 end printl("HOW_MANY") local qty = input_select_integer("0123456789", true) if qty > obj.qty then return obj.qty end return qty end --load actor functions local actor_load = nuvie_load("md/actor.lua"); if type(actor_load) == "function" then actor_load() else if type(actor_load) == "string" then --io.stderr:write(actor_load); end end look_init = nuvie_load("md/look.lua"); look_init(); combat_init = nuvie_load("md/combat.lua"); combat_init(); -- init usecode usecode_init = nuvie_load("md/usecode.lua"); usecode_init(); talk_init = nuvie_load("md/talk.lua"); talk_init(); player_init = nuvie_load("md/player.lua"); player_init(); worktype_init = nuvie_load("md/worktype.lua"); worktype_init(); dreamworld_init = nuvie_load("md/dreamworld.lua"); dreamworld_init();
gpl-3.0
rastin45/waqer12
plugins/torrent_search.lua
411
1622
--[[ NOT USED DUE TO SSL ERROR -- See https://getstrike.net/api/ local function strike_search(query) local strike_base = 'http://getstrike.net/api/v2/torrents/' local url = strike_base..'search/?phrase='..URL.escape(query) print(url) local b,c = http.request(url) print(b,c) local search = json:decode(b) vardump(search) if c ~= 200 then return search.message end vardump(search) local results = search.results local text = 'Results: '..results local results = math.min(results, 3) for i=1,results do local torrent = search.torrents[i] text = text..torrent.torrent_title ..'\n'..'Seeds: '..torrent.seeds ..' '..'Leeches: '..torrent.seeds ..'\n'..torrent.magnet_uri..'\n\n' end return text end]]-- local function search_kickass(query) local url = 'http://kat.cr/json.php?q='..URL.escape(query) local b,c = http.request(url) local data = json:decode(b) local text = 'Results: '..data.total_results..'\n\n' local results = math.min(#data.list, 5) for i=1,results do local torrent = data.list[i] local link = torrent.torrentLink link = link:gsub('%?title=.+','') text = text..torrent.title ..'\n'..'Seeds: '..torrent.seeds ..' '..'Leeches: '..torrent.leechs ..'\n'..link --..'\n magnet:?xt=urn:btih:'..torrent.hash ..'\n\n' end return text end local function run(msg, matches) local query = matches[1] return search_kickass(query) end return { description = "Search Torrents", usage = "!torrent <search term>: Search for torrent", patterns = { "^!torrent (.+)$" }, run = run }
gpl-2.0
BrokenROM/external_skia
resources/slides.lua
68
9898
gShowBounds = false gUseBlurInTransitions = false gPath = "/skia/trunk/resources/" function load_file(file) local prev_path = package.path package.path = package.path .. ";" .. gPath .. file .. ".lua" require(file) package.path = prev_path end load_file("slides_utils") gSlides = parse_file(io.open("/skia/trunk/resources/slides_content2.lua", "r")) function make_rect(l, t, r, b) return { left = l, top = t, right = r, bottom = b } end function make_paint(typefacename, stylebits, size, color) local paint = Sk.newPaint(); paint:setAntiAlias(true) paint:setSubpixelText(true) paint:setTypeface(Sk.newTypeface(typefacename, stylebits)) paint:setTextSize(size) paint:setColor(color) return paint end function draw_bullet(canvas, x, y, paint, indent) if 0 == indent then return end local ps = paint:getTextSize() local cx = x - ps * .8 local cy = y - ps * .4 local radius = ps * .2 canvas:drawCircle(cx, cy, radius, paint) end function stroke_rect(canvas, rect, color) local paint = Sk.newPaint() paint:setStroke(true); paint:setColor(color) canvas:drawRect(rect, paint) end function drawSlide(canvas, slide, master_template) if #slide == 1 then template = master_template.title canvas:drawText(slide[1].text, 320, 240, template[1]) return end template = master_template.slide local x = template.margin_x local y = template.margin_y local scale = 1.25 if slide.blockstyle == "code" then local paint = master_template.codePaint local fm = paint:getFontMetrics() local height = #slide * (fm.descent - fm.ascent) y = (480 - height) / 2 for i = 1, #slide do local node = slide[i] y = y - fm.ascent * scale canvas:drawText(node.text, x, y, paint) y = y + fm.descent * scale end return end for i = 1, #slide do local node = slide[i] local paint = template[node.indent + 1].paint local extra_dy = template[node.indent + 1].extra_dy local fm = paint:getFontMetrics() local x_offset = -fm.ascent * node.indent * 1.25 local bounds = make_rect(x + x_offset, y, 620, 640) local blob, newBottom = Sk.newTextBlob(node.text, bounds, paint) draw_bullet(canvas, x + x_offset, y - fm.ascent, paint, node.indent) canvas:drawTextBlob(blob, 0, 0, paint) y = newBottom + paint:getTextSize() * .5 + extra_dy if gShowBounds then bounds.bottom = newBottom stroke_rect(canvas, bounds, {a=1,r=0,g=1,b=0}) stroke_rect(canvas, blob:bounds(), {a=1,r=1,g=0,b=0}) end end end -------------------------------------------------------------------------------------- function make_tmpl(paint, extra_dy) return { paint = paint, extra_dy = extra_dy } end function SkiaPoint_make_template() local title = { margin_x = 30, margin_y = 100, } title[1] = make_paint("Arial", 1, 45, { a=1, r=1, g=1, b=1 }) title[1]:setTextAlign("center") title[2] = make_paint("Arial", 1, 25, { a=1, r=.75, g=.75, b=.75 }) title[2]:setTextAlign("center") local slide = { margin_x = 20, margin_y = 25, } slide[1] = make_tmpl(make_paint("Arial", 1, 35, { a=1, r=1, g=1, b=1 }), 18) slide[2] = make_tmpl(make_paint("Arial", 0, 25, { a=1, r=1, g=1, b=1 }), 10) slide[3] = make_tmpl(make_paint("Arial", 0, 20, { a=1, r=.9, g=.9, b=.9 }), 5) return { title = title, slide = slide, codePaint = make_paint("Courier", 0, 20, { a=1, r=.9, g=.9, b=.9 }), } end gTemplate = SkiaPoint_make_template() gRedPaint = Sk.newPaint() gRedPaint:setAntiAlias(true) gRedPaint:setColor{a=1, r=1, g=0, b=0 } -- animation.proc is passed the canvas before drawing. -- The animation.proc returns itself or another animation (which means keep animating) -- or it returns nil, which stops the animation. -- local gCurrAnimation gSlideIndex = 1 ----------------------------------------------------------------------------- function new_drawable_picture(pic) return { picture = pic, width = pic:width(), height = pic:height(), draw = function (self, canvas, x, y, paint) canvas:drawPicture(self.picture, x, y, paint) end } end function new_drawable_image(img) return { image = img, width = img:width(), height = img:height(), draw = function (self, canvas, x, y, paint) canvas:drawImage(self.image, x, y, paint) end } end function convert_to_picture_drawable(slide) local rec = Sk.newPictureRecorder() drawSlide(rec:beginRecording(640, 480), slide, gTemplate) return new_drawable_picture(rec:endRecording()) end function convert_to_image_drawable(slide) local surf = Sk.newRasterSurface(640, 480) drawSlide(surf:getCanvas(), slide, gTemplate) return new_drawable_image(surf:newImageSnapshot()) end function new_drawable_slide(slide) return { slide = slide, draw = function (self, canvas, x, y, paint) if (nil == paint or ("number" == type(paint) and (1 == paint))) then canvas:save() else canvas:saveLayer(paint) end canvas:translate(x, y) drawSlide(canvas, self.slide, gTemplate) canvas:restore() end } end gNewDrawableFactory = { default = new_drawable_slide, picture = convert_to_picture_drawable, image = convert_to_image_drawable, } ----------------------------------------------------------------------------- function next_slide() local prev = gSlides[gSlideIndex] if gSlideIndex < #gSlides then gSlideIndex = gSlideIndex + 1 spawn_transition(prev, gSlides[gSlideIndex], true) end end function prev_slide() local prev = gSlides[gSlideIndex] if gSlideIndex > 1 then gSlideIndex = gSlideIndex - 1 spawn_transition(prev, gSlides[gSlideIndex], false) end end gDrawableType = "default" load_file("slides_transitions") function spawn_transition(prevSlide, nextSlide, is_forward) local transition if is_forward then transition = gTransitionTable[nextSlide.transition] else transition = gTransitionTable[prevSlide.transition] end if not transition then transition = fade_slide_transition end local prevDrawable = gNewDrawableFactory[gDrawableType](prevSlide) local nextDrawable = gNewDrawableFactory[gDrawableType](nextSlide) gCurrAnimation = transition(prevDrawable, nextDrawable, is_forward) end -------------------------------------------------------------------------------------- function spawn_rotate_animation() gCurrAnimation = { angle = 0, angle_delta = 5, pivot_x = 320, pivot_y = 240, proc = function (self, canvas, drawSlideProc) if self.angle >= 360 then drawSlideProc(canvas) return nil end canvas:translate(self.pivot_x, self.pivot_y) canvas:rotate(self.angle) canvas:translate(-self.pivot_x, -self.pivot_y) drawSlideProc(canvas) self.angle = self.angle + self.angle_delta return self end } end function spawn_scale_animation() gCurrAnimation = { scale = 1, scale_delta = .95, scale_limit = 0.2, pivot_x = 320, pivot_y = 240, proc = function (self, canvas, drawSlideProc) if self.scale < self.scale_limit then self.scale = self.scale_limit self.scale_delta = 1 / self.scale_delta end if self.scale > 1 then drawSlideProc(canvas) return nil end canvas:translate(self.pivot_x, self.pivot_y) canvas:scale(self.scale, self.scale) canvas:translate(-self.pivot_x, -self.pivot_y) drawSlideProc(canvas) self.scale = self.scale * self.scale_delta return self end } end local bgPaint = nil function draw_bg(canvas) if not bgPaint then bgPaint = Sk.newPaint() local grad = Sk.newLinearGradient( 0, 0, { a=1, r=0, g=0, b=.3 }, 640, 480, { a=1, r=0, g=0, b=.8 }) bgPaint:setShader(grad) bgPaint:setDither(true) end canvas:drawPaint(bgPaint) end function onDrawContent(canvas, width, height) local matrix = Sk.newMatrix() matrix:setRectToRect(make_rect(0, 0, 640, 480), make_rect(0, 0, width, height), "center") canvas:concat(matrix) draw_bg(canvas) local drawSlideProc = function(canvas) drawSlide(canvas, gSlides[gSlideIndex], gTemplate) end if gCurrAnimation then gCurrAnimation = gCurrAnimation:proc(canvas, drawSlideProc) return true else drawSlideProc(canvas) return false end end function onClickHandler(x, y) return false end local keyProcs = { n = next_slide, p = prev_slide, r = spawn_rotate_animation, s = spawn_scale_animation, ["="] = function () scale_text_delta(gTemplate, 1) end, ["-"] = function () scale_text_delta(gTemplate, -1) end, b = function () gShowBounds = not gShowBounds end, B = function () gUseBlurInTransitions = not gUseBlurInTransitions end, ["1"] = function () gDrawableType = "default" end, ["2"] = function () gDrawableType = "picture" end, ["3"] = function () gDrawableType = "image" end, } function onCharHandler(uni) local proc = keyProcs[uni] if proc then proc() return true end return false end
bsd-3-clause
rm-code/PZ-UI-Overhaul
pzuioverhaul/media/lua/client/uio/BaseElement.lua
1
7485
-- TODO These MUST go elsewhere TODO -- These are hotfixes for missing functionality in Kahlua if table.pack == nil then table.pack = function(...) return { n = select("#", ...), ... } end end if table.unpack == nil then table.unpack = function(t, i) i = i or 1; if t[i] then return t[i], unpack(t, i + 1) end end end UIO = {}; UIO.maxID = -1; UIO.BaseElement = {}; function UIO.BaseElement.new(px, py, pw, ph) local self = {}; local jObj = {}; local parent = nil; local children = {}; local ID = UIO.maxID + 1; UIO.maxID = ID; local joyPadFocus = nil; local mouseOver = false; local MIN_X = -1; local MIN_Y = -1; local MAX_X = -1; --getCore():getScreenWidth(); local MAX_Y = -1; --getCore():getScreenHeight(); local x = px; local y = py; local w = pw; local h = ph; -- ------------------------------------------------ -- Local Functions -- ------------------------------------------------ local function clamp(min, val, max) -- {{{ clamp value to valid range return math.max(min, math.min(val, max)); end -- }}} -- ------------------------------------------------ -- Public Functions -- ------------------------------------------------ function self:addToUIManager() -- {{{ add element to UI UIManager.AddUI(jObj); end -- }}} function self:drawRectangle(mode, x, y, w, h, color) -- {{{ draw a rectangle, filled or line if mode == 'fill' then jObj:DrawTextureScaledColor(nil, x, y, w, h, color.r, color.g, color.b, color.a); elseif mode == 'line' then jObj:DrawTextureScaledColor(nil, x, y, w, 1, color.r, color.g, color.b, color.a); jObj:DrawTextureScaledColor(nil, x, y, 1, h, color.r, color.g, color.b, color.a); jObj:DrawTextureScaledColor(nil, x + w, y, 1, h, color.r, color.g, color.b, color.a); jObj:DrawTextureScaledColor(nil, x, y + h, w, 1, color.r, color.g, color.b, color.a); end end -- }}} function self:drawText(text, x, y, color, font) -- {{{ draw text jObj:DrawText(font or UIFont.Small, text, x, y, color.r, color.g, color.b, color.a); end -- }}} function self:drawTextCentered(text, x, y, color, font) -- {{{ draw text centered horizontally jObj:DrawTextCentre(font or UIFont.Small, text, x, y, color.r, color.g, color.b, color.a); end -- }}} function self:drawTexture(texture, x, y) -- {{{ jObj:DrawTexture(texture, x, y, 1); end -- }}} function self:drawTextureTinted(texture, x, y, color) -- {{{ jObj:DrawTextureColor(texture, x, y, color.r, color.g, color.b, color.a); end -- }}} function self:drawTextureScaled(texture, x, y, w, h) -- {{{ jObj:DrawTextureScaled(texture, x, y, w, h, 1); end -- }}} function self:drawTextureScaledTinted(texture, x, y, w, h, color) -- {{{ jObj:DrawTextureScaledColor(texture, x, y, w, h, color.r, color.g, color.b, color.a); end -- }}} function self:close() -- {{{ remove window from UI Manager self:setVisible(false); UIManager.RemoveElement(jObj); end -- }}} function self:toggle() -- {{{ toggle visibility self:setVisible(not jObj:isVisible()); end -- }}} function self:_addAsChildTo(o) -- {{{ o:AddChild(jObj); end -- }}} function self:addChild(o) -- {{{ children[o:getID()] = o; o:setParent(self); o:_addAsChildTo(jObj); -- required to keep objects private end -- }}} function self:onMouseDown(mX, mY) -- {{{ if parent then return parent:onMouseDown(mX, mY) end return false; end -- }}} function self:onMouseUp(mX, mY) -- {{{ if parent then return parent:onMouseUp(mX, mY) end return false; end -- }}} function self:onMouseMove(mX, mY) -- {{{ mouseOver = true; if parent then return parent:onMouseMove(mX, mY) end return false; end -- }}} function self:onRightMouseDown(mX, mY) -- {{{ if parent then return parent:onRightMouseDown(mX, mY) end return false; end -- }}} function self:onRightMouseUp(mX, mY) -- {{{ if parent then return parent:onRightMouseUp(mX, mY) end return false; end -- }}} function self:onMouseWheel(mW) -- {{{ if parent then return parent:onRightMouseWheel(mX, mY) end return false; end -- }}} function self:onRightMouseUpOutside(mX, mY) -- {{{ if parent then return parent:onRightMouseUpOutside(mX, mY) end return false; end -- }}} function self:onRightMouseDownOutside(mX, mY) -- {{{ if parent then return parent:onRightMouseDownOutside(mX, mY) end return false; end -- }}} function self:onMouseUpOutside(mX, mY) -- {{{ if parent then return parent:onMouseUpOutside(mX, mY) end return false; end -- }}} function self:onMouseDownOutside(mX, mY) -- {{{ if parent then return parent:onMouseDownOutside(mX, mY) end return false; end -- }}} function self:onMouseMoveOutside(mX, mY) -- {{{ mouseOver = false; if parent then return parent:onMouseMoveOutside(mX, mY) end return false; end -- }}} -- ------------------------------------------------ -- Joypad Functions -- TODO -- ------------------------------------------------ function self:onLoseJoypadFocus(joypadData) -- {{{ joyPadFocus = nil; end -- }}} function self:onGainJoypadFocus(joypadData) -- {{{ joyPadFocus = joypadData; end -- }}} function self:onJoypadDown(button) -- {{{ end -- }}} function self:onJoypadDirUp() -- {{{ end -- }}} function self:onJoypadDirDown() -- {{{ end -- }}} function self:onJoypadDirLeft() -- {{{ end -- }}} function self:onJoypadDirRight() -- {{{ end -- }}} -- ------------------------------------------------ -- Setters -- ------------------------------------------------ function self:setVisible(nv) -- {{{ set visibility jObj:setVisible(nv); end -- }}} function self:setMinX(mx) -- {{{ MIN_X = mx; end -- }}} function self:setMaxX(mx) -- {{{ MAX_X = mx; end -- }}} function self:setMinY(my) -- {{{ MIN_Y = my; end -- }}} function self:setMaxY(my) -- {{{ MAX_Y = my; end -- }}} function self:setX(nx) -- {{{ if MIN_X > -1 and MAX_X > -1 then x = clamp(MIN_X, nx, MAX_X - w); else x = nx; end jObj:setX(x); end -- }}} function self:setY(ny) -- {{{ if MIN_Y > -1 and MAX_Y > -1 then y = clamp(MIN_Y, ny, MAX_Y - h); else y = ny; end jObj:setY(y); end -- }}} function self:setWidth(nw) -- {{{ w = nw; jObj:setWidth(w); self:setX(x); end -- }}} function self:setHeight(nh) -- {{{ h = nh; jObj:setHeight(h); self:setY(y); end -- }}} function self:setPosition(nx, ny) -- {{{ self:setX(nx); self:setY(ny); end -- }}} function self:setParent(o) -- {{{ parent = o; end -- }}} -- ------------------------------------------------ -- Getters -- ------------------------------------------------ function self:isVisible() -- {{{ return jObj:isVisible(); end -- }}} function self:getID() -- {{{ return ID; end -- }}} function self:getX() -- {{{ return x; end -- }}} function self:getY() -- {{{ return y; end -- }}} function self:getWidth() -- {{{ return w; end -- }}} function self:getHeight() -- {{{ return h; end -- }}} function self:getPosition() -- {{{ return x, y; end -- }}} function self:getParent() -- {{{ return parent; end -- }}} function self:isMouseOver() -- {{{ return mouseOver; end -- }}} -- Create a java instance. jObj = UIElement.new(self); -- Clamp the position values so the UI can't be moved offscreen. self:setPosition(x, y); -- also sets it on jObj self:setWidth(w); self:setHeight(h); jObj:setAnchorLeft(false); jObj:setAnchorRight(false); jObj:setAnchorTop(false); jObj:setAnchorBottom(false); return self; end
mit
ElectricPrism/stargus
scripts/terran/units.lua
1
5569
Load("scripts/terran/unit-terran-academy.lua") Load("scripts/terran/unit-terran-armory.lua") Load("scripts/terran/unit-terran-barracks.lua") Load("scripts/terran/unit-terran-bunker.lua") Load("scripts/terran/unit-terran-command-center.lua") Load("scripts/terran/unit-terran-engineering-bay.lua") Load("scripts/terran/unit-terran-factory.lua") Load("scripts/terran/unit-terran-missile-turret.lua") Load("scripts/terran/unit-terran-refinery.lua") Load("scripts/terran/unit-terran-science-facility.lua") Load("scripts/terran/unit-terran-starport.lua") Load("scripts/terran/unit-terran-supply-depot.lua") Load("scripts/terran/unit-terran-comsat-station.lua") Load("scripts/terran/unit-terran-battlecruiser.lua") Load("scripts/terran/unit-terran-dropship.lua") Load("scripts/terran/unit-terran-firebat.lua") Load("scripts/terran/unit-terran-ghost.lua") Load("scripts/terran/unit-terran-goliath.lua") Load("scripts/terran/unit-terran-marine.lua") Load("scripts/terran/unit-terran-science-vessel.lua") Load("scripts/terran/unit-terran-scv.lua") Load("scripts/terran/unit-terran-siege-tank.lua") Load("scripts/terran/unit-terran-vulture.lua") Load("scripts/terran/unit-terran-wraith.lua") -- -- Buttons -- DefineButton( { Pos = 1, Level = 0, Icon = "icon-move", Action = "move", Key = "m", Hint = "~!Move", ForUnit = { "terran-group", "unit-terran-battlecruiser", "unit-terran-dropship", "unit-terran-firebat", "unit-terran-ghost", "unit-terran-goliath", "unit-terran-marine", "unit-terran-science-vessel", "unit-terran-scv", "unit-terran-siege-tank", "unit-terran-vulture", "unit-terran-wraith", } } ) DefineButton( { Pos = 2, Level = 0, Icon = "icon-stop", Action = "stop", Key = "s", Hint = "~!Stop", ForUnit = { "terran-group", "unit-terran-battlecruiser", "unit-terran-dropship", "unit-terran-firebat", "unit-terran-ghost", "unit-terran-goliath", "unit-terran-marine", "unit-terran-missile-turret", "unit-terran-science-vessel", "unit-terran-scv", "unit-terran-siege-tank", "unit-terran-vulture", "unit-terran-wraith", } } ) DefineButton( { Pos = 3, Level = 0, Icon = "icon-attack", Action = "attack", Key = "a", Hint = "~!Attack", ForUnit = { "terran-group", "unit-terran-battlecruiser", "unit-terran-firebat", "unit-terran-ghost", "unit-terran-goliath", "unit-terran-marine", "unit-terran-scv", "unit-terran-missile-turret", "unit-terran-siege-tank", "unit-terran-vulture", "unit-terran-wraith", } } ) DefineButton( { Pos = 4, Level = 0, Icon = "icon-patrol", Action = "patrol", Key = "p", Hint = "~!Patrol", ForUnit = { "terran-group", "unit-terran-battlecruiser", "unit-terran-dropship", "unit-terran-firebat", "unit-terran-ghost", "unit-terran-goliath", "unit-terran-marine", "unit-terran-missile-turret", "unit-terran-science-vessel", "unit-terran-siege-tank", "unit-terran-vulture", "unit-terran-wraith", } } ) DefineButton( { Pos = 5, Level = 0, Icon = "icon-hold-position", Action = "stand-ground", Key = "h", Hint = "~!Hold Position", ForUnit = { "terran-group", "unit-terran-battlecruiser", "unit-terran-dropship", "unit-terran-firebat", "unit-terran-ghost", "unit-terran-goliath", "unit-terran-marine", "unit-terran-missile-turret", "unit-terran-science-vessel", "unit-terran-siege-tank", "unit-terran-vulture", "unit-terran-wraith", } } ) DefineButton( { Pos = 6, Level = 0, Icon = "icon-rally-point", Action = "move", Key = "r", Hint = "Set ~!Rally Point", ForUnit = { "unit-terran-barracks", "unit-terran-command-center", "unit-terran-starport", } } ) DefineButton( { Pos = 9, Level = 0, Icon = "icon-terran-liftoff", Action = "move", Key = "l", Hint = "~!Liftoff", ForUnit = { "unit-terran-barracks", "unit-terran-command-center", "unit-terran-engineering-bay", "unit-terran-starport", } } ) -- -- Allow -- DefineAllow("unit-terran-battlecruiser", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-dropship", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-firebat", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-ghost", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-goliath", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-marine", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-science-vessel", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-scv", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-siege-tank", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-vulture", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-wraith", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-academy", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-armory", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-barracks", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-bunker", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-command-center", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-engineering-bay", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-factory", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-missile-turret", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-refinery", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-science-facility", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-starport", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-supply-depot", "AAAAAAAAAAAAAAAA") DefineAllow("unit-terran-comsat-station", "AAAAAAAAAAAAAAAA")
gpl-2.0
FizzerWL/ExampleMods
DiplomacyMod/Client.lua
1
1054
require('Utilities'); function DoProposalPrompt(game, proposal) local otherPlayer = game.Game.Players[proposal.PlayerOne].DisplayName(nil, false); UI.PromptFromList(otherPlayer .. ' has proposed an alliance with you for ' .. proposal.NumTurns .. ' turns. Do you accept?', { AcceptProposalBtn(game, proposal), DeclineProposalBtn(game, proposal) }); end function AcceptProposalBtn(game, proposal) local ret = {}; ret["text"] = 'Accept'; ret["selected"] = function() local payload = {}; payload.Message = "AcceptProposal"; payload.ProposalID = proposal.ID; game.SendGameCustomMessage('Accepting proposal...', payload, function(returnValue) end); end return ret; end function DeclineProposalBtn(game, proposal) local ret = {}; ret["text"] = 'Decline'; ret["selected"] = function() local payload = {}; payload.Message = "DeclineProposal"; payload.ProposalID = proposal.ID; game.SendGameCustomMessage('Declining proposal...', payload, function(returnValue) end); end return ret; end
mit
movb/Algorithm-Implementations
Sieve_of_Eratosthenes/Lua/Yonaba/sieve_test.lua
27
1175
-- Tests for sieve.lua local sieve = require 'sieve' local total, pass = 0, 0 local function dec(str, len) return #str < len and str .. (('.'):rep(len-#str)) or str:sub(1,len) end local function run(message, f) total = total + 1 local ok, err = pcall(f) if ok then pass = pass + 1 end local status = ok and 'PASSED' or 'FAILED' print(('%02d. %68s: %s'):format(total, dec(message,68), status)) end local function find(array, value) for i,v in ipairs(array) do if v == value then return i end end end run('Testing sieve', function() local primes = sieve(20) assert(#primes == 7) assert(find(primes, 0) == nil) assert(find(primes, 1) == nil) assert(find(primes, 3) == 1) assert(find(primes, 5) == 2) assert(find(primes, 7) == 3) assert(find(primes, 11) == 4) assert(find(primes, 13) == 5) assert(find(primes, 17) == 6) assert(find(primes, 19) == 7) end) run('We have 78497 primes below 1000000', function() assert(#sieve(1e6) == 78497) end) print(('-'):rep(80)) print(('Total : %02d: Pass: %02d - Failed : %02d - Success: %.2f %%') :format(total, pass, total-pass, (pass*100/total)))
mit
dvr333/Zero-K
LuaRules/Gadgets/Include/GetNukeIntercepted.lua
6
1569
local atan = math.atan local cos = math.cos local sin = math.sin local pi = math.pi local sqrt = math.sqrt -- Unit (antinuke) position, Projectile (nuke silo) position, Target position local function GetNukeIntercepted(ux, uz, px, pz, tx, tz, radiusSq) -- Translate projectile position to the origin. ux, uz, tx, tz, px, pz = ux - px, uz - pz, tx - px, tz - pz, 0, 0 -- Get direction from projectile to target local tDir if tx == 0 then if tz == 0 then return ux^2 + uz^2 < radiusSq elseif tz > 0 then tDir = pi * 0.5 else tDir = pi * 1.5 end elseif tx > 0 then tDir = atan(tz/tx) else tDir = atan(tz/tx) + pi end -- Rotate space such that direction from projectile to target is 0 -- The nuke projectile will travel along the positive x-axis local cosDir = cos(-tDir) local sinDir = sin(-tDir) ux, uz = ux*cosDir - uz*sinDir, uz*cosDir + ux*sinDir tx, tz = tx*cosDir - tz*sinDir, tz*cosDir + tx*sinDir -- Find intersection of antinuke range with x-axis -- Quadratic formula, a = 1 local b = -2*ux local c = ux^2 + uz^2 - radiusSq local determinate = b^2 - 4*c if determinate < 0 then -- No real solutions so the circle does not intersect x-axis. -- This means that antinuke projectile does not cross intercept -- range. return false end determinate = sqrt(determinate) local leftInt = (-b - determinate)/2 local rightInt = (-b + determinate)/2 -- IF the nuke does not fall short of coverage -- AND the projectile is still within coverage return leftInt < tx and rightInt > 0 end return GetNukeIntercepted
gpl-2.0
camchenry/super_shooter
states/options.lua
1
14370
options = {} -- this is out here because it needs to be accessible before options:init() is called options.file = 'config.txt' options.version = 2 function options:init() self.leftAlign = 75 end function options:enter() local config = nil if not love.filesystem.exists(self.file) then config = self:getDefaultConfig() else config = self:getConfig() end local y = 365 -- starting point local sep = 40 -- how much to seperate each item by -- basic screen settings self.vsync = Checkbox:new('VERTICAL SYNC', self.leftAlign, y) self.vsync.selected = config.display.flags.vsync y = y+sep self.fullscreen = Checkbox:new('FULLSCREEN', self.leftAlign, y) self.fullscreen.selected = config.display.flags.fullscreen y = y+sep self.borderless = Checkbox:new('BORDERLESS', self.leftAlign, y) self.borderless.selected = config.display.flags.borderless y = y+sep self.highdpi = Checkbox:new('HIGH-DPI', self.leftAlign, y) self.highdpi.selected = config.display.flags.highdpi y = y+sep y = y + 20 -- extra space between groups -- graphics and game settings self.shaderEffects = Checkbox:new('SHADER EFFECTS', self.leftAlign, y) self.shaderEffects.selected = config.graphics.shaderEffects self.azerty = Checkbox:new('AZERTY KEYBOARD', self.leftAlign + 300, y) self.azerty.selected = config.graphics.azerty y = y+sep self.particles = Checkbox:new('PARTICLES', self.leftAlign, y) self.particles.selected = config.graphics.particles y = y+sep self.displayFPS = Checkbox:new('SHOW FPS', self.leftAlign, y) self.displayFPS.selected = config.graphics.displayFPS y = y+sep self.trackpad = Checkbox:new('TRACKPAD MODE', self.leftAlign, y) self.trackpad.selected = config.input.trackpadMode -- list items -- Takes all available resolutions local resTable = love.window.getFullscreenModes(1) local resolutions = {} --local screenWidth, screenHeight = love.graphics.getDesktopDimensions() -- finish this for k, res in pairs(resTable) do --if res.width > 800 then -- cuts off any resolutions with a width under 800 --if res.width <= screenWidth and res.height <= screenHeight then table.insert(resolutions, {res.width, res.height}) --end end -- add a resolution for an experimental feature to play across multiple monitors local windowCount = love.window.getDisplayCount() --[[ local multiWidth = 0 local multiHeight = 0 if windowCount > 1 then for i = 1, windowCount do local width, height = love.window.getDesktopDimensions(i) multiWidth = multiWidth + width -- add together the width of all connected monitors if height > multiHeight then -- find the largest monitor height if multiHeight > 0 then table.insert(resolutions, {multiWidth, multiHeight}) end multiHeight = height end end table.insert(resolutions, {multiWidth, multiHeight}) end ]] --self.multiHeight = multiHeight -- sort resolutions from smallest to biggest table.sort(resolutions, function(a, b) return a[1]*a[2] < b[1]*b[2] end) local optionWidth = 120 y = 225 self.resolution = List:new('RESOLUTION: ', resolutions, self.leftAlign, y, 400) self.resolution:selectTable({config.display.width, config.display.height}) self.resolution:setText('{1}x{2}') self.resolution:setOptionWidth(optionWidth) y = y+sep local msaaOptions = {0, 2, 4, 8, 16} self.msaa = List:new('ANTIALIASING: ', msaaOptions, self.leftAlign, y, 400) self.msaa:selectValue(config.display.flags.msaa) self.msaa:setText('{}x') self.msaa:setOptionWidth(optionWidth) y = y+sep local fullscreenOptions = {"desktop", "exclusive"} self.fullscreenMode = List:new("FULLSCREEN TYPE: ", fullscreenOptions, self.leftAlign, y, 400) self.fullscreenMode:selectValue(config.display.flags.fullscreentype) self.fullscreenMode:setText('{}') self.fullscreenMode:setOptionWidth(optionWidth) local monitorOptions = {} for i = 1, windowCount do table.insert(monitorOptions, i) end self.monitorSelect = List:new("DISPLAY MONITOR: ", monitorOptions, self.leftAlign, y+400, 400) self.monitorSelect:selectValue(config.display.flags.display) self.monitorSelect:setText('{}') self.monitorSelect:setOptionWidth(optionWidth) y = y+sep local x = self.leftAlign+450 y = 225 sep = 100 -- SLIDER ITEMS self.musicVolume = Slider:new("MUSIC VOLUME: %d", 0, 100, config.audio.musicVolume, x, y, 275, 50, font[24]) self.musicVolume.changed = function() signal.emit('musicChanged', self.musicVolume.ratio) end y = y + sep self.soundVolume = Slider:new("SOUND VOLUME: %d", 0, 100, config.audio.soundVolume, x, y, 275, 50, font[24]) self.soundVolume.changed = function() signal.emit('soundChanged', self.soundVolume.ratio) end y = y + sep self.cameraZoom = Slider:new("CAMERA ZOOM: %.1f", .7, 2, config.graphics.cameraZoom, x, y, 275, 50, font[24]) --self.cameraZoom.changed = function() signal.emit('zoomChanged', self.cameraZoom.ratio) end -- not ideal self.cameraZoom.roundTo = 1 --self.cameraZoom.changed = function() game.cameraZoom = self.cameraZoom.value end local bottomMargin = 60 -- applies current config settings self.back = Button:new("< BACK", self.leftAlign, love.graphics.getHeight() - bottomMargin) self.back.activated = function() state.switch(menu) -- options can be accessed from multiple places in the game end self.apply = Button:new('APPLY CHANGES', self.leftAlign+170, love.graphics.getHeight()-bottomMargin) self.apply.activated = function () self:applyChanges() self.back.y = love.graphics.getHeight()-bottomMargin self.apply.y = love.graphics.getHeight()-bottomMargin --self.default.y = love.graphics.getHeight()-bottomMargin --self:setDefaultX(self.default.text) end --[[ local text = 'RESET DEFAULT (F2)' self.default = Button:new(text, 0, love.graphics.getHeight()-bottomMargin) self.default.activated = function () local conf = self:getDefaultConfig() self:load(conf) self.back.y = love.graphics.getHeight()-bottomMargin self.apply.y = love.graphics.getHeight()-bottomMargin self.default.y = love.graphics.getHeight()-bottomMargin self:setDefaultX(text) self:setVisibleValues(conf) self:save() end self:setDefaultX(text) ]] self:save() end function options:resetToDefault() local bottomMargin = 60 local conf = self:getDefaultConfig() self:load(conf) self.back.y = love.graphics.getHeight()-bottomMargin self.apply.y = love.graphics.getHeight()-bottomMargin --self.default.y = love.graphics.getHeight()-bottomMargin --self:setDefaultX(text) self:setVisibleValues(conf) self:save() end function options:setVisibleValues(conf) self.vsync.selected = conf.display.flags.vsync self.fullscreen.selected = conf.display.flags.fullscreen self.borderless.selected = conf.display.flags.borderless self.highdpi.selected = conf.display.flags.highdpi self.shaderEffects.selected = conf.graphics.shaderEffects self.azerty.selected = conf.graphics.azerty self.particles.selected = conf.graphics.particles self.displayFPS.selected = conf.graphics.displayFPS self.trackpad.selected = conf.input.trackpadMode self.resolution:selectTable({conf.display.width, conf.display.height}) self.msaa:selectValue(conf.display.flags.msaa) self.fullscreenMode:selectValue(conf.display.flags.fullscreentype) self.monitorSelect:selectValue(conf.display.flags.display) -- add for volumes and zoom end --[[ function options:setDefaultX(text) local textWidth = self.default.font:getWidth(text) local rightMargin = 40 self.default.x = love.graphics.getWidth() - rightMargin - textWidth end ]] function options:leave() self:load() end function options:applyChanges() self:save() self:load() return true end function options:mousepressed(x, y, button) if button == 1 then self.vsync:mousepressed(x, y) self.fullscreen:mousepressed(x, y) self.borderless:mousepressed(x, y) self.highdpi:mousepressed(x, y) self.shaderEffects:mousepressed(x, y) self.particles:mousepressed(x, y) self.displayFPS:mousepressed(x, y) self.trackpad:mousepressed(x, y) self.azerty:mousepressed(x, y) end self.musicVolume:mousepressed(x, y, button) self.soundVolume:mousepressed(x, y, button) self.cameraZoom:mousepressed(x, y, button) self.resolution:mousepressed(x, y, button) self.msaa:mousepressed(x, y, button) self.fullscreenMode:mousepressed(x, y, button) self.monitorSelect:mousepressed(x, y, button) self.back:mousepressed(x, y, button) self.apply:mousepressed(x, y, button) --self.default:mousepressed(x, y, button) end function options:keypressed(key) if key == 'escape' then state.pop() end if key == 'f2' then self:resetToDefault() end end function options:update(dt) self.vsync:update(dt) self.fullscreen:update(dt) self.borderless:update(dt) self.highdpi:update(dt) self.shaderEffects:update(dt) self.particles:update(dt) self.displayFPS:update(dt) self.trackpad:update(dt) self.azerty:update(dt) self.musicVolume:update(dt) self.soundVolume:update(dt) self.cameraZoom:update(dt) self.resolution:update(dt) self.msaa:update(dt) self.fullscreenMode:update(dt) self.monitorSelect:update(dt) self.back:update(dt) self.apply:update(dt) --self.default:update(dt) -- update volumes without applying changes soundControl.musicVolume = self.musicVolume.ratio soundControl.soundVolume = self.soundVolume.ratio end function options:draw() love.graphics.setColor(1, 1, 1) love.graphics.rectangle("fill", 0, 0, love.graphics.getWidth(), 120+55) love.graphics.setFont(fontBold[72]) love.graphics.setColor(0, 0, 0) love.graphics.print('OPTIONS', 75, 70) self.vsync:draw() self.fullscreen:draw() self.borderless:draw() self.highdpi:draw() self.shaderEffects:draw() self.particles:draw() self.displayFPS:draw() self.trackpad:draw() self.azerty:draw() self.musicVolume:draw() self.soundVolume:draw() self.cameraZoom:draw() self.resolution:draw() self.msaa:draw() self.fullscreenMode:draw() self.monitorSelect:draw() self.back:draw() self.apply:draw() --self.default:draw() end function options:getDefaultConfig() local o = { version = 0, display = { width = 1024, height = 768, -- these are the standard flags for love.window.setMode flags = { vsync = false, fullscreen = false, fullscreentype = "desktop", display = 1, highdpi = false, borderless = false, msaa = 0, }, }, graphics = { shaderEffects = true, particles = true, displayFPS = false, azerty = false, cameraZoom = 1, }, audio = { soundVolume = 100, musicVolume = 80, }, input = { trackpadMode = false, }, } return o end function options:save() local o = { version = self.version, display = { width = self.resolution.options[self.resolution.selected][1], height = self.resolution.options[self.resolution.selected][2], -- these are the standard flags for love.window.setMode flags = { vsync = self.vsync.selected, fullscreen = self.fullscreen.selected, borderless = self.borderless.selected, highdpi = self.highdpi.selected, msaa = self.msaa.options[self.msaa.selected], fullscreentype = self.fullscreenMode.options[self.fullscreenMode.selected], display = self.monitorSelect.options[self.monitorSelect.selected], }, }, graphics = { shaderEffects = self.shaderEffects.selected, particles = self.particles.selected, displayFPS = self.displayFPS.selected, azerty = self.azerty.selected, cameraZoom = self.cameraZoom.value, }, audio = { musicVolume = self.musicVolume.value, soundVolume = self.soundVolume.value, }, input = { trackpadMode = self.trackpad.selected, }, } love.filesystem.write(self.file, serialize(o)) end function options:load(conf) local config = conf or self:getConfig() -- old config file if (config.version == nil) or (self.version > config.version) then local newConfig = self:getDefaultConfig() -- this will port over old config values to a new config file, based on the default -- if there are missing values, it replaces them with the default setting for i, category in pairs(newConfig) do if type(category) == 'table' then for j, value in pairs(category) do if config[i][j] == nil then config[i][j] = value -- table within a table (right now this should only be the window flags) elseif type(value) == 'table' then for k, flag in pairs(value) do if config[i][j][k] == nil then config[i][j][k] = flag end end end end end end end -- detects if any window settings are changed local reload = false local width, height, flags = love.window.getMode() if width ~= config.display.width or height ~= config.display.height then reload = true elseif flags.fullscreen ~= config.display.flags.fullscreen then reload = true elseif flags.vsync ~= config.display.flags.vsync then reload = true elseif flags.msaa ~= config.display.flags.msaa then reload = true elseif flags.borderless ~= config.display.flags.borderless then reload = true elseif flags.highdpi ~= config.display.flags.highdpi then reload = true elseif flags.fullscreentype ~= config.display.flags.fullscreentype then reload = true elseif flags.display ~= config.display.flags.display then reload = true end if love.window.getDisplayCount() > 1 then local width, height = love.window.getDesktopDimensions(flags.display) if config.display.width > width then config.display.flags.x = 0 if self.multiHeight then --config.display.flags.y = (self.multiHeight - height) * -1 end end end if reload then -- only reloads the window if needed love.window.setMode(config.display.width, config.display.height, config.display.flags) end game.effectsEnabled = config.graphics.shaderEffects game.particlesEnabled = config.graphics.particles game.displayFPS = config.graphics.displayFPS game.azertyMode = config.graphics.azerty game.cameraZoom = config.graphics.cameraZoom game.trackpadMode = config.input.trackpadMode soundControl.soundVolume = config.audio.soundVolume/100 soundControl.musicVolume = config.audio.musicVolume/100 return true end function options:getConfig() if not self:configFileExists() then return self:getDefaultConfig() else return love.filesystem.load(self.file)() end end function options:configFileExists() return love.filesystem.exists(self.file) end
mit
m241dan/darkstar
scripts/globals/weaponskills/spinning_attack.lua
9
1355
----------------------------------- -- Spinning Attack -- Hand-to-Hand weapon skill -- Skill Level: 150 -- Delivers an area attack. Radius varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Flame Gorget & Thunder Gorget. -- Aligned with the Flame Belt & Thunder Belt. -- Element: None -- Modifiers: STR:100% -- 100%TP 200%TP 300%TP -- 1.00 1.00 1.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary) local params = {}; params.numHits = 2; params.ftp100 = 1; params.ftp200 = 1; params.ftp300 = 1; params.str_wsc = 0.35; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.0; params.crit100 = 0.0; params.crit200 = 0.0; params.crit300 = 0.0; params.canCrit = false; params.acc100 = 0.0; params.acc200= 0.0; params.acc300= 0.0; params.atkmulti = 1; if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.str_wsc = 1.0; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, primary); return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
sigurdfdragon/wesnoth-fork
data/campaigns/World_Conquest/lua/map/generator/maritime.lua
7
6120
local function generate(length, villages, castle, iterations, size, players, island) local res = wct_generator_settings_arguments( length, villages, castle, iterations, size, players, island) res.max_lakes=90 res.min_lake_height=250 res.lake_size=60 res.river_frequency=100 res.temperature_size=7 res.roads=25 res.road_windiness=2 res.height = { -- list of common terrain types which come in at different heights, from highest to lowest dr_height(910, "Uh"), dr_height(820, "Uu"), dr_height(780, "Xu"), dr_height(765, "Mm^Xm"), dr_height(725, "Mm"), dr_height(610, "Hh"), dr_height(600, "Gg"), dr_height(590, "Hh^Fp"), dr_height(580, "Gg"), dr_height(570, "Gs^Fp"), dr_height(410, "Gg"), dr_height(400, "Mm"), dr_height(360, "Gg"), dr_height(340, "Hh^Fp"), dr_height(320, "Gg"), dr_height(300, "Gs^Fp"), dr_height(240, "Gg"), dr_height(220, "Gs^Fp"), dr_height(200, "Hh^Fp"), dr_height(180, "Hh"), dr_height(100, "Gg"), dr_height(30, "Ds"), dr_height(1, "Wwg"), dr_height(0, "Wog"), } res.convert = { wct_fix_river_into_ocean("g", 29), -- DR_CONVERT MIN_HT MAX_HT MIN_TMP MAX_TMP FROM TO -- low temperatures dr_convert(50, 999, 0, 270, "Ww, Wo", "Ai"), dr_convert(350, 999, 0, 320, "Gg", "Aa"), dr_convert(330, 999, 320, 370, "Gg", "Gd"), dr_convert(100, 999, 370, 475, "Gg", "Gs"), dr_convert(350, 999, 0, 310, "Gs^Fp", "Aa^Fpa"), dr_convert(350, 999, 0, 345, "Hh", "Ha"), dr_convert(350, 999, 0, 335, "Hh^Fp", "Ha^Fpa"), dr_convert(350, 999, 0, 370, "Mm", "Ms"), dr_convert(350, 999, 0, 390, "Mm^Xm", "Ms^Xm"), -- swamp appears on low land, at mod temp dr_convert(0, 200, 400, 700, "Gg", "Ss"), -- pine appears at low temperatures dr_convert(150, 999, 320, 420, "Gg", "Gs^Fp"), dr_convert(150, 999, 320, 420, "Hh", "Hh^Fp"), -- decidius appears at mod temperatures with some heigh dr_convert(300, 999, 510, 540, "Gg,Gs", "Gg^Fds"), dr_convert(300, 999, 510, 540, "Hh", "Hh^Fds"), -- fungus appears at med temp and high dr_convert(825, 950, 500, 525, "Uu, Uh", "Uu^Tf"), dr_convert(825, 950, 550, 575, "Uu, Uh", "Uu^Tf"), dr_convert(825, 950, 600, 625, "Uu, Uh", "Uu^Tf"), -- high temperatures dr_convert(800, 999, 850, 999, "Uu, Uh, Uu^Tf", "Ql"), dr_convert(260, 999, 800, 999, "Gg", "Dd"), dr_convert(230, 999, 750, 999, "Gg", "Gd"), dr_convert(100, 999, 650, 999, "Gg", "Gs"), dr_convert(460, 630, 800, 999, "Ds, Hh", "Hd"), -- DR_TEMPERATURE FROM MIN MAX TO), -- convert forest at different temperatures dr_temperature("Gs^Fp", 420, 475, "Gs^Fdf"), dr_temperature("Hh^Fp", 420, 510, "Hh^Fmf"), dr_temperature("Gs^Fp", 475, 510, "Gg^Fdf"), dr_temperature("Gs^Fp", 510, 540, "Gg^Fds"), dr_temperature("Hh^Fp", 510, 540, "Hh^Fds"), dr_temperature("Gs^Fp", 540, 650, "Gg^Ftr"), dr_temperature("Hh^Fp", 540, 650, "Hh^Fms"), } res.road_cost = { wct_generator_road_cost_classic(), dr_road("Gs", "Re", 10), dr_road("Gd", "Re", 10), dr_road("Gg^Fds", "Re", 20), dr_road("Gg^Ftr", "Re", 20), dr_road("Gg^Fdf", "Re", 20), dr_road("Hh^Fmf", "Re", 20), dr_road("Hh^Ft", "Re", 30), dr_road("Hh^Fp", "Re", 30), dr_road("Hh^Fds", "Re", 20), dr_road("Hh^Fms", "Re", 20), dr_road("Gs^Ft", "Re", 30), dr_road("Ds", "Re", 20), dr_bridge("Ww", "Ww^Bsb", "Chw", 35), dr_road("Chw", "Chw", 2), dr_road_over_bridges("Ww^Bsb", 2), } res.village = { dr_village { terrain = "Gg", convert_to="Gg^Vh", adjacent_liked="Gg, Ww, Ww, Ww, Ww, Ww, Ww, Ww, Re, Re, Re, Re, Hh, Gs, Gg", rating=8 }, dr_village { terrain = "Gs", convert_to="Gs^Vh", adjacent_liked="Gg, Ww, Ww, Ww, Ww, Ww, Ww, Ww, Re, Re, Re, Re, Hh, Gs, Gg, Gd, Gd, Gs, Gs", rating=5 }, dr_village { terrain = "Gd", convert_to="Gd^Vc", adjacent_liked="Gg, Ww, Ww, Ww, Ww, Ww, Ww, Ww, Re, Re, Re, Re, Hh, Gs, Gd, Gd, Gs, Gs, Gd", rating=5 }, dr_village { terrain="Ds", convert_to="Dd^Vda", adjacent_liked="Gg, Gs, Gd, Wwg, Wwg, Wwg, Re, Re, Hh, Ch, Wog,", rating=2 }, dr_village { terrain="Uu", convert_to="Uu^Vud", adjacent_liked="Re,Hh,Mm,Uu,Uh,Xu", rating=4 }, dr_village { terrain="Uh", convert_to="Uu^Vu", adjacent_liked="Re,Hh,Mm,Uu,Uh,Xu", rating=3 }, dr_village { terrain = "Gg^Fds", convert_to="Gg^Vh", adjacent_liked="Gg, Ww, Ww, Ww, Ww, Ww, Ww, Ww, Re, Re, Re, Re, Hh, Gs, Gg, Gg^Fds", rating=4 }, dr_village { terrain="Gs^Fp", convert_to="Gs^Vh", adjacent_liked="Gg, Ww, Ww, Ww, Ww, Ww, Ww, Ww, Re, Re, Re, Re, Hh, Gs, Gg, Gd, Gd, Gs, Gs, Gs^Fp", rating=4 }, dr_village { terrain="Hh", convert_to="Hh^Vhh", adjacent_liked="Gg, Ww, Ww, Ww, Ww, Ww, Ww, Ww, Re, Re, Re, Re, Hh, Gs, Gg, Gd, Gd, Gs, Gs, Gs^Fp", rating=4 }, dr_village { terrain="Hh^Fp", convert_to="Hh^Vhh", adjacent_liked="Gg, Ww, Ww, Ww, Ww, Ww, Ww, Ww, Re, Re, Re, Re, Hh, Gs, Gg, Gd, Gd, Gs, Gs, Gs^Fp", rating=4 }, dr_village { terrain="Mm", convert_to="Mm^Vhh", adjacent_liked="Gg, Ww, Ww, Ww, Ww^Bsb|, Ww^Bsb/, Ww^Bsb\\, Rr, Rr, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp", rating=4 }, -- villages in snow dr_village { terrain="Aa", convert_to="Aa^Vha", adjacent_liked="Gg, Ww, Ww, Ww, Ww^Bsb|, Ww^Bsb/, Ww^Bsb\\, Rr, Rr, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp", rating=3 }, dr_village { terrain="Aa^Fpa", convert_to="Aa^Vea", adjacent_liked="Gg, Ww, Ww, Ww, Ww^Bsb|, Ww^Bsb/, Ww^Bsb\\, Rr, Rr, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp", rating=3 }, -- swamp villages dr_village { terrain="Ss", convert_to="Ss^Vhs", adjacent_liked="Gg, Ww, Ww, Ww, Ww^Bsb|, Ww^Bsb/, Ww^Bsb\\, Rr, Rr, Re, Re, Gg^Ve, Gg^Vh, Hh, Gs^Fp", rating=2 }, -- mermen villages - give them low chance of appearing dr_village { terrain="Wwg", convert_to="Wwg^Vm", adjacent_liked="Wwg, Wwg, Ch, Ss, Ds, Ds", rating=1 }, } res.castle = { valid_terrain="Gs, Gg, Gd, Gs^Fp, Gg^Ft, Gg^Fds, Gg^Ftr, Hh, Hh^Fp, Hh^Ft, Hh^Fds, Hh^Fms, Ha^Fpa, Ha, Hh^Fmf, Gg^Fdf", min_distance=15, } return default_generate_map(res) end return generate
gpl-2.0
77shahriar77/ALFA
plugins/admin.lua
53
2402
local function set_bot_photo(msg, success, result) local receiver = get_receiver(msg) if success then local file = 'data/photos/bot.jpg' print('File downloaded to:', result) os.rename(result, file) print('File moved to:', file) set_profile_photo(file, ok_cb, false) send_large_msg(receiver, 'Photo changed!', ok_cb, false) redis:del("bot:photo") else print('Error downloading: '..msg.id) send_large_msg(receiver, 'Failed, please try again!', ok_cb, false) end end local function parsed_url(link) local parsed_link = URL.parse(link) local parsed_path = URL.parse_path(parsed_link.path) return parsed_path[2] end local function run(msg,matches) local data = load_data(_config.moderation.data) local receiver = get_receiver(msg) local group = msg.to.id if not is_admin(msg) then return end if msg.media then if msg.media.type == 'photo' and redis:get("bot:photo") then if redis:get("bot:photo") == 'waiting' then load_photo(msg.id, set_bot_photo, msg) end end end if matches[1] == "setbotphoto" then redis:set("bot:photo", "waiting") return 'Please send me bot photo now' end if matches[1] == "markread" then if matches[2] == "on" then redis:set("bot:markread", "on") return "Mark read > on" end if matches[2] == "off" then redis:del("bot:markread") return "Mark read > off" end return end if matches[1] == "pm" then send_large_msg("user#id"..matches[2],matches[3]) return "Msg sent" end if matches[1] == "block" then if is_admin2(matches[2]) then return "You can't block admins" end block_user("user#id"..matches[2],ok_cb,false) return "User blocked" end if matches[1] == "unblock" then unblock_user("user#id"..matches[2],ok_cb,false) return "User unblocked" end if matches[1] == "import" then local hash = parsed_url(matches[2]) import_chat_link(hash,ok_cb,false) end return end return { patterns = { "^[!/](pm) (%d+) (.*)$", "^[!/](import) (.*)$", "^[!/](unblock) (%d+)$", "^[!/](block) (%d+)$", "^[!/](markread) (on)$", "^[!/](markread) (off)$", "^[!/](setbotphoto)$", "%[(photo)%]" }, run = run, }
gpl-2.0
m241dan/darkstar
scripts/zones/Al_Zahbi/npcs/Eumoa-Tajimoa.lua
13
1041
----------------------------------- -- Area: Al Zahbi -- NPC: Eumoa-Tajimoa -- Type: Standard NPC -- @zone: 48 -- @pos 19.275 -1 55.182 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Al_Zahbi/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x00ef); 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
diizzyy/packages
utils/prometheus-node-exporter-lua/files/usr/lib/lua/prometheus-collectors/ltq-dsl.lua
17
4392
local function scrape() local fd = io.popen("/etc/init.d/dsl_control lucistat") local dsl_func = loadstring(fd:read("*a")) fd:close() if not dsl_func then return end local dsl_stat = dsl_func() local dsl_line_attenuation = metric("dsl_line_attenuation_db", "gauge") local dsl_signal_attenuation = metric("dsl_signal_attenuation_db", "gauge") local dsl_snr = metric("dsl_signal_to_noise_margin_db", "gauge") local dsl_aggregated_transmit_power = metric("dsl_aggregated_transmit_power_db", "gauge") local dsl_latency = metric("dsl_latency_seconds", "gauge") local dsl_datarate = metric("dsl_datarate", "gauge") local dsl_max_datarate = metric("dsl_max_datarate", "gauge") local dsl_error_seconds_total = metric("dsl_error_seconds_total", "counter") local dsl_errors_total = metric("dsl_errors_total", "counter") -- dsl hardware/firmware information metric("dsl_info", "gauge", { atuc_vendor_id = dsl_stat.atuc_vendor_id, atuc_system_vendor_id = dsl_stat.atuc_system_vendor_id, chipset = dsl_stat.chipset, firmware_version = dsl_stat.firmware_version, api_version = dsl_stat.api_version, }, 1) -- dsl line settings information metric("dsl_line_info", "gauge", { xtse1 = dsl_stat.xtse1, xtse2 = dsl_stat.xtse2, xtse3 = dsl_stat.xtse3, xtse4 = dsl_stat.xtse4, xtse5 = dsl_stat.xtse5, xtse6 = dsl_stat.xtse6, xtse7 = dsl_stat.xtse7, xtse8 = dsl_stat.xtse8, annex = dsl_stat.annex_s, mode = dsl_stat.line_mode_s, profile = dsl_stat.profile_s, }, 1) -- dsl up is 1 if the line is up and running local dsl_up if dsl_stat.line_state == "UP" then dsl_up = 1 else dsl_up = 0 end metric("dsl_up", "gauge", { detail = dsl_stat.line_state_detail, }, dsl_up) -- dsl line status data metric("dsl_uptime_seconds", "gauge", {}, dsl_stat.line_uptime) -- dsl db measurements dsl_line_attenuation({direction="down"}, dsl_stat.line_attenuation_down) dsl_line_attenuation({direction="up"}, dsl_stat.line_attenuation_up) dsl_signal_attenuation({direction="down"}, dsl_stat.signal_attenuation_down) dsl_signal_attenuation({direction="up"}, dsl_stat.signal_attenuation_up) dsl_snr({direction="down"}, dsl_stat.noise_margin_down) dsl_snr({direction="up"}, dsl_stat.noise_margin_up) dsl_aggregated_transmit_power({direction="down"}, dsl_stat.actatp_down) dsl_aggregated_transmit_power({direction="up"}, dsl_stat.actatp_up) -- dsl performance data if dsl_stat.latency_down ~= nil then dsl_latency({direction="down"}, dsl_stat.latency_down / 1000000) dsl_latency({direction="up"}, dsl_stat.latency_up / 1000000) end dsl_datarate({direction="down"}, dsl_stat.data_rate_down) dsl_datarate({direction="up"}, dsl_stat.data_rate_up) dsl_max_datarate({direction="down"}, dsl_stat.max_data_rate_down) dsl_max_datarate({direction="up"}, dsl_stat.max_data_rate_up) -- dsl errors dsl_error_seconds_total({err="forward error correction",loc="near"}, dsl_stat.errors_fecs_near) dsl_error_seconds_total({err="forward error correction",loc="far"}, dsl_stat.errors_fecs_far) dsl_error_seconds_total({err="errored",loc="near"}, dsl_stat.errors_es_near) dsl_error_seconds_total({err="errored",loc="far"}, dsl_stat.errors_es_near) dsl_error_seconds_total({err="severely errored",loc="near"}, dsl_stat.errors_ses_near) dsl_error_seconds_total({err="severely errored",loc="near"}, dsl_stat.errors_ses_near) dsl_error_seconds_total({err="loss of signal",loc="near"}, dsl_stat.errors_loss_near) dsl_error_seconds_total({err="loss of signal",loc="far"}, dsl_stat.errors_loss_far) dsl_error_seconds_total({err="unavailable",loc="near"}, dsl_stat.errors_uas_near) dsl_error_seconds_total({err="unavailable",loc="far"}, dsl_stat.errors_uas_far) dsl_errors_total({err="header error code error",loc="near"}, dsl_stat.errors_hec_near) dsl_errors_total({err="header error code error",loc="far"}, dsl_stat.errors_hec_far) dsl_errors_total({err="non pre-emptive crc error",loc="near"}, dsl_stat.errors_crc_p_near) dsl_errors_total({err="non pre-emptive crc error",loc="far"}, dsl_stat.errors_crc_p_far) dsl_errors_total({err="pre-emptive crc error",loc="near"}, dsl_stat.errors_crcp_p_near) dsl_errors_total({err="pre-emptive crc error",loc="far"}, dsl_stat.errors_crcp_p_far) end return { scrape = scrape }
gpl-2.0
smikail/arumbash
plugins/inpm.lua
33
2992
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
santssoft/darkstar
scripts/globals/mobskills/deadeye.lua
12
1270
--------------------------------------------- -- Deadeye -- Family: Qiqurn -- Description: Lowers the defense and magical defense of enemies within range. -- Type: Magical -- Utsusemi/Blink absorb: Ignores shadows -- Range: Unknown -- Notes: Used only by certain Notorious Monsters. Strong dsp.effect. --------------------------------------------- require("scripts/globals/monstertpmoves") require("scripts/globals/settings") require("scripts/globals/status") require("scripts/globals/msg") --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0 end function onMobWeaponSkill(target, mob, skill) local defDown = false local mDefDown = false defDown = MobStatusEffectMove(mob, target, dsp.effect.DEFENSE_DOWN, 50, 0, 120) mDefDown = MobStatusEffectMove(mob, target, dsp.effect.MAGIC_DEF_DOWN, 50, 0, 120) skill:setMsg(dsp.msg.basic.SKILL_ENFEEB_IS) -- display defense down first, else magic defense down if (defDown == dsp.msg.basic.SKILL_ENFEEB_IS) then typeEffect = dsp.effect.DEFENSE_DOWN elseif (mDefDown == dsp.msg.basic.NFEEB_IS) then typeEffect = dsp.effect.MAGIC_DEF_DOWN else skill:setMsg(dsp.msg.basic.SKILL_MISS) end return typeEffect end
gpl-3.0
ducseb/domoticz
scripts/dzVents/examples/check dead devices by desc.lua
25
1272
--Check dead device using their description --This allow to configure device to be checked directly in domoticz GUI by accessing to device details and add "CDA:<delayInMinute>" --You have to active http fetching ! return { active = true, on = { ['timer'] = { 'every 60 minutes' } }, execute = function(domoticz) local message="" domoticz.devices().forEach(function(device) if (device.description ~= nil) then _, _, threshold = string.find(device.description,"CDA:(%d+)") if (threshold ~= nil) then local name = device.name local minutes = domoticz.devices(name).lastUpdate.minutesAgo if ( minutes > tonumber(threshold)) then message = message .. 'Device ' .. name .. ' seems to be dead. No heartbeat for at least ' .. minutes .. ' minutes.\r' end end end end) if (message ~= "") then domoticz.notify('Dead devices', message, domoticz.PRIORITY_HIGH) domoticz.log('Dead devices found: ' .. message, domoticz.LOG_ERROR) end end }
gpl-3.0
santssoft/darkstar
scripts/zones/Metalworks/npcs/Mighty_Fist.lua
9
2275
----------------------------------- -- Area: Metalworks -- NPC: Mighty Fist -- Starts & Finishes Quest: The Darksmith (R) -- Involved in Quest: Dark Legacy -- !pos -47 2 -30 237 ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); local ID = require("scripts/zones/Metalworks/IDs"); ----------------------------------- function onTrade(player,npc,trade) if (player:getQuestStatus(BASTOK,dsp.quest.id.bastok.THE_DARKSMITH) ~= QUEST_AVAILABLE) then if (trade:hasItemQty(645,2) and trade:getItemCount() == 2) then player:startEvent(566); end end end; function onTrigger(player,npc) if (player:getCharVar("darkLegacyCS") == 1) then player:startEvent(752); elseif (player:hasKeyItem(dsp.ki.DARKSTEEL_FORMULA)) then player:startEvent(754); elseif (player:getQuestStatus(BASTOK,dsp.quest.id.bastok.THE_DARKSMITH) == QUEST_AVAILABLE and player:getFameLevel(BASTOK) >= 3) then player:startEvent(565); else Message = math.random(0,1); if (Message == 1) then player:startEvent(560); else player:startEvent(561); end end end; function onEventUpdate(player,csid,option) -- printf("CSID2: %u",csid); -- printf("RESULT2: %u",option); end; function onEventFinish(player,csid,option) if (csid == 565) then player:addQuest(BASTOK,dsp.quest.id.bastok.THE_DARKSMITH); elseif (csid == 566) then TheDarksmith = player:getQuestStatus(BASTOK,dsp.quest.id.bastok.THE_DARKSMITH); player:tradeComplete(); player:addGil(GIL_RATE*8000); player:messageSpecial(ID.text.GIL_OBTAINED,GIL_RATE*8000); if (TheDarksmith == QUEST_ACCEPTED) then player:addFame(BASTOK,30); player:completeQuest(BASTOK,dsp.quest.id.bastok.THE_DARKSMITH); else player:addFame(BASTOK,5); end elseif (csid == 752) then player:setCharVar("darkLegacyCS",2); player:addKeyItem(dsp.ki.LETTER_FROM_THE_DARKSTEEL_FORGE); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.LETTER_FROM_THE_DARKSTEEL_FORGE); end end;
gpl-3.0
santssoft/darkstar
scripts/zones/Port_Windurst/npcs/Degong.lua
12
1291
----------------------------------- -- Area: Port Windurst -- NPC: Degong -- Type: Fishing Synthesis Image Support -- !pos -178.400 -3.835 60.480 240 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/crafting"); local ID = require("scripts/zones/Port_Windurst/IDs"); ----------------------------------- function onTrade(player,npc,trade) end; function onTrigger(player,npc) local guildMember = isGuildMember(player,5); local SkillCap = getCraftSkillCap(player,dsp.skill.FISHING); local SkillLevel = player:getSkillLevel(dsp.skill.FISHING); if (guildMember == 1) then if (player:hasStatusEffect(dsp.effect.FISHING_IMAGERY) == false) then player:startEvent(10013,SkillCap,SkillLevel,2,239,player:getGil(),0,30,0); -- p1 = skill level else player:startEvent(10013,SkillCap,SkillLevel,2,239,player:getGil(),19293,30,0); end else player:startEvent(10013); -- Standard Dialogue end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 10013 and option == 1) then player:messageSpecial(ID.text.FISHING_SUPPORT,0,0,2); player:addStatusEffect(dsp.effect.FISHING_IMAGERY,1,0,3600); end end;
gpl-3.0
santssoft/darkstar
scripts/globals/weaponskills/dragon_kick.lua
10
1570
----------------------------------- -- Dragon Kick -- Hand-to-Hand weapon skill -- Skill Level: 225 -- Damage varies with TP. -- Will stack with Sneak Attack. -- Aligned with the Breeze Gorget & Thunder Gorget. -- Aligned with the Breeze Belt & Thunder Belt. -- Element: None -- Modifiers: STR:50% VIT:50% -- 100%TP 200%TP 300%TP -- 2.00 2.50 3.50 ----------------------------------- require("scripts/globals/status") require("scripts/globals/settings") require("scripts/globals/weaponskills") ----------------------------------- function onUseWeaponSkill(player, target, wsID, tp, primary, action, taChar) local params = {} params.numHits = 1 params.ftp100 = 2 params.ftp200 = 2.5 params.ftp300 = 3.5 params.str_wsc = 0.5 params.dex_wsc = 0.0 params.vit_wsc = 0.5 params.agi_wsc = 0.0 params.int_wsc = 0.0 params.mnd_wsc = 0.0 params.chr_wsc = 0.0 params.crit100 = 0.0 params.crit200 = 0.0 params.crit300 = 0.0 params.canCrit = false params.acc100 = 0.0 params.acc200= 0.0 params.acc300= 0.0 params.atk100 = 1; params.atk200 = 1; params.atk300 = 1; params.kick = true -- https://www.bluegartr.com/threads/112776-Dev-Tracker-Findings-Posts-%28NO-DISCUSSION%29?p=6712150&viewfull=1#post6712150 if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 2.0 params.ftp200 = 3.875 params.ftp300 = 7.0 end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, wsID, params, tp, action, primary, taChar) return tpHits, extraHits, criticalHit, damage end
gpl-3.0
account3r2/EZTCP
eztcp.lua
1
4008
--[[========================================================================\\ || EZTCP - A library to simplify TCP networking. || || Copyright (C) 2015 Niko Geil. || || || || This program is free software: you can redistribute it and/or modify || || it under the terms of the GNU General Public License as published by || || the Free Software Foundation, either version 3 of the License, or || || (at your option) any later version. || || || || This program is distributed in the hope that it will be useful, || || but WITHOUT ANY WARRANTY; without even the implied warranty of || || MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the || || GNU General Public License for more details. || || || || You should have received a copy of the GNU General Public License || || along with this program. If not, see <http://www.gnu.org/licenses/>. || \\========================================================================]] local eztcp = {} eztcp.version = "1.0.1" eztcp.create = {} eztcp.send = {} -- Create an empty set for the server and client objects. function eztcp.create.set() local set = {} setmetatable(set, { __index = { insert = function (set, client) -- Insert object into set. table.insert(set, client) end, remove = function (set, client) -- Remove object from set. for k, v in pairs(set) do if v == client then table.remove(set, k) break end end end, } }) return set end -- Send a raw message. function eztcp.send.raw(client, line, noNewline) local bytes, err = client:send(line .. (noNewline and "" or "\n")) -- Get bytes or err. return bytes, err end -- Create a server object. function eztcp.create.server(bindTo, bindToPort, set, timeout) local server = socket.bind(bindTo, bindToPort) -- Create the server. if set then -- If we got a set, then... set:insert(server) -- Insert the server into it. end if timeout and type(timeout) == "number" then -- Verify timeout. server:settimeout(timeout) -- Set timeout if we got it. end return server end --[[ || Process returns: || client object or nil, message or status code or nil, error or nil, ip, port || Status codes: || 0 - Client connected. || 1 - Client disconnected. || 2 - Client timed out. ]] -- Process the set. This is usually in a loop. Note that this function requires -- set[1] to be the server object. This will not work if it is not. function eztcp.process(set) local reading, _, err = socket.select(set) for _, object in ipairs(reading) do if object == set[1] then local client, err = object:accept() -- Create a client object. if client then local ip, port = client:getpeername() set:insert(client) -- Insert client into set. return client, 0, nil, ip, port else return nil, nil, "Could not create new client: " .. err, nil, nil end else local ip, port = object:getpeername() local line, err = object:receive() if err and err == "closed" then set:remove(object) -- If client closed their connection. object:close() -- Closed the connection. return object, 1, nil, ip, port elseif err and err == "timeout" then set:remove(object) -- If client timed out. object:close() -- Close the connection. return object, 2, nil, ip, port elseif err then set:remove(object) -- If an error occurred. object:close() -- Close the connection. return object, nil, err, ip, port else -- If we got here, we received a message successfully. return object, line, nil, ip, port end end end end return eztcp
gpl-3.0
santssoft/darkstar
scripts/zones/Lower_Jeuno/npcs/Vola.lua
9
2825
----------------------------------- -- Area: Lower Jeuno -- NPC: Vola -- Starts and Finishes Quest: Fistful of Fury -- Involved in Quests: Beat Around the Bushin (before the quest) -- !pos 43 3 -45 245 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/shop"); require("scripts/globals/quests"); local ID = require("scripts/zones/Lower_Jeuno/IDs"); ----------------------------------- function onTrade(player,npc,trade) FistfulOfFury = player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.FISTFUL_OF_FURY); if (FistfulOfFury == QUEST_ACCEPTED and trade:hasItemQty(1012,1) == true and trade:hasItemQty(1013,1) == true and trade:hasItemQty(1014,1) == true and trade:getItemCount() == 3) then player:startEvent(213); -- Finish Quest "Fistful of Fury" end end; function onTrigger(player,npc) FistfulOfFury = player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.FISTFUL_OF_FURY); BeatAroundTheBushin = player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.BEAT_AROUND_THE_BUSHIN); if (player:getFameLevel(NORG) >= 3 and FistfulOfFury == QUEST_AVAILABLE and player:getQuestStatus(BASTOK,dsp.quest.id.bastok.SILENCE_OF_THE_RAMS) == QUEST_COMPLETED) then player:startEvent(216); -- Start Quest "Fistful of Fury" elseif (FistfulOfFury == QUEST_ACCEPTED) then player:startEvent(215); -- During Quest "Fistful of Fury" elseif (BeatAroundTheBushin == QUEST_AVAILABLE and player:getMainJob() == dsp.job.MNK and player:getMainLvl() >= 71 and player:getFameLevel(NORG) >= 6) then player:startEvent(160); -- Start Quest "Beat Around the Bushin" elseif (BeatAroundTheBushin ~= QUEST_AVAILABLE) then player:startEvent(214); -- During & After Quest "Beat Around the Bushin" else player:startEvent(212); -- Standard dialog end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option) if (csid == 216 and option == 1) then player:addQuest(JEUNO,dsp.quest.id.jeuno.FISTFUL_OF_FURY); elseif (csid == 213) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ID.text.ITEM_CANNOT_BE_OBTAINED,13202); else player:addTitle(dsp.title.BROWN_BELT); player:addItem(13202); player:messageSpecial(ID.text.ITEM_OBTAINED,13202); player:addFame(NORG,125); player:tradeComplete(); player:completeQuest(JEUNO,dsp.quest.id.jeuno.FISTFUL_OF_FURY); end elseif (csid == 160 and player:getQuestStatus(JEUNO,dsp.quest.id.jeuno.BEAT_AROUND_THE_BUSHIN) == QUEST_AVAILABLE) then player:setCharVar("BeatAroundTheBushin",1); -- For the next quest "Beat around the Bushin" end end;
gpl-3.0
m241dan/darkstar
scripts/zones/Southern_San_dOria/npcs/Lanqueron.lua
13
1569
----------------------------------- -- Area: Southern San dOria -- NPC: Lanqueron -- Type: Item Deliverer NPC -- Involved in Quest: Lost Chick -- @zone: 230 -- @pos 0.335 1.199 -28.404 ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Southern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player: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
DylanM-Marshall/FIDDLE
_deprecated/TORCHmodels/models/NSmodel.lua
2
1975
--[[ NETseq models ]]-- require 'torch' -- torch require 'nngraph' -- provides all sorts of trainable modules/layers ---------------------------------------------------------------------- ---------------------------------------------------------------------- print '==> define parameters' ----------------------------------------------------- -- Model Parameters ----------------------------------------------------- finalNout = 500 nfeats = 2 -- for sense and antisense for NSMS and should be 4 for DS width = 500 height = 1 ninputs = nfeats*width*height nstates = {40,80,500} filtSizeW={10,10} filtSizeH={1,1} poolSize ={2,2} ----------------------------------------------------- -- Model Architecture ----------------------------------------------------- NSinp = nn.Identity()() -- 1st Layer -- m11 = nn.SpatialConvolutionMM(nfeats,nstates[1],filtSizeW[1],filtSizeH[1])(NSinp):annotate{ name = 'C1', description = 'Convolution', graphAttributes = {color = 'red'} } m11 = nn.ReLU()(m11):annotate{ name='NL1',description = 'ReLU' } m11 = nn.SpatialMaxPooling(poolSize[1],1,poolSize[1],1)(m11):annotate{ name = 'P1', description = 'MaxPool' } local Nshape = math.floor((width-filtSizeW[1]+1)/poolSize[1]) -- 2nd Layer -- m11 = nn.SpatialConvolutionMM(nstates[1],nstates[2],filtSizeW[2],filtSizeH[2])(m11):annotate{ name = 'C2', description = 'Convolution', graphAttributes = {color = 'red'} } m11 = nn.ReLU()(m11):annotate{ name='NL2',description = 'ReLU' } m11 = nn.SpatialMaxPooling(poolSize[2],1,poolSize[2],1)(m11):annotate{ name = 'P2', description = 'MaxPool' } Nshape = math.floor((Nshape-filtSizeW[2]+1)/poolSize[2]) m11 = nn.View( nstates[2]*1*Nshape)(m11) m11 = nn.Dropout(0.5)(m11) -- 3rd Layer -- m11 = nn.Linear(nstates[2]*1*Nshape, finalNout)(m11):annotate{ name='FC3',description = 'FullyConnected' } -- LogSoftMax Layer -- m11 = nn.LogSoftMax()(m11) model = nn.gModule({NSinp},{m11})
gpl-3.0
tritao/premake-core
src/base/rule.lua
14
3133
--- -- base/rule.lua -- Defines rule sets for generated custom rule files. -- Copyright (c) 2014 Jason Perkins and the Premake project --- local p = premake p.rule = p.api.container("rule", p.global) local rule = p.rule --- -- Create a new rule container instance. --- function rule.new(name) local self = p.container.new(rule, name) -- create a variable setting function. Do a version with lowercased -- first letter(s) to match Premake's naming style for other calls _G[name .. "Vars"] = function(vars) rule.setVars(self, vars) end local lowerName = name:gsub("^%u+", string.lower) _G[lowerName .. "Vars"] = _G[name .. "Vars"] return self end --- -- Enumerate the property definitions for a rule. --- function rule.eachProperty(self) local props = self.propertydefinition local i = 0 return function () i = i + 1 if i <= #props then return props[i] end end end --- -- Find a property definition by its name. -- -- @param name -- The property name. -- @returns -- The property definition if found, nil otherwise. --- function rule.getProperty(self, name) local props = self.propertydefinition for i = 1, #props do local prop = props[i] if prop.name == name then return prop end end end --- -- Find the field definition for one this rule's properties. This field -- can then be used with the api.* functions to manipulate the property's -- values in the current configuration scope. -- -- @param prop -- The property definition. -- @return -- The field definition for the property; this will be created if it -- does not already exist. --- function rule.getPropertyField(self, prop) if prop._field then return prop._field end local kind = prop.kind or "string" if kind == "list" then kind = "list:string" end local fld = p.field.new { name = "_rule_" .. self.name .. "_" .. prop.name, scope = "config", kind = kind, tokens = true, } prop._field = fld return fld end --- -- Given the value for a particular property, returns a formatted string. -- -- @param prop -- The property definition. -- @param value -- The value of the property to be formatted. -- @returns -- A string value. --- function rule.getPropertyString(self, prop, value) -- list? if type(value) == "table" then local sep = prop.separator or " " return table.concat(value, sep) end -- enum? if prop.values then local i = table.indexof(prop.values, value) return tostring(i) end -- primitive value = tostring(value) if #value > 0 then return value else return nil end end --- -- Set one or more rule variables in the current configuration scope. -- -- @param vars -- A key-value list of variables to set and their corresponding values. --- function rule.setVars(self, vars) for key, value in pairs(vars) do local prop = rule.getProperty(self, key) if not prop then error (string.format("rule '%s' does not have property '%s'", self.name, key)) end local fld = rule.getPropertyField(self, prop) p.api.storeField(fld, value) end end
bsd-3-clause
santssoft/darkstar
scripts/globals/mobskills/bomb_toss_suicide.lua
10
1104
--------------------------------------------------- -- Bomb Toss - Suicide -- Throws a bomb at an enemy. Sometimes backfires. --------------------------------------------- require("scripts/globals/monstertpmoves") require("scripts/globals/settings") require("scripts/globals/status") --------------------------------------------- function onMobSkillCheck(target,mob,skill) -- notorious monsters shouldn't explode, nor dynamis if mob:isMobType(MOBTYPE_NOTORIOUS) or mob:isInDynamis() then return 1 end return 0 end function onMobWeaponSkill(target, mob, skill) local dmgmod = 1 local BOMB_TOSS_HPP = skill:getMobHPP() / 100 local job = mob:getMainJob() local power = math.random(12,18) local info = MobMagicalMove(mob,target,skill,mob:getWeaponDmg()*power*BOMB_TOSS_HPP,dsp.magic.ele.FIRE,dmgmod,TP_MAB_BONUS,1) local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,dsp.attackType.MAGICAL,dsp.damageType.FIRE,MOBPARAM_IGNORE_SHADOWS) mob:setHP(0) target:takeDamage(dmg, mob, dsp.attackType.MAGICAL, dsp.damageType.FIRE) return dmg end
gpl-3.0
wuxianliang/treelstm
util/Tree.lua
9
1126
--[[ A basic tree structure. --]] local Tree = torch.class('treelstm.Tree') function Tree:__init() self.parent = nil self.num_children = 0 self.children = {} end function Tree:add_child(c) c.parent = self self.num_children = self.num_children + 1 self.children[self.num_children] = c end function Tree:size() if self._size ~= nil then return self._size end local size = 1 for i = 1, self.num_children do size = size + self.children[i]:size() end self._size = size return size end function Tree:depth() local depth = 0 if self.num_children > 0 then for i = 1, self.num_children do local child_depth = self.children[i]:depth() if child_depth > depth then depth = child_depth end end depth = depth + 1 end return depth end local function depth_first_preorder(tree, nodes) if tree == nil then return end table.insert(nodes, tree) for i = 1, tree.num_children do depth_first_preorder(tree.children[i], nodes) end end function Tree:depth_first_preorder() local nodes = {} depth_first_preorder(self, nodes) return nodes end
gpl-2.0
m241dan/darkstar
scripts/zones/Port_San_dOria/npcs/Ambleon.lua
13
1061
----------------------------------- -- Area: Port San d'Oria -- NPC: Ambleon -- Type: NPC World Pass Dealer -- @zone: 232 -- @pos 71.622 -17 -137.134 -- -- Auto-Script: Requires Verification (Verified by Brawndo) ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x02c6); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
dpaiton/OpenPV
projects/depthSCANN/input/depthInference/ATA_validate_LCA.lua
2
6847
------------------------------------------------------------------- -- ATA validate for LCA -- -- Sheng Lundquist 6/9/15 -- -- Implements training of ATA method with SCANN model as described in -- Lundquist et al., "Emergence of Depth-Tuned Hidden Units Through -- Sparse Encoding of Binocular Images" ------------------------------------------------------------------- --Util module package.path = package.path .. ";" .. os.getenv("HOME") .. "/workspace/PetaVision/parameterWrapper/?.lua;" local pv = require("PVModule") ------------------------------------------------ -- Parameters -- ------------------------------------------------ -- User defined variables local nxSize = 1200 --Size of image local nySize = 360 local outputPath = "/home/ec2-user/output/depthInference/ATA_validate_LCA/" --Output directory local writePeriod = 1 --How often to write out local stopTime = 93 --Stopping time, last 93 local progressStep = 5; --How often to print out a status report --Image parameters local V1PVP = "/home/ec2-user/saved_output/benchmarkEncoding/V1_LCA.pvp" --V1 activity file local depthImageListPath = "/home/ec2-user/dataset/list/benchmark_depth_noc.txt" --List of images, raw local numDepthBins = 128; --LCA parameters local stride = 2 --Stride of LCA local numDictElements = 512 --Total number of dictionary elements local dictPatchSize = 66 --Square patch, with this as the dimension --ATA previous weights local ATAWeightsDir = "/home/ec2-user/saved_output/depthInference/saved_ATA_LCA/" local pvParams = { --base column column = { groupType = "HyPerCol"; nx = nxSize; ny = nySize; dt = 1.0; randomSeed = 1234567890; startTime = 0; stopTime = stopTime; progressStep = progressStep; outputPath = outputPath; filenamesContainLayerNames = 2; filenamesContainConnectionNames = 2; checkpointRead = false; checkpointWrite = false; suppressLastOutput = false; deleteOlderCheckpoints = true; writeProgressToErr = true; outputNamesOfLayersAndConns = "LayerAndConnNames.txt"; dtAdaptFlag = true; dtScaleMax = 5.0; dtScaleMin = 0.25; dtChangeMax = 0.05; dtChangeMin = 0.0; }; V1_LCA = { groupType = "Movie"; restart = 0; nxScale = .5/stride; nyScale = .5/stride; nf = numDictElements; readPvpFile = true; imageListPath = V1PVP; writeFrameToTimestamp = true; writeStep = -1; sparseLayer = true; writeSparseValues = true; displayPeriod = 1; start_frame_index = 1111; skip_frame_index = 11; echoFramePathnameFlag = true; mirrorBCflag = true; jitterFlag = 0; useImageBCflag = false; inverseFlag = false; normalizeLuminanceFlag = false; writeImages = false; offsetX = 0; offsetY = 0; autoResizeFlag = 0; randomMovie = 0; phase = 0; }; DepthImage = { groupType = "Movie"; restart = 0; nxScale = 1; nyScale = 1; readPvpFile = false; imageListPath = depthImageListPath; writeFrameToTimestamp = true; nf = 1; writeStep = -1; sparseLayer = false; displayPeriod = 1; start_frame_index = 100; skip_frame_index = 1; echoFramePathnameFlag = true; mirrorBCflag = false; jitterFlag = 0; useImageBCflag = false; inverseFlag = false; normalizeLuminanceFlag = false; writeImages = false; offsetAnchor = "br"; offsetX = 0; offsetY = 0; randomMovie = 0; autoResizeFlag = 0; phase = 0; }; DepthDownsample = { groupType = "ANNLayer"; restart = 0; nxScale = .25; nyScale = .25; nf = 1; writeStep = writePeriod; initialWriteTime = writePeriod; mirrorBCflag = false; writeSparseActivity = 0; InitVType = "ZeroV"; VThresh = -INFINITY; VMax = INFINITY; VMin = -INFINITY; VShift = 0; VWidth = 0; phase = 1; }; RCorrBuf = { groupType = "ANNLayer"; restart = 0; nxScale = .5/stride; nyScale = .5/stride; nf = numDepthBins; writeStep = -1.0; initialWriteTime = 1.0; mirrorBCflag = 0; writeSparseActivity = 0; InitVType = "ZeroV"; VThresh = -INFINITY; VMax = INFINITY; VMin = -INFINITY; VShift = 0; VWidth = 0; valueBC = 0; phase = 5; }; RCorrRecon = { groupType = "WTALayer"; restart = 0; nxScale = .5/stride; nyScale = .5/stride; nf = 1; writeStep = 1.0; initialWriteTime = 1.0; mirrorBCflag = false; writeSparseActivity = false; delay = 0; originalLayerName = "RCorrBuf"; phase = 6; }; DepthImageToDepthDownsample = { groupType = "PoolingConn"; preLayerName = "DepthImage"; postLayerName = "DepthDownsample"; channelCode = 0; sharedWeights = true; nxp = 1; nyp = 1; numAxonalArbors = 1; initFromLastFlag = 0; writeStep = -1; initialWriteTime = 0.0; writeCompressedWeights = false; normalizeMethod = "none"; shrinkPatches = false; writeCompressedCheckpoints = false; plasticityFlag = 0; pvpatchAccumulateType = "maxpooling"; delay = 0; convertRateToSpikeCount = false; selfFlag = false; updateGSynFromPostPerspective = false; useWindowPost = false; keepKernelsSynchronized = true; }; V1ToDepthGT = { groupType = "HyPerConn"; preLayerName = "V1_LCA"; postLayerName = "RCorrBuf"; channelCode = -1; nxp = 33; nyp = 33; shrinkPatches = false; numAxonalArbors = 1; initFromLastFlag = 0; weightInitType = "FileWeight"; initWeightsFile = ATAWeightsDir.."/V1ToDepthGT_W.pvp"; strength = 1; normalizeMethod = "none"; preActivityIsNotRate = false; keepKernelsSynchronized = true; combine_dW_with_W_flag = false; writeStep = -1; writeCompressedWeights = false; writeCompressedCheckpoints = false; plasticityFlag = false; weightUpdatePeriod = 1.0; initialWeightUpdateTime = 1.0; initialWriteTime = 0.0; dWMax = 1; selfFlag = false; shmget_flag = false; delay = 0; useWindowPost = false; updateGSynFromPostPerspective = false; pvpatchAccumulateType = "convolve"; useMask = true; maskLayerName = "DepthDownsample"; sharedWeights = true; }; } --Prints out a PetaVision approved parameter file to the console pv.printConsole(pvParams)
epl-1.0
m241dan/darkstar
scripts/zones/Pashhow_Marshlands/npcs/Luck_Rune.lua
13
1050
----------------------------------- -- Area: Pashhow Marshlands -- NPC: Luck Rune -- Involved in Quest: Mhaura Fortune -- @pos 573.245 24.999 199.560 109 ----------------------------------- package.loaded["scripts/zones/Pashhow_Marshlands/TextIDs"] = nil; ------------------------------------- require("scripts/zones/Pashhow_Marshlands/TextIDs"); ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) player:messageSpecial(NOTHING_OUT_OF_THE_ORDINARY); 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
palmettos/test
modules/admin-full/luasrc/model/cbi/admin_system/startup.lua
67
2805
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <[email protected]> Copyright 2010-2012 Jo-Philipp Wich <[email protected]> Copyright 2010 Manuel Munz <freifunk at somakoma dot de> 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.fs" require "luci.sys" require "luci.util" local inits = { } for _, name in ipairs(luci.sys.init.names()) do local index = luci.sys.init.index(name) local enabled = luci.sys.init.enabled(name) if index < 255 then inits["%02i.%s" % { index, name }] = { name = name, index = tostring(index), enabled = enabled } end end m = SimpleForm("initmgr", translate("Initscripts"), translate("You can enable or disable installed init scripts here. Changes will applied after a device reboot.<br /><strong>Warning: If you disable essential init scripts like \"network\", your device might become inaccessible!</strong>")) m.reset = false m.submit = false s = m:section(Table, inits) i = s:option(DummyValue, "index", translate("Start priority")) n = s:option(DummyValue, "name", translate("Initscript")) e = s:option(Button, "endisable", translate("Enable/Disable")) e.render = function(self, section, scope) if inits[section].enabled then self.title = translate("Enabled") self.inputstyle = "save" else self.title = translate("Disabled") self.inputstyle = "reset" end Button.render(self, section, scope) end e.write = function(self, section) if inits[section].enabled then inits[section].enabled = false return luci.sys.init.disable(inits[section].name) else inits[section].enabled = true return luci.sys.init.enable(inits[section].name) end end start = s:option(Button, "start", translate("Start")) start.inputstyle = "apply" start.write = function(self, section) luci.sys.call("/etc/init.d/%s %s >/dev/null" %{ inits[section].name, self.option }) end restart = s:option(Button, "restart", translate("Restart")) restart.inputstyle = "reload" restart.write = start.write stop = s:option(Button, "stop", translate("Stop")) stop.inputstyle = "remove" stop.write = start.write f = SimpleForm("rc", translate("Local Startup"), translate("This is the content of /etc/rc.local. Insert your own commands here (in front of 'exit 0') to execute them at the end of the boot process.")) t = f:field(TextValue, "rcs") t.rmempty = true t.rows = 20 function t.cfgvalue() return luci.fs.readfile("/etc/rc.local") or "" end function f.handle(self, state, data) if state == FORM_VALID then if data.rcs then luci.fs.writefile("/etc/rc.local", data.rcs:gsub("\r\n", "\n")) end end return true end return m, f
apache-2.0
santssoft/darkstar
scripts/zones/Davoi/npcs/Quemaricond.lua
9
1387
----------------------------------- -- Area: Davoi -- NPC: Quemaricond -- Involved in Mission: Infiltrate Davoi -- !pos 23 0.1 -23 149 ----------------------------------- require("scripts/globals/missions"); require("scripts/globals/keyitems"); local ID = require("scripts/zones/Davoi/IDs"); require("scripts/globals/pathfind"); ----------------------------------- local path = { 20.6, 0, -23, 46, 0, -19, 53.5, -1.8, -19, 61, -1.1, -18.6, 67.3, -1.5, -18.6, 90, -0.5, -19 }; function onSpawn(npc) npc:initNpcAi(); npc:setPos(dsp.path.first(path)); onPath(npc); end; function onPath(npc) dsp.path.patrol(npc, path); end; function onTrade(player,npc,trade) end; function onTrigger(player,npc) if (player:getCurrentMission(SANDORIA) == dsp.mission.id.sandoria.INFILTRATE_DAVOI and player:getCharVar("MissionStatus") == 3) then player:startEvent(117); npc:wait(); else player:showText(npc, ID.text.QUEMARICOND_DIALOG); npc:wait(2000); end end; function onEventUpdate(player,csid,option) end; function onEventFinish(player,csid,option,npc) if (csid == 117) then player:setCharVar("MissionStatus",4); player:addKeyItem(dsp.ki.ROYAL_KNIGHTS_DAVOI_REPORT); player:messageSpecial(ID.text.KEYITEM_OBTAINED,dsp.ki.ROYAL_KNIGHTS_DAVOI_REPORT); end npc:wait(0); end;
gpl-3.0