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
hanxi/cocos2d-x-v3.1
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/PhysicsJointRatchet.lua
6
1308
-------------------------------- -- @module PhysicsJointRatchet -- @extend PhysicsJoint -------------------------------- -- @function [parent=#PhysicsJointRatchet] getAngle -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsJointRatchet] setAngle -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsJointRatchet] setPhase -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsJointRatchet] getPhase -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsJointRatchet] setRatchet -- @param self -- @param #float float -------------------------------- -- @function [parent=#PhysicsJointRatchet] getRatchet -- @param self -- @return float#float ret (return value: float) -------------------------------- -- @function [parent=#PhysicsJointRatchet] construct -- @param self -- @param #cc.PhysicsBody physicsbody -- @param #cc.PhysicsBody physicsbody -- @param #float float -- @param #float float -- @return PhysicsJointRatchet#PhysicsJointRatchet ret (return value: cc.PhysicsJointRatchet) return nil
mit
kitala1/darkstar
scripts/zones/Kazham/npcs/Eron-Tomaron.lua
15
3605
----------------------------------- -- Area: Kazham -- NPC: Eron-Tomaron -- Title Change NPC -- @pos -22 -4 -24 250 ----------------------------------- require("scripts/globals/titles"); local title2 = { DISCERNING_INDIVIDUAL , VERY_DISCERNING_INDIVIDUAL , EXTREMELY_DISCERNING_INDIVIDUAL , 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 title3 = { HEIR_OF_THE_GREAT_FIRE , YA_DONE_GOOD , GULLIBLES_TRAVELS , KAZHAM_CALLER , EXCOMMUNICATE_OF_KAZHAM , EVEN_MORE_GULLIBLES_TRAVELS , KING_OF_THE_OPOOPOS , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { FODDERCHIEF_FLAYER , WARCHIEF_WRECKER , DREAD_DRAGON_SLAYER , OVERLORD_EXECUTIONER , DARK_DRAGON_SLAYER , ADAMANTKING_KILLER , BLACK_DRAGON_SLAYER , MANIFEST_MAULER , BEHEMOTHS_BANE , ARCHMAGE_ASSASSIN , HELLSBANE , GIANT_KILLER , LICH_BANISHER , JELLYBANE , BOGEYDOWNER , BEAKBENDER , SKULLCRUSHER , MORBOLBANE , GOLIATH_KILLER , MARYS_GUIDE , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { SIMURGH_POACHER , ROC_STAR , SERKET_BREAKER , CASSIENOVA , THE_HORNSPLITTER , TORTOISE_TORTURER , MON_CHERRY , BEHEMOTH_DETHRONER , THE_VIVISECTOR , DRAGON_ASHER , EXPEDITIONARY_TROOPER , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title6 = { ADAMANTKING_USURPER , OVERLORD_OVERTHROWER , DEITY_DEBUNKER , FAFNIR_SLAYER , ASPIDOCHELONE_SINKER , NIDHOGG_SLAYER , MAAT_MASHER , KIRIN_CAPTIVATOR , CACTROT_DESACELERADOR , LIFTER_OF_SHADOWS , TIAMAT_TROUNCER , VRTRA_VANQUISHER , WORLD_SERPENT_SLAYER , XOLOTL_XTRAPOLATOR , BOROKA_BELEAGUERER , OURYU_OVERWHELMER , VINEGAR_EVAPORATOR , VIRTUOUS_SAINT , BYEBYE_TAISAI , TEMENOS_LIBERATOR , APOLLYON_RAVAGER , WYRM_ASTONISHER , NIGHTMARE_AWAKENER , 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 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x271D,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==0x271D) then if(option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif(option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif(option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title4[option - 512] ) end elseif(option > 768 and option <797) then if (player:delGil(500)) then player:setTitle( title5[option - 768] ) end elseif(option > 1024 and option < 1053) then if (player:delGil(600)) then player:setTitle( title6[option - 1024] ) end end end end;
gpl-3.0
d-o/LUA-LIB
src/rinLibrary/namings.lua
2
3536
------------------------------------------------------------------------------- --- Name encoding and decoding functions. -- Functions intended for internal library use but they might be useful -- to applications. These functions deal with converting names into values -- and the inverse. -- @module rinLibrary.namings -- @author Pauli -- @copyright 2014 Rinstrum Pty Ltd ------------------------------------------------------------------------------- local string = string local tostring = tostring local type = type local lpeg = require 'rinLibrary.lpeg' local Cs, spc = lpeg.Cs, lpeg.space local nspc = 1 - spc local canonPat = spc^0 * Cs(nspc^0 * (spc^1 / ' ' * nspc^1)^0) * spc^0 local canonCache = setmetatable({}, { __mode = "kv" }) ------------------------------------------------------------------------------- -- @param s String to convert -- @return Canonical form for string -- @local local function canonical(s) s = tostring(s) local r = canonCache[s] if r == nil then r = string.lower(canonPat:match(s)) canonCache[s] = r end return r end ------------------------------------------------------------------------------- -- @function canonicalisation -- @string s String to convert -- @treturn string Canonical form for string -- @usage -- print(namings.canonicalisation(' hello WoRlD ')) local _M = { canonicalisation = canonical } ------------------------------------------------------------------------------- -- Convert a named value into a real value but also let real values through -- unmodified. -- @string n Name to be converted -- @tab map Mapping from names to numeric values, names should be lower case canonical form -- @string default Default value to return if something is amiss -- @number l Least value allowed -- @number u Uppermost value allowed -- @treturn number The numeric code associted with the specified name -- @usage -- local name = require 'rinLibrary.namings' -- -- local map = { -- cthulhu = 1, -- hastur = 2, -- nyarlathotep = 3, -- tsathoggua = 4 -- } -- -- print(name.convertNameToValue('Cthulhu', map)) -- print(name.convertNameToValue('shub-niggurath', map, map['hastur'])) -- print(name.convertNameToValue(16, map, map['tsathoggua'], 1, 4)) function _M.convertNameToValue(n, map, default, l, u) local r if type(n) == 'string' then r = map[canonical(n)] or default elseif type(n) == 'number' then r = n else r = default end if l ~= nil and r < l then r = default end if u ~= nil and r > u then r = default end return r end ------------------------------------------------------------------------------- -- Convert a named value into a real value but also let real values through -- unmodified. -- @number n Number to be converted -- @tab map Mapping from numeric values to names, names should be lower case canonical form -- @string default Default value to return if something is amiss -- @treturn string The name associted with the specified code -- @usage -- local name = require 'rinLibrary.namings' -- -- local map = { -- [1] = 'cthulhu', -- [2] = 'hastur', -- [3] = 'nyarlathotep', -- [4] = 'tsathoggua' -- } -- -- print(name.convertNameToValue(2, map)) -- print(name.convertNameToValue(12, map, 'nyarlathotep')) function _M.convertValueToName(n, map, default) if type(n) == 'string' then return canonical(n) elseif type(n) == 'number' then return map[n] or default end return default end return _M
gpl-3.0
CopierTeam/Umbrella-Cp
plugins/Time.lua
5
2600
api_key = nil base_api = "https://maps.googleapis.com/maps/api" dateFormat = "%A %d %B - %H:%M:%S" -- Need the utc time for the google api function utctime() return os.time(os.date("!*t")) end -- Use the geocoding api to get the lattitude and longitude with accuracy specifier -- CHECKME: this seems to work without a key?? function get_latlong(area) local api = base_api .. "/geocode/json?" local parameters = "address=".. (URL.escape(area) or "") if api_key ~= nil then parameters = parameters .. "&key="..api_key end -- Do the request local res, code = https.request(api..parameters) if code ~=200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Get the data lat = data.results[1].geometry.location.lat lng = data.results[1].geometry.location.lng acc = data.results[1].geometry.location_type types= data.results[1].types return lat,lng,acc,types end end -- Use timezone api to get the time in the lat, -- Note: this needs an API key function get_time(lat,lng) local api = base_api .. "/timezone/json?" -- Get a timestamp (server time is relevant here) local timestamp = utctime() local parameters = "location=" .. URL.escape(lat) .. "," .. URL.escape(lng) .. "&timestamp="..URL.escape(timestamp) if api_key ~=nil then parameters = parameters .. "&key="..api_key end local res,code = https.request(api..parameters) if code ~= 200 then return nil end local data = json:decode(res) if (data.status == "ZERO_RESULTS") then return nil end if (data.status == "OK") then -- Construct what we want -- The local time in the location is: -- timestamp + rawOffset + dstOffset local localTime = timestamp + data.rawOffset + data.dstOffset return localTime, data.timeZoneId end return localTime end function getformattedLocalTime(area) if area == nil then return "The time in nowhere is never" end lat,lng,acc = get_latlong(area) if lat == nil and lng == nil then return 'It seems that in "'..area..'" they do not have a concept of time.' end local localTime, timeZoneId = get_time(lat,lng) return "منطقه : "..timeZoneId.."\nزمان و تاریخ : ".. os.date(dateFormat,localTime) end function run(msg, matches) return getformattedLocalTime(matches[1]) end return { description = "Displays the local time in an area", usage = "time [area]: Displays the local time in that area", patterns = {"^[Tt]ime (.*)$"}, run = run }
gpl-2.0
kitala1/darkstar
scripts/zones/Windurst_Woods/npcs/Perih_Vashai.lua
17
6983
----------------------------------- -- Area: Windurst Woods -- NPC: Parih Vashai -- Starts and Finishes Quest: The Fanged One -- @zone 241 -- @pos 117 -3 92 ----------------------------------- package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Windurst_Woods/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(trade:hasItemQty(1113,1) and trade:getItemCount() == 1) then -- Trade old earring (complete Rng AF2 quest) local FireAndBrimstoneCS = player:getVar("fireAndBrimstone"); if (FireAndBrimstoneCS == 5) then player:startEvent(0x0219, 0, 13360); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TheFangedOne = player:getQuestStatus(WINDURST,THE_FANGED_ONE); -- RNG flag quest local SinHunting = player:getQuestStatus(WINDURST,SIN_HUNTING); -- RNG AF1 local SinHuntingCS = player:getVar("sinHunting"); local FireAndBrimstone = player:getQuestStatus(WINDURST,FIRE_AND_BRIMSTONE); -- RNG AF2 local FireAndBrimstoneCS = player:getVar("fireAndBrimstone"); local UnbridledPassion = player:getQuestStatus(WINDURST,UNBRIDLED_PASSION); -- RNG AF3 local UnbridledPassionCS = player:getVar("unbridledPassion"); local LvL = player:getMainLvl(); local Job = player:getMainJob(); -- COP mission if(player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Louverance_s_Path") == 1) then player:startEvent(0x02AE); -- the fanged one elseif(TheFangedOne ~= QUEST_COMPLETED) then if(TheFangedOne == QUEST_AVAILABLE and player:getMainLvl() >= ADVANCED_JOB_LEVEL) then player:startEvent(0x015f); elseif(TheFangedOne == QUEST_ACCEPTED and player:hasKeyItem(OLD_TIGERS_FANG) == false) then player:startEvent(0x0160); elseif(player:hasKeyItem(OLD_TIGERS_FANG) and player:getVar("TheFangedOne_Event") ~= 1) then player:startEvent(0x0165); elseif(player:getVar("TheFangedOne_Event") == 1) then player:startEvent(0x0166); end -- sin hunting elseif(SinHunting == QUEST_AVAILABLE and Job == 11 and LvL >= 40 and SinHuntingCS == 0) then player:startEvent(0x020b); -- start RNG AF1 elseif(SinHuntingCS > 0 and SinHuntingCS < 5) then player:startEvent(0x020c); -- during quest RNG AF1 elseif(SinHuntingCS == 5) then player:startEvent(0x020f); -- complete quest RNG AF1 -- fire and brimstone elseif(SinHunting == QUEST_COMPLETED and Job == 11 and FireAndBrimstone == QUEST_AVAILABLE and FireAndBrimstoneCS == 0) then player:startEvent(0x0213); -- start RNG AF2 elseif(FireAndBrimstoneCS > 0 and FireAndBrimstoneCS < 4) then player:startEvent(0x0214); -- during RNG AF2 elseif(FireAndBrimstoneCS == 4) then player:startEvent(0x0217,0,13360,1113); -- second part RNG AF2 elseif(FireAndBrimstoneCS == 5) then player:startEvent(0x0218); -- during second part RNG AF2 -- Unbridled Passion elseif(FireAndBrimstone == QUEST_COMPLETED and Job == 11 and UnbridledPassion == QUEST_AVAILABLE and UnbridledPassion == 0) then player:startEvent(0x021d, 0, 13360); -- start RNG AF3 elseif(UnbridledPassionCS > 0 and UnbridledPassionCS < 3) then player:startEvent(0x021e); -- during RNG AF3 elseif(UnbridledPassionCS >= 3 and UnbridledPassionCS < 7) then player:startEvent(0x021e); -- during RNG AF3 elseif(UnbridledPassionCS == 7) then player:startEvent(0x0222, 0, 14099); -- complete RNG AF3 -- standard dialog else player:startEvent(0x0152); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x015f) then player:addQuest(WINDURST,THE_FANGED_ONE); elseif(csid == 0x0165 or csid == 0x0166) then if(player:getFreeSlotsCount(0) >= 1 and player:hasItem(13117) == false) then player:delKeyItem(OLD_TIGERS_FANG); player:setVar("TheFangedOne_Event",0); player:setVar("TheFangedOne_Died",0); player:addTitle(THE_FANGED_ONE); player:addItem(13117); player:messageSpecial(ITEM_OBTAINED,13117); player:unlockJob(11); player:messageSpecial(PERIH_VASHAI_DIALOG); player:addFame(WINDURST, WIN_FAME* 30); player:completeQuest(WINDURST,THE_FANGED_ONE); else player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13117); player:setVar("TheFangedOne_Event",1); end elseif(csid == 0x020b) then -- start quest RNG AF1 player:addQuest(WINDURST,SIN_HUNTING); player:addKeyItem(CHIEFTAINNESS_TWINSTONE_EARRING); player:messageSpecial(KEYITEM_OBTAINED,CHIEFTAINNESS_TWINSTONE_EARRING); player:setVar("sinHunting",1); elseif(csid == 0x020f) then -- complete quest RNG AF1 if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,17188); else player:addItem(17188); player:messageSpecial(ITEM_OBTAINED,17188); player:completeQuest(WINDURST,SIN_HUNTING); player:delKeyItem(CHIEFTAINNESS_TWINSTONE_EARRING); player:delKeyItem(PERCHONDS_ENVELOPE); player:setVar("sinHunting",0); end elseif(csid == 0x0213) then -- start RNG AF2 player:addQuest(WINDURST,FIRE_AND_BRIMSTONE); player:setVar("fireAndBrimstone",1); elseif(csid == 0x0217) then -- start second part RNG AF2 player:setVar("fireAndBrimstone",5); elseif(csid == 0x0219) then -- complete quest RNG AF2 if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12518); else player:tradeComplete(); player:addItem(12518); player:messageSpecial(ITEM_OBTAINED,12518); player:completeQuest(WINDURST,FIRE_AND_BRIMSTONE); player:setVar("fireAndBrimstone",0); end elseif(csid == 0x021d) then -- start RNG AF3 player:addQuest(WINDURST,UNBRIDLED_PASSION); player:setVar("unbridledPassion",1); elseif(csid == 0x0222) then -- complete quest RNG AF3 if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,14099); else player:addItem(14099); player:messageSpecial(ITEM_OBTAINED,14099); player:completeQuest(WINDURST,UNBRIDLED_PASSION); player:delKeyItem(KOHS_LETTER); player:setVar("unbridledPassion",0); end elseif(csid == 0x02AE) then player:setVar("COP_Louverance_s_Path",2); end end;
gpl-3.0
zhaoluxyz/Hugula
Client/Assets/Lua/const/importClass.lua
5
1263
------------------------------------------------ -- Copyright © 2013-2014 Hugula: Arpg game Engine -- -- author pu ------------------------------------------------ -- local luanet=luanet -- UnityEngine=luanet.UnityEngine local UnityEngine = UnityEngine ----------------------global------------------------- GameObject=UnityEngine.GameObject -- Vector3=UnityEngine.Vector3 -- Quaternion = UnityEngine.Quaternion local Resources = UnityEngine.Resources -----------------------init--------------------------- -- iTween = luanet.import_type("iTween") LeanTweenType=LeanTweenType ------------------------------static 变量--------------------------- LeanTween=LeanTween Random = UnityEngine.Random CUtils=CUtils --luanet.import_type("CUtils") -- --LCUtils -- LuaHelper=LuaHelper --LLuaHelper --luanet.import_type("LuaHelper") toluaiTween=iTween -- PLua = luanet.import_type("PLua") Net= LNet.instance -- luanet.import_type("LNet").instance -- Msg=luanet.import_type("Msg") Request=LRequest --luanet.import_type("LRequest") local LocalizationMy = Localization --获取语言包内容 function getValue(key) return LocalizationMy.Get(key) end --释放没使用的资源 function unloadUnusedAssets() luaGC() Resources.UnloadUnusedAssets() end
mit
kitala1/darkstar
scripts/zones/Kazham/npcs/Dakha_Topsalwan.lua
20
1147
----------------------------------- -- Area: Kazham -- NPC: Dakha Topsalwan -- @zone 250 -- @pos ----------------------------------- package.loaded["scripts/zones/Kazham/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/Kazham/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) Z = player:getZPos(); if(Z >= -20 and Z <= -16) then player:startEvent(0x0042); else player:startEvent(0x0079); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Cape_Teriggan/Zone.lua
28
2719
----------------------------------- -- -- Zone: Cape_Teriggan (113) -- ----------------------------------- package.loaded[ "scripts/zones/Cape_Teriggan/TextIDs"] = nil; ----------------------------------- require("scripts/zones/Cape_Teriggan/TextIDs"); require("scripts/globals/icanheararainbow"); require("scripts/globals/weather"); require("scripts/globals/zone"); require("scripts/globals/conquest"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) local manuals = {17240513,17240514}; SetFieldManual(manuals); -- Kreutzet SetRespawnTime(17240413, 900, 10800); SetRegionalConquestOverseers(zone:getRegionID()) end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn( player, prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos( 315.644, -1.517, -60.633, 108); end if (triggerLightCutscene(player)) then -- Quest: I Can Hear A Rainbow cs = 0x0002; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter( player, region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0002) then lightCutsceneUpdate(player); -- Quest: I Can Hear A Rainbow end end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish( player, csid, option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid == 0x0002) then lightCutsceneFinish(player); -- Quest: I Can Hear A Rainbow end end; ----------------------------------- -- onZoneWeatherChange ----------------------------------- function onZoneWeatherChange(weather) if (GetMobAction(17240413) == 24 and (weather == WEATHER_WIND or weather == WEATHER_GALES)) then SpawnMob(17240413); -- Kreutzet elseif (GetMobAction(17240413) == 16 and (weather ~= WEATHER_WIND and weather ~= WEATHER_GALES)) then DespawnMob(17240413); end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Mine_Shaft_2716/npcs/_0d0.lua
12
1980
----------------------------------- -- Area: Mine_Shaft_2716 -- NPC: Shaft entrance ----------------------------------- package.loaded["scripts/zones/Mine_Shaft_2716/TextIDs"] = nil; ----------------------------------- require("scripts/globals/bcnm"); require("scripts/globals/quests"); require("scripts/globals/missions"); require("scripts/zones/Mine_Shaft_2716/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getCurrentMission(COP) == THREE_PATHS and ( player:getVar("COP_Louverance_s_Path") == 7 or player:getVar("COP_Louverance_s_Path") == 8 ))then if(trade:getItemCount() == 1 and trade:hasItemQty(1684,1)) then player:startEvent(0x0003); end elseif(TradeBCNM(player,player:getZoneID(),trade,npc))then return; end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if(player:getCurrentMission(COP) ==FIRE_IN_THE_EYES_OF_MEN and player:getVar("PromathiaStatus")==0)then player:startEvent(0x0004); elseif(EventTriggerBCNM(player,npc))then end return 1; end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("onUpdate CSID: %u",csid); --printf("onUpdate RESULT: %u",option); if(EventUpdateBCNM(player,csid,option))then return; end end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) --printf("onFinish CSID: %u",csid); --printf("onFinish RESULT: %u",option); if(csid ==0x0003)then player:setVar("COP_Louverance_s_Path",9); player:tradeComplete(); elseif(csid ==0x0004)then player:setVar("PromathiaStatus",1); elseif(EventFinishBCNM(player,csid,option))then return; end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Upper_Delkfutts_Tower/TextIDs.lua
3
1129
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6414; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6417; -- Obtained: <item>. GIL_OBTAINED = 6418; -- Obtained <number> gil. KEYITEM_OBTAINED = 6420; -- Obtained key item: <keyitem>. FISHING_MESSAGE_OFFSET = 7071; -- You can't fish here. -- Treasure Coffer/Chest Dialog CHEST_UNLOCKED = 7332; -- You unlock the chest! CHEST_FAIL = 7333; -- Fails to open the chest. CHEST_TRAP = 7334; -- The chest was trapped! CHEST_WEAK = 7335; -- You cannot open the chest when you are in a weakened state. CHEST_MIMIC = 7336; -- The chest was a mimic! CHEST_MOOGLE = 7337; -- You cannot open the chest while participating in the moogle event. CHEST_ILLUSION = 7338; -- The chest was but an illusion... CHEST_LOCKED = 7339; -- The chest appears to be locked. -- Other Dialog THIS_ELEVATOR_GOES_DOWN = 25; -- This elevator goes down, but it is locked. Perhaps a key is needed to activate it. -- conquest Base CONQUEST_BASE = 7166; -- Tallying conquest results...
gpl-3.0
kitala1/darkstar
scripts/globals/weaponskills/mordant_rime.lua
12
4867
----------------------------------- -- Mordant Rime -- Dagger weapon skill -- Skill level: N/A -- Description: Delivers a twofold attack that decreases target's movement speed. Chance of decreasing movement speed varies with TP. Carnwenhan: Aftermath effect varies with TP. -- Aligned with the Breeze Gorget, Thunder Gorget, Aqua Gorget & Snow Gorget. -- Aligned with the Breeze Belt, Thunder Belt, Aqua Belt & Snow Belt. -- Element: None -- Skillchain Properties: Fragmentation/Distortion -- Modifiers: DEX:30% ; CHR:70% -- Damage Multipliers by TP: -- 100%TP 200%TP 300%TP -- 5.0 5.0 5.0 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 2; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.0; params.dex_wsc = 0.3; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.0; params.chr_wsc = 0.5; 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; local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then params.ftp100 = 5; params.ftp200 = 5; params.ftp300 = 5; params.chr_wsc = 0.7; end local chance = player:getTP()-100 > math.random()*150; if(damage > 0 and chance) and (target:hasStatusEffect(EFFECT_WEIGHT) == false) then target:addStatusEffect(EFFECT_WEIGHT, 50, 0, 60); end if((player:getEquipID(SLOT_MAIN) == 19000) and (player:getMainJob() == JOB_BRD)) then if(damage > 0) then -- AFTERMATH LV1 if ((player:getTP() >= 100) and (player:getTP() <= 110)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 10, 0, 180, 0, 2); elseif ((player:getTP() >= 111) and (player:getTP() <= 120)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 11, 0, 180, 0, 2); elseif ((player:getTP() >= 121) and (player:getTP() <= 130)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 12, 0, 180, 0, 2); elseif ((player:getTP() >= 131) and (player:getTP() <= 140)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 13, 0, 180, 0, 2); elseif ((player:getTP() >= 141) and (player:getTP() <= 150)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 14, 0, 180, 0, 2); elseif ((player:getTP() >= 151) and (player:getTP() <= 160)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 15, 0, 180, 0, 2); elseif ((player:getTP() >= 161) and (player:getTP() <= 170)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 16, 0, 180, 0, 2); elseif ((player:getTP() >= 171) and (player:getTP() <= 180)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 17, 0, 180, 0, 2); elseif ((player:getTP() >= 181) and (player:getTP() <= 190)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 18, 0, 180, 0, 2); elseif ((player:getTP() >= 191) and (player:getTP() <= 199)) then player:addStatusEffect(EFFECT_AFTERMATH_LV1, 19, 0, 180, 0, 2); -- AFTERMATH LV2 elseif ((player:getTP() >= 200) and (player:getTP() <= 210)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 24, 0, 180, 0, 2); elseif ((player:getTP() >= 211) and (player:getTP() <= 219)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 28, 0, 180, 0, 2); elseif ((player:getTP() >= 221) and (player:getTP() <= 229)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 32, 0, 180, 0, 2); elseif ((player:getTP() >= 231) and (player:getTP() <= 239)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 36, 0, 180, 0, 2); elseif ((player:getTP() >= 241) and (player:getTP() <= 249)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 40, 0, 180, 0, 2); elseif ((player:getTP() >= 251) and (player:getTP() <= 259)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 44, 0, 180, 0, 2); elseif ((player:getTP() >= 261) and (player:getTP() <= 269)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 48, 0, 180, 0, 2); elseif ((player:getTP() >= 271) and (player:getTP() <= 279)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 52, 0, 180, 0, 2); elseif ((player:getTP() >= 281) and (player:getTP() <= 289)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 56, 0, 180, 0, 2); elseif ((player:getTP() >= 291) and (player:getTP() <= 299)) then player:addStatusEffect(EFFECT_AFTERMATH_LV2, 59, 0, 180, 0, 2); -- AFTERMATH LV3 elseif ((player:getTP() == 300)) then player:addStatusEffect(EFFECT_AFTERMATH_LV3, 45, 0, 120, 0, 1); end end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
kitala1/darkstar
scripts/zones/Beadeaux/npcs/qm2.lua
17
1459
-------------------------- -- Area: Beadeaux -- NPC: ??? (qm2) -- Type: Quest NPC -- @pos -79 1 -99 147 -------------------------- package.loaded["scripts/zones/Beadeaux/TextIDs"] = nil; -------------------------- require("scripts/zones/Beadeaux/TextIDs"); require("scripts/globals/keyitems"); require("scripts/globals/weather"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- TODO: The ??? should only spawn during rainy weather, temporary fix in place to prevent players from getting the keyitem unless the proper weather is present. if(player:getQuestStatus(BASTOK,BEADEAUX_SMOG) == QUEST_ACCEPTED and player:hasKeyItem(CORRUPTED_DIRT) == false and player:getWeather() == WEATHER_RAIN) then player:addKeyItem(CORRUPTED_DIRT); player:messageSpecial(KEYITEM_OBTAINED,CORRUPTED_DIRT); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Northern_San_dOria/npcs/Arnau.lua
12
1723
----------------------------------- -- Area: Northern San d'Oria -- NPC: Arnau -- Involved in Mission: Save the Children -- @pos 148 0 139 231 ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/missions"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (player:getCurrentMission(COP) == THE_ROAD_FORKS and player:getVar("EMERALD_WATERS_Status") == 2)then player:startEvent(0x0033); --COP event elseif(player:getCurrentMission(SANDORIA) == SAVE_THE_CHILDREN and player:getVar("MissionStatus") < 2) then player:startEvent(0x02b5); elseif(player:hasCompletedMission(SANDORIA,SAVE_THE_CHILDREN) and player:getVar("OptionalCSforSTC") == 1) then player:startEvent(0x02b6); else player:startEvent(0x0014); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if(csid == 0x0033)then player:setVar("EMERALD_WATERS_Status",3); elseif (csid == 0x02b5) then player:setVar("MissionStatus",2); elseif (csid == 0x02b6) then player:setVar("OptionalCSforSTC",0); end end;
gpl-3.0
Firef0x/burg-new
util/osdetect.lua
4
3450
#!lua -- -- Copyright (C) 2009 Free Software Foundation, Inc. -- -- GRUB 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. -- -- GRUB 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 GRUB. If not, see <http://www.gnu.org/licenses/>. -- function enum_device (device, fs, uuid) local root local title local source local kernels = {} local kernel_num = 0 local function enum_file (name) local version version = string.match (name, "vmlinuz%-(.*)") if (version ~= nil) then table.insert (kernels, version) kernel_num = kernel_num + 1 end end local function sort_kernel (first, second) local a1, a2, a3, a4, b1, b2, b3, b4 a1, a2, a3, a4 = string.match (first, "(%d+)%.?(%d*).?(%d*)%-?(%d*)") b1, b2, b3, b4 = string.match (second, "(%d+)%.?(%d*).?(%d*)%-?(%d*)") return (a1 > b1) or (a2 > b2) or (a3 > b3) or (a4 < b4); end root = "(" .. device .. ")/" source = "root (" .. device .. ")\nchainloader +1" title = nil if (grub.file_exist (root .. "bootmgr") and grub.file_exist (root .. "boot/bcd")) then title = "Windows Vista bootmgr" elseif (grub.file_exist (root .. "ntldr") and grub.file_exist (root .. "ntdetect.com") and grub.file_exist (root .. "boot.ini")) then title = "Windows NT/2000/XP loader" elseif (grub.file_exist (root .. "windows/win.com")) then title = "Windows 98/ME" elseif (grub.file_exist (root .. "io.sys") and grub.file_exist (root .. "command.com")) then title = "MS-DOS" elseif (grub.file_exist (root .. "kernel.sys")) then title = "FreeDOS" elseif (grub.file_exist (root .. "boot/loader") and grub.file_exist (root .. "boot/device.hints")) then source = "root (" .. device .. ")\nfreebsd /boot/loader" .. "\nfreebsd_loadenv /boot/device.hints" title = "FreeBSD" else grub.enum_file (enum_file, root .. "boot") if kernel_num ~= 0 then table.sort (kernels, sort_kernel) for i = 1, kernel_num do local initrd title = "Linux " .. kernels[i] source = "root (" .. device .. ")\nlinux /boot/vmlinuz-" .. kernels[i] .. " root=UUID=" .. uuid .. " ro" if grub.file_exist (root .. "boot/initrd-" .. kernels[i] .. ".img") then initrd = "\ninitrd /boot/initrd-" .. kernels[i] .. ".img" elseif grub.file_exist (root .. "boot/initrd.img-" .. kernels[i]) then initrd = "\ninitrd /boot/initrd.img-" .. kernels[i] elseif grub.file_exist (root .. "boot/initrd-" .. kernels[i]) then initrd = "\ninitrd /boot/initrd-" .. kernels[i] else initrd = "" end grub.add_menu (source .. initrd, title) grub.add_menu (source .. " single" .. initrd, title .. " (single-user mode)") end return 0 end end if title == nil then local partition = string.match (device, ".*,(%d+)") if (partition ~= nil) and (tonumber (partition) > 4) then return 0 end title = "Other OS" end grub.add_menu (source, title) return 0 end grub.enum_device (enum_device)
gpl-3.0
fqrouter/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk/meetme.lua
80
1246
--[[ LuCI - Lua Configuration Interface Copyright 2009 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ast = require "luci.asterisk" cbimap = Map("asterisk", "MeetMe - Rooms") meetme = cbimap:section(TypedSection, "meetme", "MeetMe Rooms") meetme.addremove = true meetme.anonymous = true meetme.template = "cbi/tblsection" meetme:option(Value, "_description", "Description", "Short room description") room = meetme:option(Value, "room", "Room Number", "Unique room identifier") function room.write(self, s, val) if val and #val > 0 then local old = self:cfgvalue(s) self.map.uci:foreach("asterisk", "dialplanmeetme", function(v) if v.room == old then self.map:set(v['.name'], "room", val) end end) Value.write(self, s, val) end end meetme:option(Value, "pin", "PIN", "PIN required to access") meetme:option(Value, "adminpin", "Admin PIN", "PIN required for administration") function meetme.remove(self, s) return ast.meetme.remove(self.map:get(s, "room"), self.map.uci) end return cbimap
apache-2.0
kitala1/darkstar
scripts/zones/Norg/npcs/Quntsu-Nointsu.lua
15
2845
----------------------------------- -- Area: Norg -- NPC: Quntsu-Nointsu -- Title Change NPC -- @pos -67 -1 34 252 ----------------------------------- require("scripts/globals/titles"); local title2 = { HONORARY_DOCTORATE_MAJORING_IN_TONBERRIES , BUSHIDO_BLADE , BLACK_MARKETEER , CRACKER_OF_THE_SECRET_CODE , LOOKS_SUBLIME_IN_A_SUBLIGAR , LOOKS_GOOD_IN_LEGGINGS , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title3 = { APPRENTICE_SOMMELIER , TREASUREHOUSE_RANSACKER , HEIR_OF_THE_GREAT_WATER , PARAGON_OF_SAMURAI_EXCELLENCE , PARAGON_OF_NINJA_EXCELLENCE , GUIDER_OF_SOULS_TO_THE_SANCTUARY , BEARER_OF_BONDS_BEYOND_TIME , FRIEND_OF_THE_OPOOPOS , PENTACIDE_PERPETRATOR , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title4 = { BEARER_OF_THE_WISEWOMANS_HOPE , BEARER_OF_THE_EIGHT_PRAYERS , LIGHTWEAVER , DESTROYER_OF_ANTIQUITY , SEALER_OF_THE_PORTAL_OF_THE_GODS , BURIER_OF_THE_ILLUSION , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 , 0 } local title5 = { 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 } local title6 = { 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 } 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 } ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x03F3,npcUtil.genTmask(player,title2),npcUtil.genTmask(player,title3),npcUtil.genTmask(player,title4),npcUtil.genTmask(player,title5),npcUtil.genTmask(player,title6),npcUtil.genTmask(player,title7),1 ,player:getGil()); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if (csid==0x03F3) then if(option > 0 and option <29) then if (player:delGil(200)) then player:setTitle( title2[option] ) end elseif(option > 256 and option <285) then if (player:delGil(300)) then player:setTitle( title3[option - 256] ) end elseif(option > 512 and option < 541) then if (player:delGil(400)) then player:setTitle( title4[option - 512] ) end end end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Northern_San_dOria/npcs/Aurege.lua
38
1960
----------------------------------- -- Area: Northern San d'Oria -- NPC: Aurege -- Type: Quest Giver NPC -- Starts Quest: Exit the Gambler -- @zone: 231 -- @pos -156.253 11.999 253.691 ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/keyitems"); require("scripts/globals/titles"); package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) exitTheGambler = player:getQuestStatus(SANDORIA,EXIT_THE_GAMBLER); if (player:hasKeyItem(MAP_OF_KING_RANPERRES_TOMB)) then player:startEvent(0x0202); elseif (exitTheGambler == QUEST_COMPLETED) then player:startEvent(0x0204); else player:startEvent(0x0209); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); exitTheGambler = player:getQuestStatus(SANDORIA,EXIT_THE_GAMBLER); if (exitTheGambler == QUEST_AVAILABLE) then player:addQuest(SANDORIA,EXIT_THE_GAMBLER); elseif (exitTheGambler == QUEST_COMPLETED and player:hasKeyItem(MAP_OF_KING_RANPERRES_TOMB) == false) then player:messageSpecial(KEYITEM_OBTAINED,MAP_OF_KING_RANPERRES_TOMB); player:addKeyItem(MAP_OF_KING_RANPERRES_TOMB); player:addTitle(DAYBREAK_GAMBLER); player:addFame(SANDORIA,SAN_FAME*30); end end;
gpl-3.0
kiarash14/be
plugins/service_entergroup.lua
279
2147
local add_user_cfg = load_from_file('data/add_user_cfg.lua') local function template_add_user(base, to_username, from_username, chat_name, chat_id) base = base or '' to_username = '@' .. (to_username or '') from_username = '@' .. (from_username or '') chat_name = chat_name or '' chat_id = "chat#id" .. (chat_id or '') if to_username == "@" then to_username = '' end if from_username == "@" then from_username = '' end base = string.gsub(base, "{to_username}", to_username) base = string.gsub(base, "{from_username}", from_username) base = string.gsub(base, "{chat_name}", chat_name) base = string.gsub(base, "{chat_id}", chat_id) return base end function chat_new_user_link(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.from.username local from_username = '[link](@' .. (msg.action.link_issuer.username or '') .. ')' local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end function chat_new_user(msg) local pattern = add_user_cfg.initial_chat_msg local to_username = msg.action.user.username local from_username = msg.from.username local chat_name = msg.to.print_name local chat_id = msg.to.id pattern = template_add_user(pattern, to_username, from_username, chat_name, chat_id) if pattern ~= '' then local receiver = get_receiver(msg) send_msg(receiver, pattern, ok_cb, false) end end local function run(msg, matches) if not msg.service then return "Are you trying to troll me?" end if matches[1] == "chat_add_user" then chat_new_user(msg) elseif matches[1] == "chat_add_user_link" then chat_new_user_link(msg) end end return { description = "Service plugin that sends a custom message when an user enters a chat.", usage = "", patterns = { "^!!tgservice (chat_add_user)$", "^!!tgservice (chat_add_user_link)$" }, run = run }
gpl-2.0
kitala1/darkstar
scripts/zones/North_Gustaberg_[S]/Zone.lua
12
1336
----------------------------------- -- -- Zone: North_Gustaberg_[S] (88) -- ----------------------------------- package.loaded["scripts/zones/North_Gustaberg_[S]/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/zones/North_Gustaberg_[S]/TextIDs"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; if (player:getXPos() == 0 and player:getYPos() == 0 and player:getZPos() == 0) then player:setPos(380.038,-2.25,147.627,192); end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
lvdmaaten/nn
Add.lua
61
1699
local Add, parent = torch.class('nn.Add', 'nn.Module') function Add:__init(inputSize,scalar) parent.__init(self) local size = inputSize if scalar then size=1 end self.scalar = scalar self.bias = torch.Tensor(size) self.gradBias = torch.Tensor(size) self._ones = torch.Tensor{1} self:reset() end function Add:reset(stdv) if stdv then stdv = stdv * math.sqrt(3) else stdv = 1./math.sqrt(self.bias:size(1)) end self.bias:uniform(-stdv, stdv) end function Add:updateOutput(input) self.output:resizeAs(input):copy(input) if self.scalar then self.output:add(self.bias[1]); else if input:isSameSizeAs(self.bias) then self.output:add(self.bias) else local batchSize = input:size(1) if self._ones:size(1) ~= batchSize then self._ones:resize(batchSize):fill(1) end local bias = self.bias:view(-1) local output = self.output:view(batchSize, -1) output:addr(1, self._ones, bias) end end return self.output end function Add:updateGradInput(input, gradOutput) if self.gradInput then self.gradInput:resizeAs(gradOutput):copy(gradOutput) return self.gradInput end end function Add:accGradParameters(input, gradOutput, scale) scale = scale or 1 if self.gradBias:size(1) == 1 then self.gradBias[1] = self.gradBias[1] + scale*gradOutput:sum(); else if input:isSameSizeAs(self.bias) then self.gradBias:add(scale, gradOutput) else local gradOutput = gradOutput:view(input:size(1), -1) self.gradBias:view(-1):addmv(scale, gradOutput:t(), self._ones) end end end
bsd-3-clause
kitala1/darkstar
scripts/zones/Crawlers_Nest/npcs/Treasure_Chest.lua
12
3190
----------------------------------- -- Area: Crawler Nest -- NPC: Treasure Chest -- Involved In Quest: Enveloped in Darkness -- @pos 41 0.1 -314 197 ----------------------------------- package.loaded["scripts/zones/Crawlers_Nest/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/treasure"); require("scripts/zones/Crawlers_Nest/TextIDs"); local TreasureType = "Chest"; local TreasureLvL = 43; local TreasureMinLvL = 33; ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- trade:hasItemQty(1040,1); -- Treasure Key -- trade:hasItemQty(1115,1); -- Skeleton Key -- trade:hasItemQty(1023,1); -- Living Key -- trade:hasItemQty(1022,1); -- Thief's Tools local questItemNeeded = 0; -- Player traded a key. if((trade:hasItemQty(1040,1) or trade:hasItemQty(1115,1) or trade:hasItemQty(1023,1) or trade:hasItemQty(1022,1)) and trade:getItemCount() == 1) then local zone = player:getZoneID(); -- IMPORTANT ITEM: AF2 RDM QUEST ----------- if(player:getVar("needs_crawler_blood") == 1) then questItemNeeded = 1; end -------------------------------------- local pack = openChance(player,npc,trade,TreasureType,TreasureLvL,TreasureMinLvL,questItemNeeded); local success = 0; if(pack[2] ~= nil) then player:messageSpecial(pack[2]); success = pack[1]; else success = pack[1]; end if(success ~= -2) then player:tradeComplete(); if(math.random() <= success) then -- Succeded to open the coffer player:messageSpecial(CHEST_UNLOCKED); if(questItemNeeded == 1) then player:addKeyItem(CRAWLER_BLOOD); player:messageSpecial(KEYITEM_OBTAINED,CRAWLER_BLOOD); -- Crawler Blood (KI) player:setVar("needs_crawler_blood",0); else player:setVar("["..zone.."]".."Treasure_"..TreasureType,os.time() + math.random(CHEST_MIN_ILLUSION_TIME,CHEST_MAX_ILLUSION_TIME)); local loot = chestLoot(zone,npc); -- print("loot array: "); -- debug -- print("[1]", loot[1]); -- debug -- print("[2]", loot[2]); -- debug if(loot[1]=="gil") then player:addGil(loot[2]*GIL_RATE); player:messageSpecial(GIL_OBTAINED,loot[2]*GIL_RATE); else -- Item player:addItem(loot[2]); player:messageSpecial(ITEM_OBTAINED,loot[2]); end end UpdateTreasureSpawnPoint(npc:getID()); end end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:messageSpecial(CHEST_LOCKED,1040); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Port_San_dOria/npcs/Bricorsant.lua
36
1376
----------------------------------- -- Area: Port San d'Oria -- NPC: Bricorsant -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x23a); 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
TeleDALAD/2DALAD2
plugins/anti_spam.lua
923
3750
--An empty table for solving multiple kicking problem(thanks to @topkecleon ) kicktable = {} do local TIME_CHECK = 2 -- seconds local data = load_data(_config.moderation.data) -- Save stats, ban user local function pre_process(msg) -- Ignore service msg if msg.service then return msg end if msg.from.id == our_id then return msg end -- Save user on Redis if msg.from.type == 'user' then local hash = 'user:'..msg.from.id print('Saving user', hash) if msg.from.print_name then redis:hset(hash, 'print_name', msg.from.print_name) end if msg.from.first_name then redis:hset(hash, 'first_name', msg.from.first_name) end if msg.from.last_name then redis:hset(hash, 'last_name', msg.from.last_name) end end -- Save stats on Redis if msg.to.type == 'chat' then -- User is on chat local hash = 'chat:'..msg.to.id..':users' redis:sadd(hash, msg.from.id) end -- Total user msgs local hash = 'msgs:'..msg.from.id..':'..msg.to.id redis:incr(hash) --Load moderation data local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then --Check if flood is one or off if data[tostring(msg.to.id)]['settings']['flood'] == 'no' then return msg end end -- Check flood if msg.from.type == 'user' then local hash = 'user:'..msg.from.id..':msgs' local msgs = tonumber(redis:get(hash) or 0) local data = load_data(_config.moderation.data) local NUM_MSG_MAX = 5 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'])--Obtain group flood sensitivity end end local max_msg = NUM_MSG_MAX * 1 if msgs > max_msg then local user = msg.from.id -- Ignore mods,owner and admins if is_momod(msg) then return msg end local chat = msg.to.id local user = msg.from.id -- Return end if user was kicked before if kicktable[user] == true then return end kick_user(user, chat) local name = user_print_name(msg.from) --save it to log file savelog(msg.to.id, name.." ["..msg.from.id.."] spammed and kicked ! ") -- incr it on redis local gbanspam = 'gban:spam'..msg.from.id redis:incr(gbanspam) local gbanspam = 'gban:spam'..msg.from.id local gbanspamonredis = redis:get(gbanspam) --Check if user has spammed is group more than 4 times if gbanspamonredis then if tonumber(gbanspamonredis) == 4 and not is_owner(msg) then --Global ban that user banall_user(msg.from.id) local gbanspam = 'gban:spam'..msg.from.id --reset the counter redis:set(gbanspam, 0) local username = " " if msg.from.username ~= nil then username = msg.from.username end local name = user_print_name(msg.from) --Send this to that chat send_large_msg("chat#id"..msg.to.id, "User [ "..name.." ]"..msg.from.id.." Globally banned (spamming)") local log_group = 1 --set log group caht id --send it to log group send_large_msg("chat#id"..log_group, "User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Globally banned from ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (spamming)") end end kicktable[user] = true msg = nil end redis:setex(hash, TIME_CHECK, msgs+1) end return msg end local function cron() --clear that table on the top of the plugins kicktable = {} end return { patterns = {}, cron = cron, pre_process = pre_process } end
gpl-2.0
umbrellaTG/sphero
plugins/lock_emoji.lua
7
2768
local function run(msg) local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)]['settings']['antiemoji'] == 'no' then if not is_momod(msg) then chat_del_user('chat#id'..msg.to.id, 'user#id'..msg.from.id, ok_cb, true) local msgads = 'ForbiddenAdText' local receiver = msg.to.id send_large_msg('chat#id'..receiver, msg.."\n", ok_cb, false) end end end return {patterns = { 😞(.+)", "(.+)😞", "😐(.+)", "(.+)😐", "🙁(.+)", "(.+)🙁", "🌝(.+)", "(.+)🌝", "🤖(.+)", "(.+)🤖", "😲(.+)", "(.+)😲", "💋(.+)", "(.+)💋", "🙄(.+)", "(.+)🙄", "🤗(.+)", "(.+)🤗", "😱(.+)", "(.+)😱", "🤐(.+)", "(.+)🤐", "💩(.+)", "(.+)💩", "🌹(.+)", "(.+)🌹", "🖐(.+)", "(.+)🖐", "❤️(.+)", "(.+)❤️", "💗(.+)", "(.+)💗", "🤔(.+)", "(.+)🤔", "😖(.+)", "(.+)😖", "☹️(.+)", "(.+)☹️", "😔(.+)", "(.+)😔", "👾(.+)", "(.+)👾", "🚀(.+)", "(.+)🚀", "🌎🌍(.+)", "(.+)🌍", "(.+)🍦", "😸(.+)", "(.+)😺", "😯(.+)", "(.+)😯", "🤒(.+)", "(.+)🤒", "😷(.+)", "(.+)😷", "🙀(.+)", "(.+)🙀", "🎪(.+)", "(.+)🌚", "🌚(.+)", "(.+)😂", "😂(.+)", "(.+)😳", "😳(.+)", "(.+)😛", "😛(.+)", "(.+)😢", "😢(.+)", "(.+)😓", "😓(.+)", "(.+)😾", "😾(.+)", "(.+)👊🏻", "👊🏻(.+)", "(.+)✊🏻", "✊🏻(.+)", "(.+)👿", "👿(.+)", "(.+)👅", "👅(.+)", "(.+)🖕🏿", "🖕🏿(.+)", "(.+)😲", "😲(.+)", "(.+)👹", "👹(.+)", "(.+)😴", "😴(.+)", "(.+)☂", "☂(.+)", "(.+)🗣", "🗣(.+)", "(.+)⛄️", "⛄️(.+)", "(.+)😻", "😻(.+)", "😀(.+)", "(.+)😀", "😬(.+)", "(.+)😬", "😁(.+)", "(.+)😁", "😂(.+)", "(.+)😂", "😃(.+)", "(.+)😃", "😄(.+)", "(.+)😄", "😅(.+)", "(.+)😅", "😆(.+)", "(.+)😆", "😇(.+)", "(.+)😇", "😉(.+)", "(.+)😉", "😊(.+)", "(.+)😊", "🙂(.+)", "(.+)🙂", "🙃(.+)", "(.+)🙃", "☺️(.+)", "(.+)☺️", "😋(.+)", "(.+)😋", "😌(.+)", "(.+)😌", "😍(.+)", "(.+)😍", "😘(.+)", "(.+)😘", "😗(.+)", "(.+)😗", "😙(.+)", "(.+)😙", "😚(.+)", "(.+)😚", "😜(.+)", "(.+)😜", "😝(.+)", "(.+)😝", "🤑(.+)", "(.+)🤑", "🤓(.+)", "(.+)🤓", "😎(.+)", "(.+)😎", "🤗(.+)", "(.+)🤗", "😏(.+)", "(.+)😏", "😶(.+)", "(.+)😶", "😺(.+)", "(.+😺)", "😸(.+)", "(.+)😸", "😹(.+)", "(.+)😹", "😼(.+)", "(.+)😼", "😿(.+)", "(.+)😿", "🌝(.+)", "(.+)🌝", "🌚(.+)", "(.+)🌚", "🌶(.+)", "(.+🌶)", "🖐🏼(.+)", "(.+)🖐🏼", }, run = run }
gpl-2.0
kitala1/darkstar
scripts/globals/weaponskills/knights_of_round.lua
12
2071
----------------------------------- -- Knights Of Round -- Sword Weapon Skill -- Skill Level: N/A -- Caliburn/Excalibur: Additional Effect: Regen. -- Regen 10HP/Tick, duration varies with TP. -- Available only when equipped with the Relic Weapons Caliburn (Dynamis use only) or Excalibur. -- Also available without aftermath as a latent effect on Corbenic Sword. -- Aligned with the Flame Gorget & Light Gorget. -- Aligned with the Flame Belt & Light Belt. -- Element: None -- Modifiers: STR:40% ; MND:40% -- 100%TP 200%TP 300%TP -- 3.00 3.00 3.00 ----------------------------------- require("scripts/globals/status"); require("scripts/globals/settings"); require("scripts/globals/weaponskills"); ----------------------------------- function onUseWeaponSkill(player, target, wsID) local params = {}; params.numHits = 1; params.ftp100 = 3; params.ftp200 = 3; params.ftp300 = 3; params.str_wsc = 0.4; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.0; params.mnd_wsc = 0.4; 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.ftp100 = 5; params.ftp200 = 5; params.ftp300 = 5; end local damage, criticalHit, tpHits, extraHits = doPhysicalWeaponskill(player, target, params); if((player:getEquipID(SLOT_MAIN) == 18276) and (player:getMainJob() == JOB_RDM or JOB_PLD)) then if(damage > 0) then if(player:getTP() >= 100 and player:getTP() < 200) then player:addStatusEffect(EFFECT_AFTERMATH, 10, 0, 20, 0, 3); elseif(player:getTP() >= 200 and player:getTP() < 300) then player:addStatusEffect(EFFECT_AFTERMATH, 10, 0, 40, 0, 3); elseif(player:getTP() == 300) then player:addStatusEffect(EFFECT_AFTERMATH, 10, 0, 60, 0, 3); end end end damage = damage * WEAPON_SKILL_POWER return tpHits, extraHits, criticalHit, damage; end
gpl-3.0
Mechaniston/FibaroHC_mechHomeBcfg
old vers/T_light.lua
1
1791
--[[ ***** OPTIONS ***** ]]-- -- Devices ID's local doorID = 29; local lightID = 33; -- Light actuator type local lightIsRGBW = 1; local lightRGBWChannel = 2; -- RGBW <=> 1234 -- Debug mode local debug = true; --[[ ***** ROUTINES ***** ]]-- function split(s, pattern, maxsplit) local pattern = pattern or ' '; local maxsplit = maxsplit or -1; local s = s; local t = {}; local patsz = #pattern; while maxsplit ~= 0 do local curpos = 1; local found = string.find(s, pattern); if found ~= nil then table.insert(t, string.sub(s, curpos, found - 1)); curpos = found + patsz; s = string.sub(s, curpos); else table.insert(t, string.sub(s, curpos)); break; end maxsplit = maxsplit - 1; if maxsplit == 0 then table.insert(t, string.sub(s, curpos - patsz)); -- -1 ? end end return t; end function setRGBW(RGBWChannel, value) if RGBWChannel == 1 then fibaro:call(lightID, "SetR", value); elseif RGBWChannel == 2 then fibaro:call(lightID, "SetG", value); elseif RGBWChannel == 3 then fibaro:call(lightID, "SetB", value); elseif RGBWChannel == 4 then fibaro:call(lightID, "SetW", value); end end --[[ ***** GETTING ENVIROMENT ***** ]]-- if lightIsRGBW == 1 then local lightColors = split(fibaro:getValue(id_master, "color"), ','); -- 4th params: ', lightRGBWChannel' if debug then fibaro:debug("RGBW light colors: "..lightColors[1]..","..lightColors[2]..","..lightColors[3]..","..lightColors[4]); end if tonumber(lightColors[lightRGBWChannel]) > 0 then light = '1'; else light = '0'; end else local light = fibaro:getValue(lightID, 'value'); end if light == '1' then setRGBW(lightRGBWChannel, 0); else setRGBW(lightRGBWChannel, 255); end
mit
kitala1/darkstar
scripts/zones/Tavnazian_Safehold/npcs/Misseulieu.lua
29
1544
----------------------------------- -- Area: Tavnazian Safehold -- NPC: Misseulieu -- Standard Merchant NPC ----------------------------------- require("scripts/globals/shop"); package.loaded["scripts/zones/Tavnazian_Safehold/TextIDs"] = nil; require("scripts/zones/Tavnazian_Safehold/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:showText(npc,MISSEULIEU_SHOP_DIALOG); stock = {0x3121,2485, -- Brass Harness 0x32b9,1625, -- Holly Clogs 0x37ed,4042200, -- Barone Cosciales (Available after COP Chapter 4 only) 0x3bc9,25210200, -- Barone Gambieras (Available after COP Chapter 4 only) 0x3a00,7276200, -- Barone Manopolas (Available after COP Chapter 4 only) 0x3c1d,8000000, -- Vir Subligar (Available after COP Chapter 4 only) 0x3c1e,8000000} -- Femina Subligar (Available after COP Chapter 4 only) showShop(player, STATIC, stock); end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Dynamis-Windurst/mobs/Avatar_Icon.lua
16
5149
----------------------------------- -- Area: Dynamis Windurst -- NPC: Avatar Icon -- Map1 Position: http://images2.wikia.nocookie.net/__cb20090312004752/ffxi/images/8/84/Win1.jpg -- Map2 Position: http://images2.wikia.nocookie.net/__cb20090312004839/ffxi/images/6/61/Win2.jpg ----------------------------------- package.loaded["scripts/zones/Dynamis-Windurst/TextIDs"] = nil; ----------------------------------- require("scripts/globals/status"); require("scripts/globals/dynamis"); require("scripts/zones/Dynamis-Windurst/TextIDs"); ----------------------------------- -- onMobSpawn Action ----------------------------------- function onMobSpawn(mob) mob:setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) local X = mob:getXPos(); local Y = mob:getYPos(); local Z = mob:getZPos(); local spawnList = windyList; if(mob:getStatPoppedMobs() == false) then mob:setStatPoppedMobs(true); for nb = 1, table.getn(spawnList), 2 do if(mob:getID() == spawnList[nb]) then for nbi = 1, table.getn(spawnList[nb + 1]), 1 do if((nbi % 2) == 0) then X=X+2; Z=Z+2; else X=X-2; Z=Z-2; end local mobNBR = spawnList[nb + 1][nbi]; if(mobNBR <= 20) then if(mobNBR == 0) then mobNBR = math.random(1,15); end -- Spawn random Vanguard (TEMPORARY) local DynaMob = getDynaMob(target,mobNBR,1); --printf("Avatar Icon => mob %u \n",DynaMob); if(DynaMob ~= nil) then -- Spawn Mob SpawnMob(DynaMob):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(DynaMob):setPos(X,Y,Z); GetMobByID(DynaMob):setSpawn(X,Y,Z); -- Spawn Pet for BST, DRG, and SMN if(mobNBR == 9 or mobNBR == 15) then SpawnMob(DynaMob + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(DynaMob + 1):setPos(X,Y,Z); GetMobByID(DynaMob + 1):setSpawn(X,Y,Z); end end elseif(mobNBR > 20) then SpawnMob(mobNBR):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); local MJob = GetMobByID(mobNBR):getMainJob(); if(MJob == 9 or MJob == 14 or MJob == 15) then -- Spawn Pet for BST, DRG, and SMN SpawnMob(mobNBR + 1):setMobMod(MOBMOD_SUPERLINK, mob:getShortID()); GetMobByID(mobNBR + 1):setPos(X,Y,Z); GetMobByID(mobNBR + 1):setSpawn(X,Y,Z); end end end end end end end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob,killer) mobID = mob:getID(); -- Time Bonus (20min): 008 if(mobID == 17543494 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(20); mob:addInBattlefieldList(); -- Time Bonus (20min): 018 elseif(mobID == 17543504 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(20); mob:addInBattlefieldList(); -- Time Bonus (10min): 031 elseif(mobID == 17543514 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(10); mob:addInBattlefieldList(); -- Time Bonus (20min): 041 elseif(mobID == 17543518 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(20); mob:addInBattlefieldList(); -- Time Bonus (10min): 058 elseif(mobID == 17543534 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(10); mob:addInBattlefieldList(); -- Time Bonus (20min): 066 elseif(mobID == 17543542 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(20); mob:addInBattlefieldList(); -- Time Bonus (20min): 101 elseif(mobID == 17543577 and mob:isInBattlefieldList() == false) then killer:addTimeToDynamis(20); mob:addInBattlefieldList(); -- HP Bonus: 006 012 019 024 029 035 042 051 056 074 083 088 094 095 100 110 117 | 126 133 136 138 elseif(mobID == 17543492 or mobID == 17543498 or mobID == 17543505 or mobID == 17543508 or mobID == 17543512 or mobID == 17543517 or mobID == 17543393 or mobID == 17543527 or mobID == 17543532 or mobID == 17543550 or mobID == 17543559 or mobID == 17543564 or mobID == 17543570 or mobID == 17543571 or mobID == 17543576 or mobID == 17543586 or mobID == 17543593 or mobID == 17543601 or mobID == 17543608 or mobID == 17543611 or mobID == 17543613) then killer:restoreHP(2000); killer:messageBasic(024,(killer:getMaxHP()-killer:getHP())); -- MP Bonus: 008 017 025 030 032 040 045 057 060 072 077 080 086 096 111 118 | 127 131 137 139 elseif(mobID == 17543494 or mobID == 17543503 or mobID == 17543305 or mobID == 17543513 or mobID == 17543515 or mobID == 17543392 or mobID == 17543521 or mobID == 17543533 or mobID == 17543536 or mobID == 17543548 or mobID == 17543553 or mobID == 17543556 or mobID == 17543562 or mobID == 17543572 or mobID == 17543587 or mobID == 17543594 or mobID == 17543602 or mobID == 17543606 or mobID == 17543612 or mobID == 17543614) then killer:restoreMP(2000); killer:messageBasic(025,(killer:getMaxMP()-killer:getMP())); end end;
gpl-3.0
Roblox/Core-Scripts
CoreScriptsRoot/Modules/Settings/Pages/ShareGame/Reducers/Toasts.lua
1
1179
local CorePackages = game:GetService("CorePackages") local AppTempCommon = CorePackages.AppTempCommon local Modules = game:GetService("CoreGui").RobloxGui.Modules local ShareGame = Modules.Settings.Pages.ShareGame local Immutable = require(AppTempCommon.Common.Immutable) local ReceivedUserInviteStatus = require(ShareGame.Actions.ReceivedUserInviteStatus) local StoppedToastTimer = require(ShareGame.Actions.StoppedToastTimer) local Constants = require(ShareGame.Constants) local InviteStatus = Constants.InviteStatus return function(state, action) state = state or { moderated = {}, } if action.type == ReceivedUserInviteStatus.name then local inviteStatus = action.inviteStatus if inviteStatus == InviteStatus.Moderated then local moderationModel = { timeStamp = tick(), id = action.userId, subjectType = "user", } state = Immutable.JoinDictionaries(state, { moderated = Immutable.JoinDictionaries( state.moderated, Immutable.Append(state.moderated, moderationModel) ), }) end elseif action.type == StoppedToastTimer.name then state = Immutable.JoinDictionaries(state, { moderated = {}, }) end return state end
apache-2.0
apletnev/koreader
frontend/ui/widget/opdsbrowser.lua
2
25350
local ButtonDialog = require("ui/widget/buttondialog") local ButtonDialogTitle = require("ui/widget/buttondialogtitle") local Cache = require("cache") local CacheItem = require("cacheitem") local ConfirmBox = require("ui/widget/confirmbox") local InfoMessage = require("ui/widget/infomessage") local LoginDialog = require("ui/widget/logindialog") local Menu = require("ui/widget/menu") local MultiInputDialog = require("ui/widget/multiinputdialog") local NetworkMgr = require("ui/network/manager") local OPDSParser = require("ui/opdsparser") local Screen = require("device").screen local UIManager = require("ui/uimanager") local gettext = require("gettext") local http = require('socket.http') local https = require('ssl.https') local lfs = require("libs/libkoreader-lfs") local logger = require("logger") local ltn12 = require('ltn12') local mime = require('mime') local socket = require('socket') local url = require('socket.url') local util = require("util") local T = require("ffi/util").template local CatalogCacheItem = CacheItem:new{ size = 1024, -- fixed size for catalog item } -- cache catalog parsed from feed xml local CatalogCache = Cache:new{ max_memsize = 20*1024, -- keep only 20 cache items current_memsize = 0, cache = {}, cache_order = {}, } local OPDSBrowser = Menu:extend{ opds_servers = {}, calibre_name = gettext("Local calibre catalog"), catalog_type = "application/atom%+xml", search_type = "application/opensearchdescription%+xml", acquisition_rel = "^http://opds%-spec%.org/acquisition", image_rel = "http://opds-spec.org/image", thumbnail_rel = "http://opds-spec.org/image/thumbnail", formats = { ["application/epub+zip"] = "EPUB", ["application/fb2+zip"] = "FB2", ["application/pdf"] = "PDF", ["text/plain"] = "TXT", ["application/x-mobipocket-ebook"] = "MOBI", ["application/x-mobi8-ebook"] = "AZW3", }, width = Screen:getWidth(), height = Screen:getHeight(), no_title = false, parent = nil, } function OPDSBrowser:init() local servers = G_reader_settings:readSetting("opds_servers") if not servers then -- If there are no saved servers, add some defaults servers = { { title = "Project Gutenberg", url = "http://m.gutenberg.org/ebooks.opds/?format=opds", }, { title = "Feedbooks", url = "http://www.feedbooks.com/publicdomain/catalog.atom", }, { title = "ManyBooks", url = "http://manybooks.net/opds/index.php", }, { title = "Internet Archive", url = "http://bookserver.archive.org/catalog/", }, } G_reader_settings:saveSetting("opds_servers", servers) end self.item_table = self:genItemTableFromRoot() Menu.init(self) -- call parent's init() end function OPDSBrowser:addServerFromInput(fields) logger.dbg("input catalog", fields) local servers = G_reader_settings:readSetting("opds_servers") or {} table.insert(servers, { title = fields[1], url = (fields[2]:match("^%a+://") and fields[2] or "http://" .. fields[2]), }) G_reader_settings:saveSetting("opds_servers", servers) self:init() end function OPDSBrowser:editCalibreFromInput(fields) logger.dbg("input calibre server", fields) local calibre = G_reader_settings:readSetting("calibre_opds") or {} if fields[1] then calibre.host = fields[1] end if tonumber(fields[2]) then calibre.port = fields[2] end G_reader_settings:saveSetting("calibre_opds", calibre) self:init() end function OPDSBrowser:addNewCatalog() self.add_server_dialog = MultiInputDialog:new{ title = gettext("Add OPDS catalog"), fields = { { text = "", hint = gettext("Catalog name"), }, { text = "", hint = gettext("Catalog URL"), }, }, buttons = { { { text = gettext("Cancel"), callback = function() self.add_server_dialog:onClose() UIManager:close(self.add_server_dialog) end }, { text = gettext("Add"), callback = function() self.add_server_dialog:onClose() UIManager:close(self.add_server_dialog) self:addServerFromInput(MultiInputDialog:getFields()) end }, }, }, width = Screen:getWidth() * 0.95, height = Screen:getHeight() * 0.2, } self.add_server_dialog:onShowKeyboard() UIManager:show(self.add_server_dialog) end function OPDSBrowser:editCalibreServer() local calibre = G_reader_settings:readSetting("calibre_opds") or {} self.add_server_dialog = MultiInputDialog:new{ title = gettext("Edit local calibre host and port"), fields = { { -- TODO: get IP address of current device text = calibre.host or "192.168.1.1", hint = gettext("calibre host"), }, { text = calibre.port and tostring(calibre.port) or "8080", hint = gettext("calibre port"), }, }, buttons = { { { text = gettext("Cancel"), callback = function() self.add_server_dialog:onClose() UIManager:close(self.add_server_dialog) end }, { text = gettext("Apply"), callback = function() self.add_server_dialog:onClose() UIManager:close(self.add_server_dialog) self:editCalibreFromInput(MultiInputDialog:getFields()) end }, }, }, width = Screen:getWidth() * 0.95, height = Screen:getHeight() * 0.2, } self.add_server_dialog:onShowKeyboard() UIManager:show(self.add_server_dialog) end function OPDSBrowser:genItemTableFromRoot() local item_table = {} local added_servers = G_reader_settings:readSetting("opds_servers") or {} for _, server in ipairs(added_servers) do table.insert(item_table, { text = server.title, content = server.subtitle, url = server.url, deletable = true, editable = true, }) end local calibre_opds = G_reader_settings:readSetting("calibre_opds") or {} if not calibre_opds.host or not calibre_opds.port then table.insert(item_table, { text = self.calibre_name, callback = function() self:editCalibreServer() end, deletable = false, }) else table.insert(item_table, { text = self.calibre_name, url = string.format("http://%s:%d/opds", calibre_opds.host, calibre_opds.port), editable = true, deletable = false, }) end table.insert(item_table, { text = gettext("Add new OPDS catalog"), callback = function() self:addNewCatalog() end, }) return item_table end function OPDSBrowser:getBasicAuthentication(host) local authentications = G_reader_settings:readSetting("www-auth") or {} return authentications[host] end function OPDSBrowser:setBasicAuthentication(host, username, password) local authentications = G_reader_settings:readSetting("www-auth") or {} authentications[host] = { username = username, password = password, } G_reader_settings:saveSetting("www-auth", authentications) end function OPDSBrowser:getAuthorizationHeader(host) local auth = self:getBasicAuthentication(host) if auth then local authorization = auth.username .. ':' .. auth.password return { Authorization = "Basic " .. mime.b64(authorization), } end end function OPDSBrowser:fetchFeed(feed_url) local request, sink = {}, {} local parsed = url.parse(feed_url) request['url'] = feed_url request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) request['headers'] = self:getAuthorizationHeader(parsed.host) logger.dbg("request", request) http.TIMEOUT, https.TIMEOUT = 10, 10 local httpRequest = parsed.scheme == 'http' and http.request or https.request local code, headers, status = socket.skip(1, httpRequest(request)) -- raise error message when network is unavailable if headers == nil then error(code) end if code == 401 and status and status:find("Unauthorized") then self._coroutine = coroutine.running() or self._coroutine self:fetchWithLogin(parsed.host, function() return self:fetchFeed(feed_url) end) if coroutine.running() then local result = coroutine.yield() return result end else local xml = table.concat(sink) if xml ~= "" then return xml end end end function OPDSBrowser:fetchWithLogin(host, callback) self.login_dialog = LoginDialog:new{ title = gettext("Login to OPDS server"), username = "", buttons = { { { text = gettext("Cancel"), enabled = true, callback = function() self:closeDialog() end, }, { text = gettext("Login"), enabled = true, callback = function() local username, password = self:getCredential() self:setBasicAuthentication(host, username, password) self:closeDialog() UIManager:scheduleIn(0.5, function() local res = callback() if res then coroutine.resume(self._coroutine, res) end end) end, }, }, }, width = Screen:getWidth() * 0.8, height = Screen:getHeight() * 0.4, } self.login_dialog:onShowKeyboard() UIManager:show(self.login_dialog) end function OPDSBrowser:closeDialog() self.login_dialog:onClose() UIManager:close(self.login_dialog) end function OPDSBrowser:getCredential() return self.login_dialog:getCredential() end function OPDSBrowser:parseFeed(feed_url) local feed local hash = "opds|catalog|" .. feed_url local cache = CatalogCache:check(hash) if cache then feed = cache.feed else logger.dbg("cache", hash) feed = self:fetchFeed(feed_url) if feed then CatalogCache:insert(hash, CatalogCacheItem:new{ feed = feed }) end end if feed then return OPDSParser:parse(feed) end end function OPDSBrowser:getCatalog(feed_url) local ok, catalog = pcall(self.parseFeed, self, feed_url) if not ok and catalog and not NetworkMgr:isOnline() then NetworkMgr:promptWifiOn() return elseif not ok and catalog then logger.warn("cannot get catalog info from", feed_url, catalog) UIManager:show(InfoMessage:new{ text = T( gettext("Cannot get catalog info from %1"), (feed_url or "") ), }) return end if ok and catalog then logger.dbg("catalog", catalog) return catalog end end function OPDSBrowser:genItemTableFromURL(item_url) local catalog = self:getCatalog(item_url) return self:genItemTableFromCatalog(catalog, item_url) end function OPDSBrowser:genItemTableFromCatalog(catalog, item_url) local item_table = {} if not catalog then return item_table end local feed = catalog.feed or catalog local function build_href(href) return url.absolute(item_url, href) end local hrefs = {} if feed.link then for _, link in ipairs(feed.link) do if link.type ~= nil then if link.type:find(self.catalog_type) or link.type:find(self.search_type) then if link.rel and link.href then hrefs[link.rel] = build_href(link.href) end end end end end item_table.hrefs = hrefs if not feed.entry then return item_table end for _, entry in ipairs(feed.entry) do local item = {} item.acquisitions = {} if entry.link then for _, link in ipairs(entry.link) do if link.type:find(self.catalog_type) and (not link.rel or link.rel == "subsection" or link.rel == "http://opds-spec.org/sort/popular" or link.rel == "http://opds-spec.org/sort/new") then item.url = build_href(link.href) end if link.rel then if link.rel:match(self.acquisition_rel) then table.insert(item.acquisitions, { type = link.type, href = build_href(link.href), }) elseif link.rel == self.thumbnail_rel then item.thumbnail = build_href(link.href) elseif link.rel == self.image_rel then item.image = build_href(link.href) end end end end local title = "Unknown" if type(entry.title) == "string" then title = entry.title elseif type(entry.title) == "table" then if type(entry.title.type) == "string" and entry.title.div ~= "" then title = entry.title.div end end if title == "Unknown" then logger.warn("Cannot handle title", entry.title) end local author = "Unknown Author" if type(entry.author) == "table" and entry.author.name then author = entry.author.name end item.text = title item.title = title item.author = author item.id = entry.id item.content = entry.content item.updated = entry.updated table.insert(item_table, item) end return item_table end function OPDSBrowser:updateCatalog(item_table_url) local menu_table = self:genItemTableFromURL(item_table_url) if #menu_table > 0 then self:switchItemTable(nil, menu_table) if self.page_num <= 1 then self:onNext() end return true end end function OPDSBrowser:appendCatalog(item_table_url) local new_table = self:genItemTableFromURL(item_table_url) if #new_table == 0 then return false end for _, item in ipairs(new_table) do table.insert(self.item_table, item) end self.item_table.hrefs = new_table.hrefs self:switchItemTable(nil, self.item_table, -1) return true end function OPDSBrowser.getCurrentDownloadDir() local lastdir = G_reader_settings:readSetting("lastdir") return G_reader_settings:readSetting("download_dir") or lastdir end function OPDSBrowser:downloadFile(item, format, remote_url) -- download to user selected directory or last opened dir local download_dir = self.getCurrentDownloadDir() local file_system = util.getFilesystemType(download_dir) if file_system == "vfat" or file_system == "fuse.fsp" then item.author = util.replaceInvalidChars(item.author) item.title = util.replaceInvalidChars(item.title) else item.author = util.replaceSlashChar(item.author) item.title = util.replaceSlashChar(item.title) end local local_path = download_dir .. "/" .. item.author .. ' - ' .. item.title .. "." .. string.lower(format) local_path = util.fixUtf8(local_path, "_") local function download() UIManager:scheduleIn(1, function() logger.dbg("downloading file", local_path, "from", remote_url) local parsed = url.parse(remote_url) http.TIMEOUT, https.TIMEOUT = 20, 20 local httpRequest = parsed.scheme == 'http' and http.request or https.request local _, c, _ = httpRequest { url = remote_url, headers = self:getAuthorizationHeader(parsed.host), sink = ltn12.sink.file(io.open(local_path, "w")), } if c == 200 then logger.dbg("file downloaded to", local_path) if self.file_downloaded_callback then self.file_downloaded_callback(local_path) end else UIManager:show(InfoMessage:new { text = gettext("Could not save file to:\n") .. local_path, timeout = 3, }) end end) UIManager:show(InfoMessage:new{ text = gettext("Downloading may take several minutes…"), timeout = 1, }) end if lfs.attributes(local_path, "mode") == "file" then UIManager:show(ConfirmBox:new { text = T(gettext("The file %1 already exists. Do you want to overwrite it?"), local_path), ok_text = gettext("Overwrite"), ok_callback = function() download() end, }) else download() end end function OPDSBrowser:createNewDownloadDialog(path, buttons) self.download_dialog = ButtonDialogTitle:new{ title = T(gettext("Download directory:\n%1\n\nDownload file type:"), path), buttons = buttons } end function OPDSBrowser:showDownloads(item) local acquisitions = item.acquisitions local downloadsperline = 2 local lines = math.ceil(#acquisitions/downloadsperline) local buttons = {} for i = 1, lines do local line = {} for j = 1, downloadsperline do local button = {} local index = (i-1)*downloadsperline + j local acquisition = acquisitions[index] if acquisition then local format = self.formats[acquisition.type] if format then -- append DOWNWARDS BLACK ARROW ⬇ U+2B07 to format button.text = format .. "\xE2\xAC\x87" button.callback = function() self:downloadFile(item, format, acquisition.href) UIManager:close(self.download_dialog) end table.insert(line, button) end elseif #acquisitions > downloadsperline then table.insert(line, {text=""}) end end table.insert(buttons, line) end table.insert(buttons, {}) -- set download directory button table.insert(buttons, { { text = gettext("Choose download directory by long-pressing"), callback = function() require("ui/downloadmgr"):new{ title = gettext("Choose download directory"), onConfirm = function(path) logger.dbg("set download directory to", path) G_reader_settings:saveSetting("download_dir", path) UIManager:nextTick(function() UIManager:close(self.download_dialog) self:createNewDownloadDialog(path, buttons) UIManager:show(self.download_dialog) end) end, }:chooseDir() end, } }) self:createNewDownloadDialog(self.getCurrentDownloadDir(), buttons) UIManager:show(self.download_dialog) end function OPDSBrowser:onMenuSelect(item) -- add catalog if item.callback then item.callback() -- acquisition elseif item.acquisitions and #item.acquisitions > 0 then logger.dbg("downloads available", item) self:showDownloads(item) -- navigation else table.insert(self.paths, { url = item.url, }) if not self:updateCatalog(item.url) then table.remove(self.paths) end end return true end function OPDSBrowser:editServerFromInput(item, fields) logger.dbg("input catalog", fields) local servers = {} for _, server in ipairs(G_reader_settings:readSetting("opds_servers") or {}) do if server.title == item.text or server.url == item.url then server.title = fields[1] server.url = (fields[2]:match("^%a+://") and fields[2] or "http://" .. fields[2]) end table.insert(servers, server) end G_reader_settings:saveSetting("opds_servers", servers) self:init() end function OPDSBrowser:editOPDSServer(item) logger.dbg("edit", item) self.edit_server_dialog = MultiInputDialog:new{ title = gettext("Edit OPDS catalog"), fields = { { text = item.text or "", hint = gettext("Catalog Name"), }, { text = item.url or "", hint = gettext("Catalog URL"), }, }, buttons = { { { text = gettext("Cancel"), callback = function() self.edit_server_dialog:onClose() UIManager:close(self.edit_server_dialog) end }, { text = gettext("Apply"), callback = function() self.edit_server_dialog:onClose() UIManager:close(self.edit_server_dialog) self:editServerFromInput(item, MultiInputDialog:getFields()) end }, }, }, width = Screen:getWidth() * 0.95, height = Screen:getHeight() * 0.2, } self.edit_server_dialog:onShowKeyboard() UIManager:show(self.edit_server_dialog) end function OPDSBrowser:deleteOPDSServer(item) logger.dbg("delete", item) local servers = {} for _, server in ipairs(G_reader_settings:readSetting("opds_servers") or {}) do if server.title ~= item.text or server.url ~= item.url then table.insert(servers, server) end end G_reader_settings:saveSetting("opds_servers", servers) self:init() end function OPDSBrowser:onMenuHold(item) if item.deletable or item.editable then self.opds_server_dialog = ButtonDialog:new{ buttons = { { { text = gettext("Edit"), enabled = item.editable, callback = function() UIManager:close(self.opds_server_dialog) if item.text ~= self.calibre_name then self:editOPDSServer(item) else self:editCalibreServer(item) end end }, { text = gettext("Delete"), enabled = item.deletable, callback = function() UIManager:close(self.opds_server_dialog) self:deleteOPDSServer(item) end }, }, } } UIManager:show(self.opds_server_dialog) return true end end function OPDSBrowser:onReturn() logger.dbg("return to last page catalog") if #self.paths > 0 then table.remove(self.paths) local path = self.paths[#self.paths] if path then -- return to last path self:updateCatalog(path.url) else -- return to root path, we simply reinit opdsbrowser self:init() end end return true end function OPDSBrowser:onNext() logger.dbg("fetch next page catalog") -- self.page_num comes from menu.lua local page_num = self.page_num -- fetch more entries until we fill out one page or reach the end while page_num == self.page_num do local hrefs = self.item_table.hrefs if hrefs and hrefs.next then if not self:appendCatalog(hrefs.next) then break -- reach end of paging end else break end end return true end return OPDSBrowser
agpl-3.0
molovik/Starbound_RU
translations/others/quests/scripts/portraits.lua
9
1103
function setPortraits(titleFn) quest.setParameter("sail", { type = "noDetail", name = "К.Э.П", portrait = { { image = string.format("/ai/portraits/%squestportrait.png", player.species()) } } }) local config = config.getParameter("portraits") local portraitParameters = { QuestStarted = config.questStarted or config.default, QuestComplete = config.questComplete or config.default, QuestFailed = config.questFailed or config.default, Objective = config.objective } local parameters = quest.parameters() for portraitName, portrait in pairs(portraitParameters) do local drawables local title if type(portrait) == "string" then local paramValue = parameters[portrait] if paramValue then drawables = paramValue.portrait title = paramValue.name end else drawables = portrait.portrait title = portrait.title end if titleFn then title = titleFn(title) end quest.setPortrait(portraitName, drawables) quest.setPortraitTitle(portraitName, title) end end
apache-2.0
paulosalvatore/maruim_server
data/migrations/15.lua
58
2534
function onUpdateDatabase() print("> Updating database to version 16 (moving skills into players table)") db.query("ALTER TABLE `players` ADD `skill_fist` int(10) unsigned NOT NULL DEFAULT 10, ADD `skill_fist_tries` bigint(20) unsigned NOT NULL DEFAULT 0, ADD `skill_club` int(10) unsigned NOT NULL DEFAULT 10, ADD `skill_club_tries` bigint(20) unsigned NOT NULL DEFAULT 0, ADD `skill_sword` int(10) unsigned NOT NULL DEFAULT 10, ADD `skill_sword_tries` bigint(20) unsigned NOT NULL DEFAULT 0, ADD `skill_axe` int(10) unsigned NOT NULL DEFAULT 10, ADD `skill_axe_tries` bigint(20) unsigned NOT NULL DEFAULT 0, ADD `skill_dist` int(10) unsigned NOT NULL DEFAULT 10, ADD `skill_dist_tries` bigint(20) unsigned NOT NULL DEFAULT 0, ADD `skill_shielding` int(10) unsigned NOT NULL DEFAULT 10, ADD `skill_shielding_tries` bigint(20) unsigned NOT NULL DEFAULT 0, ADD `skill_fishing` int(10) unsigned NOT NULL DEFAULT 10, ADD `skill_fishing_tries` bigint(20) unsigned NOT NULL DEFAULT 0") db.query("UPDATE `players` SET `skill_fist` = (SELECT `value` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 0), `skill_fist_tries` = (SELECT `count` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 0), `skill_club` = (SELECT `value` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 1), `skill_club_tries` = (SELECT `count` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 1), `skill_sword` = (SELECT `value` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 2), `skill_sword_tries` = (SELECT `count` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 2), `skill_axe` = (SELECT `value` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 3), `skill_axe_tries` = (SELECT `count` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 3), `skill_dist` = (SELECT `value` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 4), `skill_dist_tries` = (SELECT `count` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 4), `skill_shielding` = (SELECT `value` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 5), `skill_shielding_tries` = (SELECT `count` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 5), `skill_fishing` = (SELECT `value` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 6), `skill_fishing_tries` = (SELECT `count` FROM `player_skills` WHERE `player_id` = `id` AND `skillid` = 6)") db.query("DROP TRIGGER `oncreate_players`") db.query("DROP TABLE `player_skills`") return true end
gpl-2.0
amirkingred/nod2
plugins/invite.lua
84
2540
--[[ Invite other user to the chat group. Use !invite ********* (where ********* is id_number) to invite a user by id_number. This is the most reliable method. Use !invite @username to invite a user by @username. Less reliable. Some users don't have @username. Use !invite Type print_name Here to invite a user by print_name. Unreliable. Avoid if possible. ]]-- do -- Think it's kind of useless. Just to suppress '*** lua: attempt to call a nil value' local function callback(extra, success, result) if success == 1 and extra ~= false then return extra.text else return send_large_msg(chat, "Can't invite user to this group.") end end local function resolve_username(extra, success, result) local chat = extra.chat if success == 1 then local user = 'user#id'..result.id chat_add_user(chat, user, callback, false) return extra.text else return send_large_msg(chat, "Can't invite user to this group.") end end local function action_by_reply(extra, success, result) if success == 1 then chat_add_user('chat#id'..result.to.id, 'user#id'..result.from.id, callback, false) else return send_large_msg('chat#id'..result.to.id, "Can't invite user to this group.") end end local function run(msg, matches) local user_id = matches[1] local chat = 'chat#id'..msg.to.id local text = "Add: "..user_id.." to "..chat if msg.to.type == 'chat' then if msg.reply_id and msg.text == "!invite" then msgr = get_message(msg.reply_id, action_by_reply, {msg=msg}) end if string.match(user_id, '^%d+$') then user = 'user#id'..user_id chat_add_user(chat, user, callback, {chat=chat, text=text}) elseif string.match(user_id, '^@.+$') then username = string.gsub(user_id, '@', '') msgr = res_user(username, resolve_username, {chat=chat, text=text}) else user = string.gsub(user_id, ' ', '_') chat_add_user(chat, user, callback, {chat=chat, text=text}) end else return 'This isnt a chat group!' end end return { description = 'Invite other user to the chat group.', usage = { -- Need space in front of this, so bot won't consider it as a command ' !invite [id|user_name|name]' }, patterns = { "^!invite$", "^!invite (.*)$", "^!invite (%d+)$" }, run = run, privileged = true } end --Copyright; @behroozyaghi --Persian Translate; @behroozyaghi --ch : @nod32team --کپی بدون ذکر منبع حرام است
gpl-2.0
kitala1/darkstar
scripts/zones/Cape_Teriggan/TextIDs.lua
3
1400
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory. FULL_INVENTORY_AFTER_TRADE = 6381; -- You cannot obtain the #. Try trading again after sorting your inventory. ITEM_OBTAINED = 6382; -- Obtained: <item>. GIL_OBTAINED = 6383; -- Obtained <number> gil. KEYITEM_OBTAINED = 6385; -- Obtained key item: <keyitem>. ITEMS_OBTAINED = 6391; -- You obtain BEASTMEN_BANNER = 7117; -- There is a beastmen's banner. FISHING_MESSAGE_OFFSET = 7537; -- You can't fish here. -- Other dialog NOTHING_OUT_OF_ORDINARY = 6396; -- There is nothing out of the ordinary here. -- Conquest CONQUEST = 7204; -- You've earned conquest points! -- ZM4 Dialog CANNOT_REMOVE_FRAG = 7647; -- It is an oddly shaped stone monument. A shining stone is embedded in it, but cannot be removed... ALREADY_OBTAINED_FRAG = 7648; -- You have already obtained this monument's . Try searching for another. FOUND_ALL_FRAGS = 7649; -- You have obtained all of the fragments. You must hurry to the ruins of the ancient shrine! ZILART_MONUMENT = 7651; -- It is an ancient Zilart monument. -- Other NOTHING_HAPPENS = 119; -- Nothing happens...?Possible Special Code: 00? -- conquest Base CONQUEST_BASE = 7036; -- Tallying conquest results...
gpl-3.0
fqrouter/luci
applications/luci-statistics/luasrc/model/cbi/luci_statistics/tcpconns.lua
80
1407
--[[ Luci configuration model for statistics - collectd tcpconns plugin configuration (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- m = Map("luci_statistics", translate("TCPConns Plugin Configuration"), translate( "The tcpconns plugin collects informations about open tcp " .. "connections on selected ports." )) -- collectd_tcpconns config section s = m:section( NamedSection, "collectd_tcpconns", "luci_statistics" ) -- collectd_tcpconns.enable enable = s:option( Flag, "enable", translate("Enable this plugin") ) enable.default = 0 -- collectd_tcpconns.listeningports (ListeningPorts) listeningports = s:option( Flag, "ListeningPorts", translate("Monitor all local listen ports") ) listeningports.default = 1 listeningports:depends( "enable", 1 ) -- collectd_tcpconns.localports (LocalPort) localports = s:option( Value, "LocalPorts", translate("Monitor local ports") ) localports.optional = true localports:depends( "enable", 1 ) -- collectd_tcpconns.remoteports (RemotePort) remoteports = s:option( Value, "RemotePorts", translate("Monitor remote ports") ) remoteports.optional = true remoteports:depends( "enable", 1 ) return m
apache-2.0
fqrouter/luci
modules/admin-mini/luasrc/model/cbi/mini/passwd.lua
83
1134
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- f = SimpleForm("password", translate("Admin Password"), translate("Change the password of the system administrator (User <code>root</code>)")) pw1 = f:field(Value, "pw1", translate("Password")) pw1.password = true pw1.rmempty = false pw2 = f:field(Value, "pw2", translate("Confirmation")) pw2.password = true pw2.rmempty = false function pw2.validate(self, value, section) return pw1:formvalue(section) == value and value end function f.handle(self, state, data) if state == FORM_VALID then local stat = luci.sys.user.setpasswd("root", data.pw1) == 0 if stat then f.message = translate("Password successfully changed") else f.errmessage = translate("Unknown Error") end data.pw1 = nil data.pw2 = nil end return true end return f
apache-2.0
fqrouter/luci
libs/lucid-http/luasrc/lucid/http/handler/file.lua
44
7477
--[[ HTTP server implementation for LuCI - file handler (c) 2008 Steven Barth <steven@midlink.org> (c) 2008 Freifunk Leipzig / Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ipairs, type, tonumber = ipairs, type, tonumber local os = require "os" local nixio = require "nixio", require "nixio.util" local fs = require "nixio.fs" local util = require "luci.util" local ltn12 = require "luci.ltn12" local srv = require "luci.lucid.http.server" local string = require "string" local prot = require "luci.http.protocol" local date = require "luci.http.protocol.date" local mime = require "luci.http.protocol.mime" local cond = require "luci.http.protocol.conditionals" --- File system handler -- @cstyle instance module "luci.lucid.http.handler.file" --- Create a simple file system handler. -- @class function -- @param name Name -- @param docroot Physical Document Root -- @param options Options -- @return Simple file system handler object Simple = util.class(srv.Handler) function Simple.__init__(self, name, docroot, options) srv.Handler.__init__(self, name) self.docroot = docroot self.realdocroot = fs.realpath(self.docroot) options = options or {} self.dirlist = not options.noindex self.error404 = options.error404 end --- Parse a range request. -- @param request Request object -- @param size File size -- @return offset, length, range header or boolean status function Simple.parse_range(self, request, size) if not request.headers.Range then return true end local from, to = request.headers.Range:match("bytes=([0-9]*)-([0-9]*)") if not (from or to) then return true end from, to = tonumber(from), tonumber(to) if not (from or to) then return true elseif not from then from, to = size - to, size - 1 elseif not to then to = size - 1 end -- Not satisfiable if from >= size then return false end -- Normalize if to >= size then to = size - 1 end local range = "bytes " .. from .. "-" .. to .. "/" .. size return from, (1 + to - from), range end --- Translate path and return file information. -- @param uri Request URI -- @return physical file path, file information function Simple.getfile(self, uri) if not self.realdocroot then self.realdocroot = fs.realpath(self.docroot) end local file = fs.realpath(self.docroot .. uri) if not file or file:sub(1, #self.realdocroot) ~= self.realdocroot then return uri end return file, fs.stat(file) end --- Handle a GET request. -- @param request Request object -- @return status code, header table, response source function Simple.handle_GET(self, request) local file, stat = self:getfile(prot.urldecode(request.env.PATH_INFO, true)) if stat then if stat.type == "reg" then -- Generate Entity Tag local etag = cond.mk_etag( stat ) -- Check conditionals local ok, code, hdrs ok, code, hdrs = cond.if_modified_since( request, stat ) if ok then ok, code, hdrs = cond.if_match( request, stat ) if ok then ok, code, hdrs = cond.if_unmodified_since( request, stat ) if ok then ok, code, hdrs = cond.if_none_match( request, stat ) if ok then local f, err = nixio.open(file) if f then local code = 200 local o, s, r = self:parse_range(request, stat.size) if not o then return self:failure(416, "Invalid Range") end local headers = { ["Cache-Control"] = "max-age=29030400", ["Last-Modified"] = date.to_http( stat.mtime ), ["Content-Type"] = mime.to_mime( file ), ["ETag"] = etag, ["Accept-Ranges"] = "bytes", } if o == true then s = stat.size else code = 206 headers["Content-Range"] = r f:seek(o) end headers["Content-Length"] = s -- Send Response return code, headers, srv.IOResource(f, s) else return self:failure( 403, err:gsub("^.+: ", "") ) end else return code, hdrs end else return code, hdrs end else return code, hdrs end else return code, hdrs end elseif stat.type == "dir" then local ruri = request.env.REQUEST_URI:gsub("/$", "") local duri = prot.urldecode( ruri, true ) local root = self.docroot -- check for index files local index_candidates = { "index.html", "index.htm", "default.html", "default.htm", "index.txt", "default.txt" } -- try to find an index file and redirect to it for i, candidate in ipairs( index_candidates ) do local istat = fs.stat( root .. "/" .. duri .. "/" .. candidate ) if istat ~= nil and istat.type == "reg" then return 302, { Location = ruri .. "/" .. candidate } end end local html = string.format( '<?xml version="1.0" encoding="utf-8"?>\n' .. '<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" ' .. '"http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">\n'.. '<html xmlns="http://www.w3.org/1999/xhtml" ' .. 'xml:lang="en" lang="en">\n' .. '<head>\n' .. '<title>Index of %s/</title>\n' .. '<style type="text/css">\n' .. 'body { color:#000000 } ' .. 'li { border-bottom:1px dotted #CCCCCC; padding:3px } ' .. 'small { font-size:60%%; color:#333333 } ' .. 'p { margin:0 }' .. '\n</style></head><body><h1>Index of %s/</h1><hr /><ul>'.. '<li><p><a href="%s/../">../</a> ' .. '<small>(parent directory)</small><br />' .. '<small></small></li>', duri, duri, ruri ) local entries = fs.dir( file ) if type(entries) == "function" then for i, e in util.vspairs(nixio.util.consume(entries)) do local estat = fs.stat( file .. "/" .. e ) if estat.type == "dir" then html = html .. string.format( '<li><p><a href="%s/%s/">%s/</a> ' .. '<small>(directory)</small><br />' .. '<small>Changed: %s</small></li>', ruri, prot.urlencode( e ), e, date.to_http( estat.mtime ) ) else html = html .. string.format( '<li><p><a href="%s/%s">%s</a> ' .. '<small>(%s)</small><br />' .. '<small>Size: %i Bytes | ' .. 'Changed: %s</small></li>', ruri, prot.urlencode( e ), e, mime.to_mime( e ), estat.size, date.to_http( estat.mtime ) ) end end html = html .. '</ul><hr /><address>LuCId-HTTPd' .. '</address></body></html>' return 200, { ["Date"] = date.to_http( os.time() ); ["Content-Type"] = "text/html; charset=utf-8"; }, ltn12.source.string(html) else return self:failure(403, "Permission denied") end else return self:failure(403, "Unable to transmit " .. stat.type .. " " .. file) end else if self.error404 then return 302, { Location = self.error404 } else return self:failure(404, "No such file: " .. file) end end end --- Handle a HEAD request. -- @param request Request object -- @return status code, header table, response source function Simple.handle_HEAD(self, ...) local stat, head = self:handle_GET(...) return stat, head end
apache-2.0
apletnev/koreader
plugins/goodreads.koplugin/goodreadsapi.lua
2
6689
local InputContainer = require("ui/widget/container/inputcontainer") local GoodreadsBook = require("goodreadsbook") local InfoMessage = require("ui/widget/infomessage") local UIManager = require("ui/uimanager") local url = require('socket.url') local socket = require('socket') local https = require('ssl.https') local ltn12 = require('ltn12') local _ = require("gettext") local GoodreadsApi = InputContainer:new { goodreads_key = "", goodreads_secret = "", total_result = 0, } function GoodreadsApi:init() end local function genSearchURL(text_search, userApi, search_type, npage) if (text_search) then text_search = string.gsub (text_search, "\n", "\r\n") text_search = string.gsub (text_search, "([^%w %-%_%.%~])", function (c) return string.format ("%%%02X", string.byte(c)) end) text_search = string.gsub (text_search, " ", "+") end return (string.format( "https://www.goodreads.com/search?q=%s&search[field]=%s&format=xml&key=%s&page=%s", text_search, search_type, userApi, npage )) end local function genIdUrl(id, userApi) return (string.format( "https://www.goodreads.com/book/show/%s?format=xml&key=%s", id, userApi )) end function GoodreadsApi:fetchXml(s_url) local request, sink = {}, {} local parsed = url.parse(s_url) request['url'] = s_url request['method'] = 'GET' request['sink'] = ltn12.sink.table(sink) https.TIMEOUT = 5 local httpsRequest = parsed.scheme == 'https' and https.request local headers = socket.skip(1, httpsRequest(request)) if headers == nil then return nil end local xml = table.concat(sink) if xml ~= "" then return xml end end function GoodreadsApi:showSearchTable(data) local books = {} if data == nil then UIManager:show(InfoMessage:new{text =_("Network problem.\nCheck connection.")}) return books end self.total_result = data:match("<total[-]results>(.*)</total[-]results>") for work in data:gmatch("<work>(.-)</work>") do local book = work:match("<best_book[^>]+>(.*)</best_book>") local id = book:match("<id[^>]+>([^<]+)</id>") local title = book:match("<title>([^<]+)</title>"):gsub(" %(.*#%d+%)$", "") local author = book:match("<name>([^<]+)</name>") table.insert(books, { author = author, title = title, id = id, }) end if #books == 0 then UIManager:show(InfoMessage:new{text =_("Search not found!")}) end return books end function GoodreadsApi:getTotalResults() return self.total_result end local function cleanHTMLTags(str_html) local cleaner = { { "&amp;", "&" }, { "&#151;", "-" }, { "&#146;", "'" }, { "&#160;", " " }, { "<!%[CDATA%[(.*)%]%]>", "%1" }, { "<br%s/>", "\n" }, { "%-%-", "%-" }, { "</p>", "\n" }, { "(%b<>)", "" }, { "\n\n*", "\n" }, { "\n*$", "" }, { "^\n*", "" }, } for i=1, #cleaner do local cleans = cleaner[i] str_html = string.gsub(str_html, cleans[1], cleans[2]) end return str_html end local function showIdTable(data) if data == nil then UIManager:show(InfoMessage:new{text =_("Network problem.\nCheck connection.")}) return {} end local data1 = data:match("<book>(.*)</reviews_widget>") local title_all = data1:match("<title>(.*)</title>"):gsub("<![[]CDATA[[]", ""):gsub("]]>$", "") local title = title_all:gsub(" %(.*#%d+%)$", "") local average_rating = data1:match("<average_rating>([^<]+)</average_rating>") local series = title_all:match("%(.*#%d+%)$") if series ~= nil then series = series:match("[(](.*)[)]") else series = _("N/A") end local num_pages = data1:match("<num_pages>(.*)</num_pages>"):gsub("<![[]CDATA[[]", ""):gsub("]]>$", "") if num_pages == nil or num_pages =="" then num_pages = _("N/A") end local id = data1:match("<id>([^<]+)</id>"):gsub("<![[]CDATA[[]", ""):gsub("]]>$", "") local author = data1:match("<name>([^<]+)</name>") local description = data1:match("<description>(.*)</description>") description = cleanHTMLTags(description) --change format from medium to large local image = data1:match("<image_url>([^<]+)</image_url>"):gsub("([0-9]+)m/", "%1l/") local day = data1:match("<original_publication_day[^>]+>([^<]+)</original_publication_day>") local month = data1:match("<original_publication_month[^>]+>([^<]+)</original_publication_month>") local year = data1:match("<original_publication_year[^>]+>([^<]+)</original_publication_year>") local release = {} if (year) then table.insert(release, year) end if (month) then table.insert(release, string.format("%02d", month)) end if (day) then table.insert(release, string.format("%02d", day)) end release = table.concat(release, "-") if release == "" then release = _("N/A") end local book_info = { title = title, author = author, series = series, rating = average_rating, pages = num_pages, release = release, description = description, image = image, id = id, } if id == nil then UIManager:show(InfoMessage:new{text = _("Search not found!")}) end return book_info end -- search_type = all - search all -- search_type = author - serch book by author -- search_type = title - search book by title function GoodreadsApi:showData(search_text, search_type, page, goodreads_key) local stats = {} local gen_url = genSearchURL(search_text, goodreads_key, search_type, page) local gen_xml = self:fetchXml(gen_url) local tbl = self:showSearchTable(gen_xml) if #tbl == 0 then return nil end for _, v in pairs(tbl) do local author = v.author local title = v.title local id = v.id table.insert(stats, { author, title, callback = function() local dates = self:showIdData(id, goodreads_key) if dates.id ~= nil then UIManager:show(GoodreadsBook:new{ dates = dates, }) end end, }) end return stats end function GoodreadsApi:showIdData(id, goodreads_key) local gen_url = genIdUrl(id, goodreads_key) local gen_xml = self:fetchXml(gen_url) local tbl = showIdTable(gen_xml) return tbl end return GoodreadsApi
agpl-3.0
fastmailops/prosody
util/openssl.lua
5
4389
local type, tostring, pairs, ipairs = type, tostring, pairs, ipairs; local t_insert, t_concat = table.insert, table.concat; local s_format = string.format; local oid_xmppaddr = "1.3.6.1.5.5.7.8.5"; -- [XMPP-CORE] local oid_dnssrv = "1.3.6.1.5.5.7.8.7"; -- [SRV-ID] local idna_to_ascii = require "util.encodings".idna.to_ascii; local _M = {}; local config = {}; _M.config = config; local ssl_config = {}; local ssl_config_mt = {__index=ssl_config}; function config.new() return setmetatable({ req = { distinguished_name = "distinguished_name", req_extensions = "v3_extensions", x509_extensions = "v3_extensions", prompt = "no", }, distinguished_name = { countryName = "GB", -- stateOrProvinceName = "", localityName = "The Internet", organizationName = "Your Organisation", organizationalUnitName = "XMPP Department", commonName = "example.com", emailAddress = "xmpp@example.com", }, v3_extensions = { basicConstraints = "CA:FALSE", keyUsage = "digitalSignature,keyEncipherment", extendedKeyUsage = "serverAuth,clientAuth", subjectAltName = "@subject_alternative_name", }, subject_alternative_name = { DNS = {}, otherName = {}, }, }, ssl_config_mt); end local DN_order = { "countryName"; "stateOrProvinceName"; "localityName"; "streetAddress"; "organizationName"; "organizationalUnitName"; "commonName"; "emailAddress"; } _M._DN_order = DN_order; function ssl_config:serialize() local s = ""; for k, t in pairs(self) do s = s .. ("[%s]\n"):format(k); if k == "subject_alternative_name" then for san, n in pairs(t) do for i = 1,#n do s = s .. s_format("%s.%d = %s\n", san, i -1, n[i]); end end elseif k == "distinguished_name" then for i=1,#DN_order do local k = DN_order[i] local v = t[k]; if v then s = s .. ("%s = %s\n"):format(k, v); end end else for k, v in pairs(t) do s = s .. ("%s = %s\n"):format(k, v); end end s = s .. "\n"; end return s; end local function utf8string(s) -- This is how we tell openssl not to encode UTF-8 strings as fake Latin1 return s_format("FORMAT:UTF8,UTF8:%s", s); end local function ia5string(s) return s_format("IA5STRING:%s", s); end _M.util = { utf8string = utf8string, ia5string = ia5string, }; function ssl_config:add_dNSName(host) t_insert(self.subject_alternative_name.DNS, idna_to_ascii(host)); end function ssl_config:add_sRVName(host, service) t_insert(self.subject_alternative_name.otherName, s_format("%s;%s", oid_dnssrv, ia5string("_" .. service .."." .. idna_to_ascii(host)))); end function ssl_config:add_xmppAddr(host) t_insert(self.subject_alternative_name.otherName, s_format("%s;%s", oid_xmppaddr, utf8string(host))); end function ssl_config:from_prosody(hosts, config, certhosts) -- TODO Decide if this should go elsewhere local found_matching_hosts = false; for i = 1,#certhosts do local certhost = certhosts[i]; for name in pairs(hosts) do if name == certhost or name:sub(-1-#certhost) == "."..certhost then found_matching_hosts = true; self:add_dNSName(name); --print(name .. "#component_module: " .. (config.get(name, "component_module") or "nil")); if config.get(name, "component_module") == nil then self:add_sRVName(name, "xmpp-client"); end --print(name .. "#anonymous_login: " .. tostring(config.get(name, "anonymous_login"))); if not (config.get(name, "anonymous_login") or config.get(name, "authentication") == "anonymous") then self:add_sRVName(name, "xmpp-server"); end self:add_xmppAddr(name); end end end if not found_matching_hosts then return nil, "no-matching-hosts"; end end do -- Lua to shell calls. local function shell_escape(s) return s:gsub("'",[['\'']]); end local function serialize(f,o) local r = {"openssl", f}; for k,v in pairs(o) do if type(k) == "string" then t_insert(r, ("-%s"):format(k)); if v ~= true then t_insert(r, ("'%s'"):format(shell_escape(tostring(v)))); end end end for _,v in ipairs(o) do t_insert(r, ("'%s'"):format(shell_escape(tostring(v)))); end return t_concat(r, " "); end local os_execute = os.execute; setmetatable(_M, { __index=function(_,f) return function(opts) return 0 == os_execute(serialize(f, type(opts) == "table" and opts or {})); end; end; }); end return _M;
mit
kitala1/darkstar
scripts/zones/Bastok_Markets/npcs/Aquillina.lua
36
2383
----------------------------------- -- Area: Bastok Markets -- NPC: Aquillina -- Starts & Finishes Repeatable Quest: A Flash In The Pan -- Note: Reapeatable every 15 minutes. ----------------------------------- package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/zones/Bastok_Markets/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) FlashInThePan = player:getQuestStatus(BASTOK,A_FLASH_IN_THE_PAN); if (FlashInThePan >= QUEST_ACCEPTED) then PreviousTime = player:getVar("FlashInThePan"); CurrentTime = os.time(); if (CurrentTime >= PreviousTime) then count = trade:getItemCount(); FlintStone = trade:hasItemQty(768,4); if (FlintStone == true and count == 4) then player:startEvent(0x00db); end else player:startEvent(0x00da); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) FlashInThePan = player:getQuestStatus(BASTOK,A_FLASH_IN_THE_PAN); if (FlashInThePan == QUEST_AVAILABLE) then player:startEvent(0x00d9); else player:startEvent(0x0074); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID2: %u",csid); --printf("RESULT2: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 0x00d9) then player:addQuest(BASTOK, A_FLASH_IN_THE_PAN); elseif (csid == 0x00db) then FlashInThePan = player:getQuestStatus(BASTOK,A_FLASH_IN_THE_PAN); CompleteTime = os.time(); if (FlashInThePan == QUEST_ACCEPTED) then player:completeQuest(BASTOK, A_FLASH_IN_THE_PAN); player:addFame(BASTOK,BAS_FAME*75); else player:addFame(BASTOK,BAS_FAME*8); end player:tradeComplete(); player:setVar("FlashInThePan",CompleteTime + 900); player:addGil(GIL_RATE*100); player:messageSpecial(GIL_OBTAINED,GIL_RATE*100); end end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/istakoz.lua
18
1337
----------------------------------------- -- ID: 5453 -- Item: Istakoz -- Food Effect: 5Min, Mithra only ----------------------------------------- -- Dexterity -5 -- Vitality 3 -- Defense +15.4% ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:getRace() ~= 7) then result = 247; end if(target:getMod(MOD_EAT_RAW_FISH) == 1) then result = 0; end if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5453); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_DEX, -5); target:addMod(MOD_VIT, 3); target:addMod(MOD_DEFP, 16); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_DEX, -5); target:delMod(MOD_VIT, 3); target:delMod(MOD_DEFP, 16); end;
gpl-3.0
apletnev/koreader
spec/unit/kosync_spec.lua
4
6674
local service = [[ { "base_url" : "https://sync.koreader.rocks:443/", "name" : "api", "methods" : { "register" : { "path" : "/users/create", "method" : "POST", "required_params" : [ "username", "password", ], "payload" : [ "username", "password", ], "expected_status" : [201, 402] }, "authorize" : { "path" : "/users/auth", "method" : "GET", "expected_status" : [200, 401] }, "update_progress" : { "path" : "/syncs/progress", "method" : "PUT", "required_params" : [ "document", "progress", "percentage", "device", ], "payload" : [ "document", "progress", "percentage", "device", ], "expected_status" : [200, 202, 401] }, "get_progress" : { "path" : "/syncs/progress/:document", "method" : "GET", "required_params" : [ "document", ], "expected_status" : [200, 401] }, } } ]] describe("KOSync modules #notest #nocov", function() local logger, md5, client local username, password, doc, percentage, progress, device setup(function() require("commonrequire") logger = require("logger") md5 = require("ffi/MD5") local Spore = require("Spore") client = Spore.new_from_string(service) package.loaded['Spore.Middleware.GinClient'] = {} require('Spore.Middleware.GinClient').call = function(self, req) req.headers['accept'] = "application/vnd.koreader.v1+json" end package.loaded['Spore.Middleware.KOSyncAuth'] = {} require('Spore.Middleware.KOSyncAuth').call = function(args, req) req.headers['x-auth-user'] = args.username req.headers['x-auth-key'] = args.userkey end -- password should be hashed before submitting to server username, password = "koreader", md5.sum("koreader") -- fake progress data doc, percentage, progress, device = "41cce710f34e5ec21315e19c99821415", -- fast digest of the document 0.356, -- percentage of the progress "69", -- page number or xpointer "my kpw" -- device name end) it("should create new user", function() client:reset_middlewares() client:enable('Format.JSON') client:enable("GinClient") local ok, res = pcall(function() return client:register({ username = username, password = password, }) end) if ok then if res.status == 200 then logger.dbg("register successful to ", res.body.username) elseif res.status == 402 then logger.dbg("register unsuccessful: ", res.body.message) end else logger.dbg("Please retry later", res) end end) it("should authorize user", function() client:reset_middlewares() client:enable('Format.JSON') client:enable("GinClient") client:enable("KOSyncAuth", { username = username, userkey = password, }) local ok, res = pcall(function() return client:authorize() end) if ok then if res.status == 200 then assert.are.same("OK", res.body.authorized) else logger.dbg(res.body) end else logger.dbg("Please retry later", res) end end) it("should update progress", function() client:reset_middlewares() client:enable('Format.JSON') client:enable("GinClient") client:enable("KOSyncAuth", { username = username, userkey = password, }) local ok, res = pcall(function() return client:update_progress({ document = doc, progress = progress, percentage = percentage, device = device, }) end) if ok then if res.status == 200 then local result = res.body assert.are.same(progress, result.progress) assert.are.same(percentage, result.percentage) assert.are.same(device, result.device) else logger.dbg(res.body.message) end else logger.dbg("Please retry later", res) end end) it("should get progress", function() client:reset_middlewares() client:enable('Format.JSON') client:enable("GinClient") client:enable("KOSyncAuth", { username = username, userkey = password, }) local ok, res = pcall(function() return client:get_progress({ document = doc, }) end) if ok then if res.status == 200 then local result = res.body assert.are.same(progress, result.progress) assert.are.same(percentage, result.percentage) assert.are.same(device, result.device) else logger.dbg(res.body.message) end else logger.dbg("Please retry later", res) end end) -- The response of mockKOSyncClient local res = { result = false, body = {} } -- TODO: Test kosync module local function mockKOSyncClient() --luacheck: ignore package.loaded["KOSyncClient"] = nil local c = require("KOSyncClient") c.new = function(o) o = o or {} setmetatable(o, self) --luacheck: ignore self.__index = self --luacheck: ignore return o end c.init = function() end c.register = function(name, passwd) return res.result, res.body end c.authorize = function(name, passwd) return res.result, res.body end c.update_progress = function(name, passwd, doc, prog, percent, device, device_id, cb) --luacheck: ignore cb(res.result, res.body) end c.get_progress = function(name, passwd, doc, cb) --luacheck: ignore cb(res.result, res.body) end end end)
agpl-3.0
d-o/LUA-LIB
tests/network/stream.lua
2
2581
------------------------------------------------------------------------------- -- Streaming network test. -- @author Pauli -- @copyright 2014 Rinstrum Pty Ltd ------------------------------------------------------------------------------- require "tests.assertions" describe("Streaming #stream", function () local net = require "tests.network" local timers = require 'rinSystem.rinTimers' local app, upper, lower, death setup(function() app, upper, lower = net.openDevices() end) teardown(function() net.closeDevices(app) end) before_each(function() death = timers.addTimer(0, 25, function() assert.equal("timed out", nil) end) end) after_each(function() timers.removeTimer(death) death = nil end) -- Need to verify streaming works. -- Need to verify streaming multiple registers. -- Need to verify different stream timings. describe("timings", function() local s, count = nil, 0 after_each(function() upper.removeStream(s) s = nil upper.setStreamFreq('onchange') end) local function increment(...) count = count + 1 end it("auto10", function() upper.setStreamFreq('auto10') s = upper.addStream('gross', increment, 'always') timers.addTimer(0, .1, function() count = 0 end) timers.addTimer(0, 1.1, function() assert.between(count, 8, 12) end) app.delay(1.2) end) it("auto3", function() upper.setStreamFreq('auto3') s = upper.addStream('gross', increment, 'always') timers.addTimer(0, .1, function() count = 0 end) timers.addTimer(0, 2.1, function() assert.between(count, 4, 8) end) app.delay(2.2) end) it("auto1", function() upper.setStreamFreq('auto1') s = upper.addStream('gross', increment, 'always') timers.addTimer(0, .1, function() count = 0 end) timers.addTimer(0, 3.1, function() assert.between(count, 2, 4) end) app.delay(3.2) end) it("auto25", function() upper.setStreamFreq('auto') s = upper.addStream('gross', increment, 'always') timers.addTimer(0, .1, function() count = 0 end) timers.addTimer(0, 1.1, function() assert.between(count, 19, 26) end) app.delay(1.2) end) end) end)
gpl-3.0
nicodinh/cuberite
MCServer/Plugins/APIDump/Hooks/OnDisconnect.lua
36
1597
return { HOOK_DISCONNECT = { CalledWhen = [[ A client has disconnected, either by explicitly sending the disconnect packet (in older protocols) or their connection was terminated ]], DefaultFnName = "OnDisconnect", -- also used as pagename Desc = [[ This hook is called when a client has disconnected from the server, for whatever reason. It is also called when the client sends the Disconnect packet (only in pre-1.7 protocols). This hook is not called for server ping connections.</p> <p> Note that the hook is called even for connections to players who failed to auth. In such a case there's no {{cPlayer}} object associated with the client.</p> <p> See also the {{OnHandshake|HOOK_HANDSHAKE}} hook which is called when the client connects (and presents a handshake message, so that they are not just status-pinging). If you need to store a per-player object, use the {{OnPlayerJoined|HOOK_PLAYER_JOINED}} and {{OnPlayerDestroyed|HOOK_PLAYER_DESTROYED}} hooks instead, those are guaranteed to have the {{cPlayer}} object associated. ]], Params = { { Name = "Client", Type = "{{cClientHandle}}", Notes = "The client who has disconnected" }, { Name = "Reason", Type = "string", Notes = "The reason that the client has sent in the disconnect packet" }, }, Returns = [[ If the function returns false or no value, Cuberite calls other plugins' callbacks for this event. If the function returns true, no other plugins are called for this event. In either case, the client is disconnected. ]], }, -- HOOK_DISCONNECT }
apache-2.0
paulosalvatore/maruim_server
data/migrations/13.lua
58
2963
function onUpdateDatabase() print("> Updating database to version 14 (account_bans, ip_bans and player_bans)") db.query("CREATE TABLE IF NOT EXISTS `account_bans` (`account_id` int(11) NOT NULL, `reason` varchar(255) NOT NULL, `banned_at` bigint(20) NOT NULL, `expires_at` bigint(20) NOT NULL, `banned_by` int(11) NOT NULL, PRIMARY KEY (`account_id`), KEY `banned_by` (`banned_by`), FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`banned_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB") db.query("CREATE TABLE IF NOT EXISTS `account_ban_history` (`account_id` int(11) NOT NULL, `reason` varchar(255) NOT NULL, `banned_at` bigint(20) NOT NULL, `expired_at` bigint(20) NOT NULL, `banned_by` int(11) NOT NULL, PRIMARY KEY (`account_id`), KEY `banned_by` (`banned_by`), FOREIGN KEY (`account_id`) REFERENCES `accounts` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`banned_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB") db.query("CREATE TABLE IF NOT EXISTS `ip_bans` (`ip` int(10) unsigned NOT NULL, `reason` varchar(255) NOT NULL, `banned_at` bigint(20) NOT NULL, `expires_at` bigint(20) NOT NULL, `banned_by` int(11) NOT NULL, PRIMARY KEY (`ip`), KEY `banned_by` (`banned_by`), FOREIGN KEY (`banned_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB") db.query("CREATE TABLE IF NOT EXISTS `player_namelocks` (`player_id` int(11) NOT NULL, `reason` varchar(255) NOT NULL, `namelocked_at` bigint(20) NOT NULL, `namelocked_by` int(11) NOT NULL, PRIMARY KEY (`player_id`), KEY `namelocked_by` (`namelocked_by`), FOREIGN KEY (`player_id`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE, FOREIGN KEY (`namelocked_by`) REFERENCES `players` (`id`) ON DELETE CASCADE ON UPDATE CASCADE) ENGINE=InnoDB") local resultId = db.storeQuery("SELECT `player`, `time` FROM `bans` WHERE `type` = 2") if resultId ~= false then local stmt = "INSERT INTO `player_namelocks` (`player_id`, `namelocked_at`, `namelocked_by`) VALUES " repeat stmt = stmt .. "(" .. result.getDataInt(resultId, "player") .. "," .. result.getDataInt(resultId, "time") .. "," .. result.getDataInt(resultId, "player") .. ")," until not result.next(resultId) result.free(resultId) local stmtLen = string.len(stmt) if stmtLen > 86 then stmt = string.sub(stmt, 1, stmtLen - 1) db.query(stmt) end end db.query("DROP TRIGGER `ondelete_accounts`") db.query("DROP TRIGGER `ondelete_players`") db.query("ALTER TABLE `accounts` DROP `warnings`") db.query("DROP TABLE `bans`") print("Run this query in your database to create the ondelete_players trigger:") print("DELIMITER //") print("CREATE TRIGGER `ondelete_players` BEFORE DELETE ON `players`") print(" FOR EACH ROW BEGIN") print(" UPDATE `houses` SET `owner` = 0 WHERE `owner` = OLD.`id`;") print("END //") return true end
gpl-2.0
kitala1/darkstar
scripts/globals/abilities/fighters_roll.lua
11
2170
----------------------------------- -- Ability: Fighter's Roll -- Improves "Double Attack" rate for party members within area of effect -- Optimal Job: Warrior -- Lucky Number: 5 -- Unlucky Number: 9 -- Level: 49 -- -- Die Roll |No WAR |With WAR -- -------- -------- ----------- -- 1 |2% |8% -- 2 |2% |8% -- 3 |3% |9% -- 4 |4% |10% -- 5 |12% |18% -- 6 |5% |11% -- 7 |6% |12% -- 8 |7% |13% -- 9 |1% |7% -- 10 |9% |15% -- 11 |18% |24% -- 12+ |-6% |-6% ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); ----------------------------------- -- onAbilityCheck ----------------------------------- function onAbilityCheck(player,target,ability) local effectID = getCorsairRollEffect(ability:getID()); if (player:hasStatusEffect(effectID) or player:hasBustEffect(effectID)) then return MSGBASIC_ROLL_ALREADY_ACTIVE,0; else return 0,0; end end; ----------------------------------- -- onUseAbilityRoll ----------------------------------- function onUseAbilityRoll(caster,target,ability,total) local duration = 300 + caster:getMerit(MERIT_WINNING_STREAK) local effectpowers = {2, 2, 3, 4, 12, 5, 6, 7, 1, 9, 18, 6} local effectpower = effectpowers[total] if (total < 12 and caster:hasPartyJob(JOB_WAR) ) then effectpower = effectpower + 6; end if (caster:getMainJob() == JOB_COR and caster:getMainLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getMainLvl() / target:getMainLvl()); elseif (caster:getSubJob() == JOB_COR and caster:getSubLvl() < target:getMainLvl()) then effectpower = effectpower * (caster:getSubLvl() / target:getMainLvl()); end if (target:addCorsairRoll(caster:getMainJob(), caster:getMerit(MERIT_BUST_DURATION), EFFECT_FIGHTERS_ROLL, effectpower, 0, duration, caster:getID(), total, MOD_DOUBLE_ATTACK) == false) then ability:setMsg(423); end end;
gpl-3.0
wilcox-liam/ageofwar
game/scripts/vscripts/heroes/hero_firelord/ignite.lua
1
1283
function Ignite( keys ) local caster = keys.caster local target = keys.target local ability = keys.ability local caster_int = caster:GetIntellect() local int_multiplier = ability:GetLevelSpecialValueFor("power", (ability:GetLevel() -1)) local duration = ability:GetLevelSpecialValueFor("duration", (ability:GetLevel() -1)) local damage_table = {} damage_table.attacker = caster damage_table.damage_type = ability:GetAbilityDamageType() damage_table.ability = ability damage_table.victim = target damage_table.damage = caster_int * int_multiplier / duration ApplyDamage(damage_table) end function IgniteBurntCheck( keys ) local target = keys.target local caster = keys.caster local player = caster:GetPlayerID() if target:HasModifier("modifier_ignite_burnt_debuff") then caster:Stop() GameRules:SendCustomMessage("Cannot Ignite a burnt target.", 0, 0) end end function IgniteSpread( keys ) local caster = keys.caster local target = keys.target local ability = keys.ability if not target:HasModifier("modifier_ignite_burnt_debuff") then ability:ApplyDataDrivenModifier(caster, target, "modifier_ignite_debuff", {duration = 5}) ability:ApplyDataDrivenModifier(caster, target, "modifier_ignite_burnt_debuff", {duration = 10}) end end
gpl-2.0
Roblox/Core-Scripts
CoreScriptsRoot/Modules/PlayerDropDown.lua
1
24054
--[[ // FileName: PlayerDropDown.lua // Written by: TheGamer101 // Description: Code for the player drop down in the PlayerList and Chat ]] local moduleApiTable = {} local CoreGui = game:GetService('CoreGui') local HttpService = game:GetService('HttpService') local HttpRbxApiService = game:GetService('HttpRbxApiService') local PlayersService = game:GetService('Players') local StarterGui = game:GetService("StarterGui") local AnalyticsService = game:GetService("AnalyticsService") local RobloxReplicatedStorage = game:GetService('RobloxReplicatedStorage') local fixPlayerlistFollowingSuccess, fixPlayerlistFollowingFlagValue = pcall(function() return settings():GetFFlag("FixPlayerlistFollowing") end) local fixPlayerlistFollowingEnabled = fixPlayerlistFollowingSuccess and fixPlayerlistFollowingFlagValue local LocalPlayer = PlayersService.LocalPlayer while not LocalPlayer do PlayersService.PlayerAdded:wait() LocalPlayer = PlayersService.LocalPlayer end local success, result = pcall(function() return settings():GetFFlag('UseNotificationsLocalization') end) local FFlagUseNotificationsLocalization = success and result local FFlagHandlePlayerBlockListsInternalPermissive = settings():GetFFlag('HandlePlayerBlockListsInternalPermissive') local FFlagCoreScriptsUseLocalizationModule = settings():GetFFlag('CoreScriptsUseLocalizationModule') local recentApiRequests = -- stores requests for target players by userId { Following = {}; } local POPUP_ENTRY_SIZE_Y = 24 local ENTRY_PAD = 2 local BG_TRANSPARENCY = 0.5 local BG_COLOR = Color3.new(31/255, 31/255, 31/255) local TEXT_STROKE_TRANSPARENCY = 0.75 local TEXT_COLOR = Color3.new(1, 1, 243/255) local TEXT_STROKE_COLOR = Color3.new(34/255, 34/255, 34/255) local MAX_FRIEND_COUNT = 200 local FRIEND_IMAGE = 'https://www.roblox.com/thumbs/avatar.ashx?userId=' local GET_BLOCKED_USERIDS_TIMEOUT = 5 local RobloxGui = CoreGui:WaitForChild('RobloxGui') local reportAbuseMenu = require(RobloxGui.Modules.Settings.Pages.ReportAbuseMenu) local RobloxTranslator if FFlagCoreScriptsUseLocalizationModule then RobloxTranslator = require(RobloxGui.Modules.RobloxTranslator) end local function LocalizedGetString(key, rtv) pcall(function() if FFlagCoreScriptsUseLocalizationModule then rtv = RobloxTranslator:FormatByKey(key) else local LocalizationService = game:GetService("LocalizationService") local CorescriptLocalization = LocalizationService:GetCorescriptLocalizations()[1] rtv = CorescriptLocalization:GetString(LocalizationService.RobloxLocaleId, key) end end) return rtv end local BindableEvent_SendNotificationInfo = nil spawn(function() BindableEvent_SendNotificationInfo = RobloxGui:WaitForChild("SendNotificationInfo") end) local RemoteEvent_NewFollower = nil local RemoteEvent_UpdatePlayerBlockList = nil spawn(function() RemoteEvent_NewFollower = RobloxReplicatedStorage:WaitForChild('NewFollower', 86400) or RobloxReplicatedStorage:WaitForChild('NewFollower') if FFlagHandlePlayerBlockListsInternalPermissive then RemoteEvent_UpdatePlayerBlockList = RobloxReplicatedStorage:WaitForChild('UpdatePlayerBlockList') end end) local function createSignal() local sig = {} local mSignaler = Instance.new('BindableEvent') local mArgData = nil local mArgDataCount = nil function sig:fire(...) mArgData = {...} mArgDataCount = select('#', ...) mSignaler:Fire() end function sig:connect(f) if not f then error("connect(nil)", 2) end return mSignaler.Event:connect(function() f(unpack(mArgData, 1, mArgDataCount)) end) end function sig:wait() mSignaler.Event:wait() assert(mArgData, "Missing arg data, likely due to :TweenSize/Position corrupting threadrefs.") return unpack(mArgData, 1, mArgDataCount) end return sig end local BlockStatusChanged = createSignal() local MuteStatusChanged = createSignal() local function sendNotification(title, text, image, duration, callback) if BindableEvent_SendNotificationInfo then BindableEvent_SendNotificationInfo:Fire { Title = title, Text = text, Image = image, Duration = duration, Callback = callback } end end local function getFriendStatus(selectedPlayer) if selectedPlayer == LocalPlayer then return Enum.FriendStatus.NotFriend else local success, result = pcall(function() -- NOTE: Core script only return LocalPlayer:GetFriendStatus(selectedPlayer) end) if success then return result else return Enum.FriendStatus.NotFriend end end end -- if userId = nil, then it will get count for local player local function getFriendCountAsync(userId) local friendCount = nil local wasSuccess, result = pcall(function() local str = 'user/get-friendship-count' if userId then str = str..'?userId='..tostring(userId) end return HttpRbxApiService:GetAsync(str, Enum.ThrottlingPriority.Default, Enum.HttpRequestType.Players) end) if not wasSuccess then print("getFriendCountAsync() failed because", result) return nil end result = HttpService:JSONDecode(result) if result["success"] and result["count"] then friendCount = result["count"] end return friendCount end -- checks if we can send a friend request. Right now the only way we -- can't is if one of the players is at the max friend limit local function canSendFriendRequestAsync(otherPlayer) local theirFriendCount = getFriendCountAsync(otherPlayer.UserId) local myFriendCount = getFriendCountAsync() -- assume max friends if web call fails if not myFriendCount or not theirFriendCount then return false end if myFriendCount < MAX_FRIEND_COUNT and theirFriendCount < MAX_FRIEND_COUNT then return true elseif myFriendCount >= MAX_FRIEND_COUNT then sendNotification("Cannot send friend request", "You are at the max friends limit.", "", 5, function() end) return false elseif theirFriendCount >= MAX_FRIEND_COUNT then sendNotification("Cannot send friend request", otherPlayer.Name.." is at the max friends limit.", "", 5, function() end) return false end end -- Returns whether followerUserId is following userId local function isFollowing(userId, followerUserId) local apiPath = "user/following-exists?userId=" local params = userId.."&followerUserId="..followerUserId local success, result = pcall(function() return HttpRbxApiService:GetAsync(apiPath..params, Enum.ThrottlingPriority.Default, Enum.HttpRequestType.Players) end) if not success then print("isFollowing() failed because", result) return false else if fixPlayerlistFollowingEnabled then -- check to make sure the result isn't cached by checking the most recent response if followerUserId == LocalPlayer.UserId then if recentApiRequests["Following"][tostring(userId)] ~= nil then return recentApiRequests["Following"][tostring(userId)] end end end end -- can now parse web response result = HttpService:JSONDecode(result) return result["success"] and result["isFollowing"] end local BlockedList = {} local MutedList = {} local function GetBlockedPlayersAsync() local userId = LocalPlayer.UserId local apiPath = "userblock/getblockedusers" .. "?" .. "userId=" .. tostring(userId) .. "&" .. "page=" .. "1" if userId > 0 then local blockList = nil local success, msg = pcall(function() local request = HttpRbxApiService:GetAsync(apiPath, Enum.ThrottlingPriority.Default, Enum.HttpRequestType.Players) blockList = request and game:GetService('HttpService'):JSONDecode(request) end) if blockList and blockList['success'] == true and blockList['userList'] then local returnList = {} for i, v in pairs(blockList['userList']) do returnList[v] = true end return returnList end end return {} end if FFlagHandlePlayerBlockListsInternalPermissive == false then spawn(function() BlockedList = GetBlockedPlayersAsync() GetBlockedPlayersCompleted = true end) end local function getBlockedUserIdsFromBlockedList() local userIdList = {} for userId, _ in pairs(BlockedList) do table.insert(userIdList, userId) end return userIdList end local function getBlockedUserIds() if LocalPlayer.UserId > 0 then local timeWaited = 0 while true do if GetBlockedPlayersCompleted then return getBlockedUserIdsFromBlockedList() end timeWaited = timeWaited + wait() if timeWaited > GET_BLOCKED_USERIDS_TIMEOUT then return {} end end end return {} end local function initializeBlockList() if FFlagHandlePlayerBlockListsInternalPermissive then spawn(function() BlockedList = GetBlockedPlayersAsync() GetBlockedPlayersCompleted = true local RemoteEvent_SetPlayerBlockList = RobloxReplicatedStorage:WaitForChild('SetPlayerBlockList') local blockedUserIds = getBlockedUserIds() RemoteEvent_SetPlayerBlockList:FireServer(blockedUserIds) end) end end local function isBlocked(userId) if (BlockedList[userId]) then return true end return false end local function isMuted(userId) if (MutedList[userId] ~= nil and MutedList[userId] == true) then return true end return false end local function BlockPlayerAsync(playerToBlock) if playerToBlock and LocalPlayer ~= playerToBlock then local blockUserId = playerToBlock.UserId if blockUserId > 0 then if not isBlocked(blockUserId) then BlockedList[blockUserId] = true BlockStatusChanged:fire(blockUserId, true) if FFlagHandlePlayerBlockListsInternalPermissive then if RemoteEvent_UpdatePlayerBlockList then RemoteEvent_UpdatePlayerBlockList:FireServer(blockUserId, true) end end local success, wasBlocked = pcall(function() local apiPath = "userblock/block" local params = "userId=" ..tostring(playerToBlock.UserId) local request = HttpRbxApiService:PostAsync(apiPath, params, Enum.ThrottlingPriority.Default, Enum.HttpContentType.ApplicationUrlEncoded) response = request and game:GetService('HttpService'):JSONDecode(request) return response and response.success end) return success and wasBlocked else return true end end end return false end local function UnblockPlayerAsync(playerToUnblock) if playerToUnblock then local unblockUserId = playerToUnblock.UserId if isBlocked(unblockUserId) then BlockedList[unblockUserId] = nil BlockStatusChanged:fire(unblockUserId, false) if FFlagHandlePlayerBlockListsInternalPermissive then if RemoteEvent_UpdatePlayerBlockList then RemoteEvent_UpdatePlayerBlockList:FireServer(unblockUserId, false) end end local success, wasUnBlocked = pcall(function() local apiPath = "userblock/unblock" local params = "userId=" ..tostring(playerToUnblock.UserId) local request = HttpRbxApiService:PostAsync(apiPath, params, Enum.ThrottlingPriority.Default, Enum.HttpContentType.ApplicationUrlEncoded) response = request and game:GetService('HttpService'):JSONDecode(request) return response and response.success end) return success and wasUnBlocked else return true end end return false end local function MutePlayer(playerToMute) if playerToMute and LocalPlayer ~= playerToMute then local muteUserId = playerToMute.UserId if muteUserId > 0 then if not isMuted(muteUserId) then MutedList[muteUserId] = true MuteStatusChanged:fire(muteUserId, true) end end end end local function UnmutePlayer(playerToUnmute) if playerToUnmute then local unmuteUserId = playerToUnmute.UserId MutedList[unmuteUserId] = nil MuteStatusChanged:fire(unmuteUserId, false) end end function createPlayerDropDown() local playerDropDown = {} playerDropDown.Player = nil playerDropDown.PopupFrame = nil playerDropDown.HidePopupImmediately = false playerDropDown.PopupFrameOffScreenPosition = nil -- if this is set the popup frame tweens to a different offscreen position than the default playerDropDown.HiddenSignal = createSignal() --[[ Functions for when options in the dropdown are pressed ]]-- local function onFriendButtonPressed() if playerDropDown.Player then local status = getFriendStatus(playerDropDown.Player) if status == Enum.FriendStatus.Friend then LocalPlayer:RevokeFriendship(playerDropDown.Player) elseif status == Enum.FriendStatus.Unknown or status == Enum.FriendStatus.NotFriend then -- cache and spawn local cachedLastSelectedPlayer = playerDropDown.Player spawn(function() -- check for max friends before letting them send the request if canSendFriendRequestAsync(cachedLastSelectedPlayer) then -- Yields if cachedLastSelectedPlayer and cachedLastSelectedPlayer.Parent == PlayersService then AnalyticsService:ReportCounter("PlayerDropDown-RequestFriendship") AnalyticsService:TrackEvent("Game", "RequestFriendship", "PlayerDropDown") LocalPlayer:RequestFriendship(cachedLastSelectedPlayer) end end end) elseif status == Enum.FriendStatus.FriendRequestSent then AnalyticsService:ReportCounter("PlayerDropDown-RevokeFriendship") AnalyticsService:TrackEvent("Game", "RevokeFriendship", "PlayerDropDown") LocalPlayer:RevokeFriendship(playerDropDown.Player) elseif status == Enum.FriendStatus.FriendRequestReceived then AnalyticsService:ReportCounter("PlayerDropDown-RequestFriendship") AnalyticsService:TrackEvent("Game", "RequestFriendship", "PlayerDropDown") LocalPlayer:RequestFriendship(playerDropDown.Player) end playerDropDown:Hide() end end local function onDeclineFriendButonPressed() if playerDropDown.Player then LocalPlayer:RevokeFriendship(playerDropDown.Player) playerDropDown:Hide() end end -- Client unfollows followedUserId local function onUnfollowButtonPressed() if not playerDropDown.Player then return end local followedUserId = tostring(playerDropDown.Player.UserId) local apiPath = "user/unfollow" local params = "followedUserId="..followedUserId local success, result = pcall(function() return HttpRbxApiService:PostAsync(apiPath, params, Enum.ThrottlingPriority.Default, Enum.HttpContentType.ApplicationUrlEncoded, Enum.HttpRequestType.Players) end) if not success then print("unfollowPlayer() failed because", result) playerDropDown:Hide() return end result = HttpService:JSONDecode(result) if result["success"] then if fixPlayerlistFollowingEnabled then recentApiRequests["Following"][followedUserId] = false local text = "no longer following "..playerDropDown.Player.Name if FFlagUseNotificationsLocalization then text = string.gsub(LocalizedGetString("PlayerDropDown.onUnfollowButtonPress.success",text),"{RBX_NAME}",playerDropDown.Player.Name) end sendNotification("You are", text, FRIEND_IMAGE..followedUserId.."&x=48&y=48", 5, function() end) end if RemoteEvent_NewFollower then RemoteEvent_NewFollower:FireServer(playerDropDown.Player, false) end moduleApiTable.FollowerStatusChanged:fire() end playerDropDown:Hide() end local function onBlockButtonPressed() if playerDropDown.Player then local cachedPlayer = playerDropDown.Player spawn(function() BlockPlayerAsync(cachedPlayer) end) playerDropDown:Hide() end end local function onUnblockButtonPressed() if playerDropDown.Player then local cachedPlayer = playerDropDown.Player spawn(function() UnblockPlayerAsync(cachedPlayer) end) playerDropDown:Hide() end end local function onReportButtonPressed() if playerDropDown.Player then reportAbuseMenu:ReportPlayer(playerDropDown.Player) playerDropDown:Hide() end end -- Client follows followedUserId local function onFollowButtonPressed() if not playerDropDown.Player then return end -- local followedUserId = tostring(playerDropDown.Player.UserId) local apiPath = "user/follow" local params = "followedUserId="..followedUserId local success, result = pcall(function() return HttpRbxApiService:PostAsync(apiPath, params, Enum.ThrottlingPriority.Default, Enum.HttpContentType.ApplicationUrlEncoded, Enum.HttpRequestType.Players) end) if not success then print("followPlayer() failed because", result) playerDropDown:Hide() return end result = HttpService:JSONDecode(result) if result["success"] then if fixPlayerlistFollowingEnabled then recentApiRequests["Following"][followedUserId] = true end local text = "now following "..playerDropDown.Player.Name if FFlagUseNotificationsLocalization then text = string.gsub(LocalizedGetString("PlayerDropDown.onFollowButtonPress.success",text),"{RBX_NAME}",playerDropDown.Player.Name) end sendNotification("You are", text, FRIEND_IMAGE..followedUserId.."&x=48&y=48", 5, function() end) if RemoteEvent_NewFollower then RemoteEvent_NewFollower:FireServer(playerDropDown.Player, true) end moduleApiTable.FollowerStatusChanged:fire() end playerDropDown:Hide() end local function createPopupFrame(buttons) local frame = Instance.new('Frame') frame.Name = "PopupFrame" frame.Size = UDim2.new(1, 0, 0, (POPUP_ENTRY_SIZE_Y * #buttons) + (#buttons - ENTRY_PAD)) frame.Position = UDim2.new(1, 1, 0, 0) frame.BackgroundTransparency = 1 for i,button in ipairs(buttons) do local btn = Instance.new('TextButton') btn.Name = button.Name btn.Size = UDim2.new(1, 0, 0, POPUP_ENTRY_SIZE_Y) btn.Position = UDim2.new(0, 0, 0, POPUP_ENTRY_SIZE_Y * (i - 1) + ((i - 1) * ENTRY_PAD)) btn.BackgroundTransparency = BG_TRANSPARENCY btn.BackgroundColor3 = BG_COLOR btn.BorderSizePixel = 0 btn.Text = button.Text btn.Font = Enum.Font.SourceSans btn.FontSize = Enum.FontSize.Size14 btn.TextColor3 = TEXT_COLOR btn.TextStrokeTransparency = TEXT_STROKE_TRANSPARENCY btn.TextStrokeColor3 = TEXT_STROKE_COLOR btn.AutoButtonColor = true btn.Parent = frame btn.MouseButton1Click:connect(button.OnPress) end return frame end local TWEEN_TIME = 0.25 function playerDropDown:Hide() if playerDropDown.PopupFrame then local offscreenPosition = (playerDropDown.PopupFrameOffScreenPosition ~= nil and playerDropDown.PopupFrameOffScreenPosition or UDim2.new(1, 1, 0, playerDropDown.PopupFrame.Position.Y.Offset)) if not playerDropDown.HidePopupImmediately then playerDropDown.PopupFrame:TweenPosition(offscreenPosition, Enum.EasingDirection.InOut, Enum.EasingStyle.Quad, TWEEN_TIME, true, function() if playerDropDown.PopupFrame then playerDropDown.PopupFrame:Destroy() playerDropDown.PopupFrame = nil end end) else playerDropDown.PopupFrame:Destroy() playerDropDown.PopupFrame = nil end end if playerDropDown.Player then playerDropDown.Player = nil end playerDropDown.HiddenSignal:fire() end function playerDropDown:CreatePopup(Player) playerDropDown.Player = Player local buttons = {} local status = getFriendStatus(playerDropDown.Player) local friendText = "" local canDeclineFriend = false if status == Enum.FriendStatus.Friend then friendText = "Unfriend Player" elseif status == Enum.FriendStatus.Unknown or status == Enum.FriendStatus.NotFriend then friendText = "Send Friend Request" elseif status == Enum.FriendStatus.FriendRequestSent then friendText = "Revoke Friend Request" elseif status == Enum.FriendStatus.FriendRequestReceived then friendText = "Accept Friend Request" canDeclineFriend = true end local blocked = isBlocked(playerDropDown.Player.UserId) if not blocked then table.insert(buttons, { Name = "FriendButton", Text = friendText, OnPress = onFriendButtonPressed, }) end if canDeclineFriend and not blocked then table.insert(buttons, { Name = "DeclineFriend", Text = "Decline Friend Request", OnPress = onDeclineFriendButonPressed, }) end -- following status local following = isFollowing(playerDropDown.Player.UserId, LocalPlayer.UserId) local followerText = following and "Unfollow Player" or "Follow Player" if not blocked then table.insert(buttons, { Name = "FollowerButton", Text = followerText, OnPress = following and onUnfollowButtonPressed or onFollowButtonPressed, }) end local blockedText = blocked and "Unblock Player" or "Block Player" table.insert(buttons, { Name = "BlockButton", Text = blockedText, OnPress = blocked and onUnblockButtonPressed or onBlockButtonPressed, }) table.insert(buttons, { Name = "ReportButton", Text = "Report Abuse", OnPress = onReportButtonPressed, }) if playerDropDown.PopupFrame then playerDropDown.PopupFrame:Destroy() end playerDropDown.PopupFrame = createPopupFrame(buttons) return playerDropDown.PopupFrame end PlayersService.PlayerRemoving:connect(function(leavingPlayer) if playerDropDown.Player == leavingPlayer then playerDropDown:Hide() end end) return playerDropDown end --- GetCore Blocked/Muted/Friended events. local PlayerBlockedEvent = Instance.new("BindableEvent") local PlayerUnblockedEvent = Instance.new("BindableEvent") local PlayerMutedEvent = Instance.new("BindableEvent") local PlayerUnMutedEvent = Instance.new("BindableEvent") local PlayerFriendedEvent = Instance.new("BindableEvent") local PlayerUnFriendedEvent = Instance.new("BindableEvent") BlockStatusChanged:connect(function(userId, isBlocked) local player = PlayersService:GetPlayerByUserId(userId) if player then if isBlocked then PlayerBlockedEvent:Fire(player) else PlayerUnblockedEvent:Fire(player) end end end) MuteStatusChanged:connect(function(userId, isMuted) local player = PlayersService:GetPlayerByUserId(userId) if player then if isMuted then PlayerMutedEvent:Fire(player) else PlayerUnMutedEvent:Fire(player) end end end) LocalPlayer.FriendStatusChanged:connect(function(player, friendStatus) if friendStatus == Enum.FriendStatus.Friend then PlayerFriendedEvent:Fire(player) elseif friendStatus == Enum.FriendStatus.NotFriend then PlayerUnFriendedEvent:Fire(player) end end) StarterGui:RegisterGetCore("PlayerBlockedEvent", function() return PlayerBlockedEvent end) StarterGui:RegisterGetCore("PlayerUnblockedEvent", function() return PlayerUnblockedEvent end) StarterGui:RegisterGetCore("PlayerMutedEvent", function() return PlayerMutedEvent end) StarterGui:RegisterGetCore("PlayerUnmutedEvent", function() return PlayerUnMutedEvent end) StarterGui:RegisterGetCore("PlayerFriendedEvent", function() return PlayerFriendedEvent end) StarterGui:RegisterGetCore("PlayerUnfriendedEvent", function() return PlayerUnFriendedEvent end) do moduleApiTable.FollowerStatusChanged = createSignal() function moduleApiTable:CreatePlayerDropDown() return createPlayerDropDown() end function moduleApiTable:GetFriendCountAsync(player) return getFriendCountAsync(player.UserId) end function moduleApiTable:InitBlockListAsync() initializeBlockList() end function moduleApiTable:MaxFriendCount() return MAX_FRIEND_COUNT end function moduleApiTable:GetFriendStatus() return getFriendStatus() end function moduleApiTable:CreateBlockingUtility() local blockingUtility = {} function blockingUtility:BlockPlayerAsync(player) return BlockPlayerAsync(player) end function blockingUtility:UnblockPlayerAsync(player) return UnblockPlayerAsync(player) end function blockingUtility:MutePlayer(player) return MutePlayer(player) end function blockingUtility:UnmutePlayer(player) return UnmutePlayer(player) end function blockingUtility:IsPlayerBlockedByUserId(userId) return isBlocked(userId) end function blockingUtility:GetBlockedStatusChangedEvent() return BlockStatusChanged end function blockingUtility:GetMutedStatusChangedEvent() return MuteStatusChanged end function blockingUtility:IsPlayerMutedByUserId(userId) return isMuted(userId) end function blockingUtility:GetBlockedUserIdsAsync() return getBlockedUserIds() end return blockingUtility end end return moduleApiTable
apache-2.0
kitala1/darkstar
scripts/zones/Port_San_dOria/npcs/Phersula.lua
36
1376
----------------------------------- -- Area: Port San d'Oria -- NPC: Phersula -- Standard Info NPC ----------------------------------- package.loaded["scripts/zones/Port_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Port_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) -- "Flyers for Regine" conditional script FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x80307); 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
fqrouter/luci
modules/freifunk/luasrc/controller/freifunk/freifunk.lua
13
8676
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- module("luci.controller.freifunk.freifunk", package.seeall) function index() local uci = require "luci.model.uci".cursor() local page -- Frontend page = node() page.lock = true page.target = alias("freifunk") page.subindex = true page.index = false page = node("freifunk") page.title = _("Freifunk") page.target = alias("freifunk", "index") page.order = 5 page.setuser = "nobody" page.setgroup = "nogroup" page.i18n = "freifunk" page.index = true page = node("freifunk", "index") page.target = template("freifunk/index") page.title = _("Overview") page.order = 10 page.indexignore = true page = node("freifunk", "contact") page.target = template("freifunk/contact") page.title = _("Contact") page.order = 15 page = node("freifunk", "status") page.target = template("freifunk/public_status") page.title = _("Status") page.order = 20 page.i18n = "base" page.setuser = false page.setgroup = false entry({"freifunk", "status.json"}, call("jsonstatus")) entry({"freifunk", "status", "zeroes"}, call("zeroes"), "Testdownload") entry({"freifunk", "status", "public_status_json"}, call("public_status_json")).leaf = true if nixio.fs.access("/usr/sbin/luci-splash") then assign({"freifunk", "status", "splash"}, {"splash", "publicstatus"}, _("Splash"), 40) end assign({"freifunk", "olsr"}, {"admin", "status", "olsr"}, _("OLSR"), 30) if nixio.fs.access("/etc/config/luci_statistics") then assign({"freifunk", "graph"}, {"admin", "statistics", "graph"}, _("Statistics"), 40) end -- backend assign({"mini", "freifunk"}, {"admin", "freifunk"}, _("Freifunk"), 5) entry({"admin", "freifunk"}, alias("admin", "freifunk", "index"), _("Freifunk"), 5) page = node("admin", "freifunk") page.target = template("freifunk/adminindex") page.title = _("Freifunk") page.order = 5 page = node("admin", "freifunk", "basics") page.target = cbi("freifunk/basics") page.title = _("Basic Settings") page.order = 5 page = node("admin", "freifunk", "basics", "profile") page.target = cbi("freifunk/profile") page.title = _("Profile") page.order = 10 page = node("admin", "freifunk", "basics", "profile_expert") page.target = cbi("freifunk/profile_expert") page.title = _("Profile (Expert)") page.order = 20 page = node("admin", "freifunk", "Index-Page") page.target = cbi("freifunk/user_index") page.title = _("Index Page") page.order = 50 page = node("admin", "freifunk", "contact") page.target = cbi("freifunk/contact") page.title = _("Contact") page.order = 15 entry({"freifunk", "map"}, template("freifunk-map/frame"), _("Map"), 50) entry({"freifunk", "map", "content"}, template("freifunk-map/map"), nil, 51) entry({"admin", "freifunk", "profile_error"}, template("freifunk/profile_error")) end local function fetch_olsrd() local sys = require "luci.sys" local util = require "luci.util" local table = require "table" local rawdata = sys.httpget("http://127.0.0.1:2006/") if #rawdata == 0 then if nixio.fs.access("/proc/net/ipv6_route", "r") then rawdata = sys.httpget("http://[::1]:2006/") if #rawdata == 0 then return nil end else return nil end end local data = {} local tables = util.split(util.trim(rawdata), "\r?\n\r?\n", nil, true) for i, tbl in ipairs(tables) do local lines = util.split(tbl, "\r?\n", nil, true) local name = table.remove(lines, 1):sub(8) local keys = util.split(table.remove(lines, 1), "\t") local split = #keys - 1 data[name] = {} for j, line in ipairs(lines) do local fields = util.split(line, "\t", split) data[name][j] = {} for k, key in pairs(keys) do data[name][j][key] = fields[k] end if data[name][j].Linkcost then data[name][j].LinkQuality, data[name][j].NLQ, data[name][j].ETX = data[name][j].Linkcost:match("([%w.]+)/([%w.]+)[%s]+([%w.]+)") end end end return data end function zeroes() local string = require "string" local http = require "luci.http" local zeroes = string.rep(string.char(0), 8192) local cnt = 0 local lim = 1024 * 1024 * 1024 http.prepare_content("application/x-many-zeroes") while cnt < lim do http.write(zeroes) cnt = cnt + #zeroes end end function jsonstatus() local root = {} local sys = require "luci.sys" local uci = require "luci.model.uci" local util = require "luci.util" local http = require "luci.http" local json = require "luci.json" local ltn12 = require "luci.ltn12" local version = require "luci.version" local webadmin = require "luci.tools.webadmin" local cursor = uci.cursor_state() local ffzone = webadmin.firewall_find_zone("freifunk") local ffznet = ffzone and cursor:get("firewall", ffzone, "network") local ffwifs = ffznet and util.split(ffznet, " ") or {} root.protocol = 1 root.system = { uptime = {sys.uptime()}, loadavg = {sys.loadavg()}, sysinfo = {sys.sysinfo()}, hostname = sys.hostname() } root.firmware = { luciname=version.luciname, luciversion=version.luciversion, distname=version.distname, distversion=version.distversion } root.freifunk = {} cursor:foreach("freifunk", "public", function(s) root.freifunk[s[".name"]] = s end) cursor:foreach("system", "system", function(s) root.geo = { latitude = s.latitude, longitude = s.longitude } end) root.network = {} root.wireless = {devices = {}, interfaces = {}, status = {}} local wifs = root.wireless.interfaces local netdata = luci.sys.net.deviceinfo() or {} for _, vif in ipairs(ffwifs) do root.network[vif] = cursor:get_all("network", vif) root.wireless.devices[vif] = cursor:get_all("wireless", vif) cursor:foreach("wireless", "wifi-iface", function(s) if s.device == vif and s.network == vif then wifs[#wifs+1] = s if s.ifname then local iwinfo = luci.sys.wifi.getiwinfo(s.ifname) if iwinfo then root.wireless.status[s.ifname] = { } local _, f for _, f in ipairs({ "channel", "txpower", "bitrate", "signal", "noise", "quality", "quality_max", "mode", "ssid", "bssid", "encryption", "ifname" }) do root.wireless.status[s.ifname][f] = iwinfo[f] end end end end end) end root.olsrd = fetch_olsrd() http.prepare_content("application/json") ltn12.pump.all(json.Encoder(root):source(), http.write) end function public_status_json(devs) local twa = require "luci.tools.webadmin" local sys = require "luci.sys" local i18n = require "luci.i18n" local rv = { } local dev for dev in devs:gmatch("[%w%.%-]+") do local j = { id = dev } local iw = luci.sys.wifi.getiwinfo(dev) if iw then local f for _, f in ipairs({ "channel", "txpower", "bitrate", "signal", "noise", "quality", "quality_max", "mode", "ssid", "bssid", "encryption", "ifname" }) do j[f] = iw[f] end end rv[#rv+1] = j end local load1, load5, load15 = sys.loadavg() local _, _, memtotal, memcached, membuffers, memfree = sys.sysinfo() local mem = string.format("%.2f MB (%.2f %s, %.2f %s, %.2f %s, %.2f %s)", tonumber(memtotal) / 1024, tonumber(memtotal - memfree) / 1024, tostring(i18n.translate("used")), memfree / 1024, tostring(i18n.translate("free")), memcached / 1024, tostring(i18n.translate("cached")), membuffers / 1024, tostring(i18n.translate("buffered")) ) local dr4 = sys.net.defaultroute() local dr6 = sys.net.defaultroute6() if dr6 then def6 = { gateway = dr6.nexthop:string(), dest = dr6.dest:string(), dev = dr6.device, metr = dr6.metric } end if dr4 then def4 = { gateway = dr4.gateway:string(), dest = dr4.dest:string(), dev = dr4.device, metr = dr4.metric } else local dr = sys.exec("ip r s t olsr-default") if dr then local dest, gateway, dev, metr = dr:match("^(%w+) via (%d+.%d+.%d+.%d+) dev (%w+) +metric (%d+)") def4 = { dest = dest, gateway = gateway, dev = dev, metr = metr } end end rv[#rv+1] = { time = os.date("%a, %d %b %Y, %H:%M:%S"), uptime = twa.date_format(tonumber(sys.uptime())), load = string.format("%.2f, %.2f, %.2f", load1, load5, load15), mem = mem, defroutev4 = def4, defroutev6 = def6 } luci.http.prepare_content("application/json") luci.http.write_json(rv) return end
apache-2.0
klukonin/openwisp-config
openwisp-config/tests/test_restore_unmanaged.lua
1
1640
-- manually add lib dir to lua package path package.path = package.path .. ';../files/lib/?.lua' require('os') require('io') luaunit = require('luaunit') restore_unmanaged = assert(loadfile("../files/sbin/openwisp-restore-unmanaged.lua")) write_dir = './unmanaged/' TestRestoreUnmanaged = { setUp = function() os.execute('mkdir ' .. write_dir) os.execute('cp ./config/network ./restore/network-backup') os.execute('cp ./restore/network ' .. write_dir) end, tearDown = function() os.execute('mv ./restore/network-backup ./config/network') os.execute('rm -rf ' .. write_dir) end } function TestRestoreUnmanaged.test_empty() restore_unmanaged('--test=1') os.execute('rm -rf ' .. write_dir) local file = io.open(write_dir .. 'network') luaunit.assertNil(file) end function TestRestoreUnmanaged.test_default() restore_unmanaged('--test=1') local file = io.open(write_dir .. 'network') luaunit.assertNotNil(file) local contents = file:read('*all') luaunit.assertNotNil(string.find(contents, "option unmanaged_test '1'")) luaunit.assertNotNil(string.find(contents, "option ifname 'eth0'")) luaunit.assertNil(string.find(contents, "option test_restore '1'")) end function TestRestoreUnmanaged.test_duplicate() restore_unmanaged('--test=1') restore_unmanaged('--test=1') local file = io.open(write_dir .. 'network') luaunit.assertNotNil(file) local contents = file:read('*all') local _, count = string.gsub(contents, "list ipaddr '10.0.0.1/24'", "") luaunit.assertEquals(count, 1) end os.exit(luaunit.LuaUnit.run())
gpl-3.0
adiyoss/DeepWDM
back_end/run.lua
1
4684
---------------------------------------------------------------------- require 'torch' --require('mobdebug').start() ---------------------------------------------------------------------- print '==> processing options' cmd = torch.CmdLine() cmd:text() cmd:text('Options:') -- global: cmd:option('-seed', 1, 'fixed input seed for repeatable experiments') cmd:option('-threads', 4, 'number of threads') cmd:option('-patience', 5, 'the number of epochs to be patient before early stopping') cmd:option('-epsilon', 0.01, 'the minimum amount of loss improvment require for keep training the model') -- data: cmd:option('-folder_path', 'data/', 'the path to the data files') cmd:option('-x_filename', 'x.t7', 'the features filename') cmd:option('-y_filename', 'y.t7', 'the labels filename') cmd:option('-input_dim', 39, 'the input size') cmd:option('-output_dim', 2, 'the output size') cmd:option('-val_percentage', 0.1, 'the percentage of exampels to be considered as validation set from the training set') -- model: cmd:option('-model', '2birnn', 'type of model to construct: mlp | birnn | 2birnn | rnn | 2rnn') cmd:option('-drop_out', 0.5, 'dropout rate') -- loss: cmd:option('-loss', 'nll', 'type of loss function to minimize: nll') -- training: cmd:option('-save', 'results/', 'subdirectory to save/log experiments in') cmd:option('-plot', false, 'live plot') cmd:option('-optimization', 'ADAGRAD', 'optimization method: SGD | ADAM | ADAGRAD') cmd:option('-learningRate', 0.01, 'learning rate at t=0') cmd:option('-batchSize', 1, 'mini-batch size (1 = pure stochastic)') cmd:option('-weightDecay', 0, 'weight decay (SGD only)') cmd:option('-momentum', 0, 'momentum (SGD only)') cmd:option('-type', 'double', 'type: double | float | cuda') cmd:option('-rho', 100, 'max sequence length') cmd:text() opt = cmd:parse(arg or {}) paramsLogger = io.open(paths.concat(opt.save, 'params.log'), 'w') -- save cmd parameters for key, value in pairs(opt) do paramsLogger:write(key .. ': ' .. tostring(value) .. '\n') end paramsLogger:close() -- nb of threads and fixed seed (for repeatable experiments) if opt.type == 'float' then print('==> switching to floats') torch.setdefaulttensortype('torch.FloatTensor') elseif opt.type == 'cuda' then print('==> switching to CUDA') require 'cunn' torch.setdefaulttensortype('torch.FloatTensor') end torch.setnumthreads(opt.threads) torch.manualSeed(opt.seed) ---------------------------------------------------------------------- print '==> executing all' dofile 'data.lua' dofile 'model.lua' dofile 'loss.lua' dofile 'train.lua' dofile 'validate.lua' ---------------------------------------------------------------------- print '==> training!' local iteration = 1 local best_loss = 100000 local loss = 0 -- rho time steps rnnTrainData = {} rnnTrainLabels = {} rnnValData = {} rnnValLabels = {} ------------------------------------- -- split to rho timesteps every time local count = 1 for t = 1, trainData:size(), opt.rho do rnnTrainData[count] = {} rnnTrainLabels[count] = {} for i=1, math.min(opt.rho, trainData:size()-t) do table.insert(rnnTrainData[count], trainData.data[t + i]) table.insert(rnnTrainLabels[count], trainData.labels[t + i]) end count = count + 1 end count = 1 for t = 1, valData:size(), opt.rho do rnnValData[count] = {} rnnValLabels[count] = {} for i=1, math.min(opt.rho, valData:size()-t) do table.insert(rnnValData[count], valData.data[t + i]) table.insert(rnnValLabels[count], valData.labels[t + i]) end count = count + 1 end ------------------------------------- loss = validate() print('==> validation loss: ' .. loss) -- training while loss + opt.epsilon < best_loss or iteration < opt.patience do -- train - forward and backprop train() -- validate loss = validate() print('\n==> validation loss: ' .. loss) -- for early stopping criteria if loss + opt.epsilon >= best_loss then -- increase iteration number iteration = iteration + 1 print('\n========================================') print('==> Loss did not improved, iteration: ' .. iteration) print('========================================\n') else -- update the best loss value best_loss = loss -- save/log current net local filename = paths.concat(opt.save, 'model.net') os.execute('mkdir -p ' .. sys.dirname(filename)) print('==> saving model to '..filename) torch.save(filename, model) iteration = 1 end end --[[ -- evaluate on the test set local test_loss = test(test_x, test_y) print('\n============ EVALUATING ON TEST SET ============') print('Loss = ' .. test_loss .. '\n') ]]--
mit
Roblox/Core-Scripts
PlayerScripts/StarterPlayerScripts/ControlScript/MasterControl/Thumbpad.lua
2
8574
--[[ // FileName: Thumbpad // Version 1.0 // Written by: jmargh // Description: Implements thumbpad controls for touch devices --]] local Players = game:GetService('Players') local UserInputService = game:GetService('UserInputService') local GuiService = game:GetService('GuiService') local Thumbpad = {} local MasterControl = require(script.Parent) --[[ Script Variables ]]-- while not Players.LocalPlayer do wait() end local LocalPlayer = Players.LocalPlayer local ThumbpadFrame = nil local TouchObject = nil local OnInputEnded = nil -- is defined in Create() local OnTouchChangedCn = nil local OnTouchEndedCn = nil local currentMoveVector = Vector3.new(0,0,0) --[[ Constants ]]-- local DPAD_SHEET = "rbxasset://textures/ui/DPadSheet.png" local TOUCH_CONTROL_SHEET = "rbxasset://textures/ui/TouchControlsSheet.png" --[[ Local Functions ]]-- local function createArrowLabel(name, parent, position, size, rectOffset, rectSize) local image = Instance.new('ImageLabel') image.Name = name image.Image = DPAD_SHEET image.ImageRectOffset = rectOffset image.ImageRectSize = rectSize image.BackgroundTransparency = 1 image.ImageColor3 = Color3.new(190/255, 190/255, 190/255) image.Size = size image.Position = position image.Parent = parent return image end --[[ Public API ]]-- function Thumbpad:Enable() ThumbpadFrame.Visible = true end function Thumbpad:Disable() ThumbpadFrame.Visible = false OnInputEnded() end function Thumbpad:Create(parentFrame) if ThumbpadFrame then ThumbpadFrame:Destroy() ThumbpadFrame = nil if OnTouchChangedCn then OnTouchChangedCn:disconnect() OnTouchChangedCn = nil end if OnTouchEndedCn then OnTouchEndedCn:disconnect() OnTouchEndedCn = nil end end local minAxis = math.min(parentFrame.AbsoluteSize.x, parentFrame.AbsoluteSize.y) local isSmallScreen = minAxis <= 500 local thumbpadSize = isSmallScreen and 70 or 120 local position = isSmallScreen and UDim2.new(0, thumbpadSize * 1.25, 1, -thumbpadSize - 20) or UDim2.new(0, thumbpadSize/2 - 10, 1, -thumbpadSize * 1.75 - 10) ThumbpadFrame = Instance.new('Frame') ThumbpadFrame.Name = "ThumbpadFrame" ThumbpadFrame.Visible = false ThumbpadFrame.Active = true ThumbpadFrame.Size = UDim2.new(0, thumbpadSize + 20, 0, thumbpadSize + 20) ThumbpadFrame.Position = position ThumbpadFrame.BackgroundTransparency = 1 local outerImage = Instance.new('ImageLabel') outerImage.Name = "OuterImage" outerImage.Image = TOUCH_CONTROL_SHEET outerImage.ImageRectOffset = Vector2.new(0, 0) outerImage.ImageRectSize = Vector2.new(220, 220) outerImage.BackgroundTransparency = 1 outerImage.Size = UDim2.new(0, thumbpadSize, 0, thumbpadSize) outerImage.Position = UDim2.new(0, 10, 0, 10) outerImage.Parent = ThumbpadFrame local smArrowSize = isSmallScreen and UDim2.new(0, 32, 0, 32) or UDim2.new(0, 64, 0, 64) local lgArrowSize = UDim2.new(0, smArrowSize.X.Offset * 2, 0, smArrowSize.Y.Offset * 2) local imgRectSize = Vector2.new(110, 110) local smImgOffset = isSmallScreen and -4 or -9 local lgImgOffset = isSmallScreen and -28 or -55 local dArrow = createArrowLabel("DownArrow", outerImage, UDim2.new(0.5, -smArrowSize.X.Offset/2, 1, lgImgOffset), smArrowSize, Vector2.new(8, 8), imgRectSize) local uArrow = createArrowLabel("UpArrow", outerImage, UDim2.new(0.5, -smArrowSize.X.Offset/2, 0, smImgOffset), smArrowSize, Vector2.new(8, 266), imgRectSize) local lArrow = createArrowLabel("LeftArrow", outerImage, UDim2.new(0, smImgOffset, 0.5, -smArrowSize.Y.Offset/2), smArrowSize, Vector2.new(137, 137), imgRectSize) local rArrow = createArrowLabel("RightArrow", outerImage, UDim2.new(1, lgImgOffset, 0.5, -smArrowSize.Y.Offset/2), smArrowSize, Vector2.new(8, 137), imgRectSize) local function doTween(guiObject, endSize, endPosition) guiObject:TweenSizeAndPosition(endSize, endPosition, Enum.EasingDirection.InOut, Enum.EasingStyle.Linear, 0.15, true) end local padOrigin = nil local deadZone = 0.1 local isRight, isLeft, isUp, isDown = false, false, false, false local vForward = Vector3.new(0, 0, -1) local vRight = Vector3.new(1, 0, 0) local function doMove(pos) MasterControl:AddToPlayerMovement(-currentMoveVector) local delta = Vector2.new(pos.x, pos.y) - padOrigin currentMoveVector = delta / (thumbpadSize/2) -- Scaled Radial Dead Zone local inputAxisMagnitude = currentMoveVector.magnitude if inputAxisMagnitude < deadZone then currentMoveVector = Vector3.new(0, 0, 0) else currentMoveVector = currentMoveVector.unit * ((inputAxisMagnitude - deadZone) / (1 - deadZone)) -- catch possible NAN Vector if currentMoveVector.magnitude == 0 then currentMoveVector = Vector3.new(0, 0, 0) else currentMoveVector = Vector3.new(currentMoveVector.x, 0, currentMoveVector.y).unit end end MasterControl:AddToPlayerMovement(currentMoveVector) local forwardDot = currentMoveVector:Dot(vForward) local rightDot = currentMoveVector:Dot(vRight) if forwardDot > 0.5 then -- UP if not isUp then isUp, isDown = true, false doTween(uArrow, lgArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset, 0, smImgOffset - smArrowSize.Y.Offset * 1.5)) doTween(dArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 1, lgImgOffset)) end elseif forwardDot < -0.5 then -- DOWN if not isDown then isDown, isUp = true, false doTween(dArrow, lgArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset, 1, lgImgOffset + smArrowSize.Y.Offset/2)) doTween(uArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 0, smImgOffset)) end else isUp, isDown = false, false doTween(dArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 1, lgImgOffset)) doTween(uArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 0, smImgOffset)) end if rightDot > 0.5 then if not isRight then isRight, isLeft = true, false doTween(rArrow, lgArrowSize, UDim2.new(1, lgImgOffset + smArrowSize.X.Offset/2, 0.5, -smArrowSize.Y.Offset)) doTween(lArrow, smArrowSize, UDim2.new(0, smImgOffset, 0.5, -smArrowSize.Y.Offset/2)) end elseif rightDot < -0.5 then if not isLeft then isLeft, isRight = true, false doTween(lArrow, lgArrowSize, UDim2.new(0, smImgOffset - smArrowSize.X.Offset * 1.5, 0.5, -smArrowSize.Y.Offset)) doTween(rArrow, smArrowSize, UDim2.new(1, lgImgOffset, 0.5, -smArrowSize.Y.Offset/2)) end else isRight, isLeft = false, false doTween(lArrow, smArrowSize, UDim2.new(0, smImgOffset, 0.5, -smArrowSize.Y.Offset/2)) doTween(rArrow, smArrowSize, UDim2.new(1, lgImgOffset, 0.5, -smArrowSize.Y.Offset/2)) end end --input connections ThumbpadFrame.InputBegan:connect(function(inputObject) --A touch that starts elsewhere on the screen will be sent to a frame's InputBegan event --if it moves over the frame. So we check that this is actually a new touch (inputObject.UserInputState ~= Enum.UserInputState.Begin) if TouchObject or inputObject.UserInputType ~= Enum.UserInputType.Touch or inputObject.UserInputState ~= Enum.UserInputState.Begin then return end ThumbpadFrame.Position = UDim2.new(0, inputObject.Position.x - ThumbpadFrame.AbsoluteSize.x/2, 0, inputObject.Position.y - ThumbpadFrame.Size.Y.Offset/2) padOrigin = Vector2.new(ThumbpadFrame.AbsolutePosition.x + ThumbpadFrame.AbsoluteSize.x/2, ThumbpadFrame.AbsolutePosition.y + ThumbpadFrame.AbsoluteSize.y/2) doMove(inputObject.Position) TouchObject = inputObject end) OnTouchChangedCn = UserInputService.TouchMoved:connect(function(inputObject, isProcessed) if inputObject == TouchObject then doMove(TouchObject.Position) end end) OnInputEnded = function() MasterControl:AddToPlayerMovement(-currentMoveVector) currentMoveVector = Vector3.new(0,0,0) MasterControl:SetIsJumping(false) ThumbpadFrame.Position = position TouchObject = nil isUp, isDown, isLeft, isRight = false, false, false, false doTween(dArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 1, lgImgOffset)) doTween(uArrow, smArrowSize, UDim2.new(0.5, -smArrowSize.X.Offset/2, 0, smImgOffset)) doTween(lArrow, smArrowSize, UDim2.new(0, smImgOffset, 0.5, -smArrowSize.Y.Offset/2)) doTween(rArrow, smArrowSize, UDim2.new(1, lgImgOffset, 0.5, -smArrowSize.Y.Offset/2)) end OnTouchEndedCn = UserInputService.TouchEnded:connect(function(inputObject) if inputObject == TouchObject then OnInputEnded() end end) GuiService.MenuOpened:connect(function() if TouchObject then OnInputEnded() end end) ThumbpadFrame.Parent = parentFrame end return Thumbpad
apache-2.0
kitala1/darkstar
scripts/zones/Lower_Jeuno/npcs/Sutarara.lua
17
1649
----------------------------------- -- Area: Lower Jeuno -- NPC: Sutarara -- Involved in Quests: Tenshodo Menbership (before accepting) -- @pos 30 0.1 -2 245 ----------------------------------- package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/zones/Lower_Jeuno/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local TenshodoMembership = player:getQuestStatus(JEUNO,TENSHODO_MEMBERSHIP); local WildcatJeuno = player:getVar("WildcatJeuno"); if (player:getQuestStatus(JEUNO,LURE_OF_THE_WILDCAT_JEUNO) == QUEST_ACCEPTED and player:getMaskBit(WildcatJeuno,10) == false) then player:startEvent(10055); elseif(TenshodoMembership ~= QUEST_COMPLETED) then player:startEvent(0x00d0); elseif(TenshodoMembership == QUEST_COMPLETED) then player:startEvent(0x00d3); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if (csid == 10055) then player:setMaskBit(player:getVar("WildcatJeuno"),"WildcatJeuno",10,true); end end;
gpl-3.0
kitala1/darkstar
scripts/zones/Davoi/npcs/qm1.lua
17
1419
----------------------------------- -- Area: Davoi -- NPC: ??? (qm1) -- Involved in Quest: To Cure a Cough -- @pos -115.830 -0.427 -184.289 149 ----------------------------------- package.loaded["scripts/zones/Davoi/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/quests"); require("scripts/zones/Davoi/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) local toCureaCough = player:getQuestStatus(SANDORIA,TO_CURE_A_COUGH); if(toCureaCough == QUEST_ACCEPTED and player:hasKeyItem(THYME_MOSS) == false) then player:addKeyItem(THYME_MOSS); player:messageSpecial(KEYITEM_OBTAINED,THYME_MOSS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/globals/mobskills/Onslaught.lua
7
1102
--------------------------------------------- -- Onslaught -- -- Description: Lowers target's accuracy. Additional effect: temporarily increases Attack. -- Type: Physical -- Range: Melee --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,3,3,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local duration = 20; if(mob:getTP() == 300) then duration = 60; elseif(mob:getTP() >= 200) then duration = 40; end MobStatusEffectMove(mob, target, EFFECT_ACCURACY_DOWN, 30, 0, duration); MobBuffMove(mob, EFFECT_ATTACK_BOOST, 10, 0, duration); -- About 300-400 to a DD. target:delHP(dmg); return dmg; end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/piece_of_cascade_candy.lua
36
1148
----------------------------------------- -- ID: 5942 -- Item: Piece of Cascade Candy -- Food Effect: 30Min, All Races ----------------------------------------- -- Mind +4 -- Charisma +4 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) result = 0 if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5942); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MND, 4); target:addMod(MOD_CHR, 4); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MND, 4); target:delMod(MOD_CHR, 4); end;
gpl-3.0
zhaoluxyz/Hugula
Client/tools/netProtocal/parseProtocal.lua
8
2738
require("helperFunction") io.output("../../Assets/Lua/net/netProtocalPaser.lua") io.input("NetProtocalParserCode.lua") local preCode = io.read("*all") io.write(preCode) -- function isEndStruct(line) -- return line == "===" -- end function genParseFunction(startLine) local structName = string.match(startLine, "(%S+)=") local nextLine = getNextValidLine() print("parseProtocal structName" , structName) io.write("function NetProtocalPaser:parse",structName, "(msg, key, parentTable) \n") io.write("\tif(key ~= nil) then\n") io.write("\t\tparentTable[key] = {}\n") io.write("\t\tparentTable = parentTable[key]\n") io.write("\tend\n") while(not isEndStruct(nextLine)) do local valueName, valueType ,z= string.match(nextLine, "(%S+)%s+(%S+)")--"(%S+)%s+(%S+)") local isarr=string.find(nextLine,"array") if isarr ~=nil then --local arrayKeyType = string.match(nextLine, "%S+%s+%S+%s+%$?(%S+)") --arrayKeyType=arrayKeyType:gsub("^%l", string.upper) io.write("\tself:parseArray(msg,","\'", valueName,"\'", ", parentTable,","'", valueType, "'", ")\n") else io.write("\tself:parse", valueType, "(msg,", "\'", valueName, "\'", ", parentTable)\n") end nextLine = getNextValidLine() end io.write("end\n\n") end function genFormatMessageFunction(startLine) local structName = string.match(startLine, "(%S+)=") local nextLine = getNextValidLine() io.write("function NetProtocalPaser:format",structName, "(msg, content) \n") while(not isEndStruct(nextLine)) do local valueName, valueType= string.match(nextLine, "(%S+)%s+(%S+)") -- "(%S+)%s+(%S+)") local isarr=string.find(nextLine,"array") if isarr ~=nil then --local arrayKeyType = string.match(nextLine, "%S+%s+%S+%s+%$?(%S+)") --arrayKeyType=arrayKeyType:gsub("^%l", string.upper) io.write("\tself:formatArray(msg,","content.", valueName,",","'", valueType, "'", ")\n") else io.write("\tif(content.", valueName, " == nil) then print('formatNetMessage Error: ",valueName, " is nil' ) end \n") io.write("\tself:format", valueType, "(msg,", "content.", valueName, ")\n") end nextLine = getNextValidLine() end io.write("end\n\n") end io.input("protocal/protocal.txt") local nextLine = getNextValidLine() while(nextLine ~= nil) do genParseFunction(nextLine) nextLine = getNextValidLine() end io.input("protocal/protocal.txt") local nextLine = getNextValidLine() while(nextLine ~= nil) do genFormatMessageFunction(nextLine) nextLine = getNextValidLine() end
mit
apletnev/koreader
defaults.lua
2
9121
-- To make configuration changes that persists between (nightly) releases, -- copy defaults.lua to defaults.persistent.lua and make the changes there. -- number of page turns between full screen refresh -- default to do a full refresh on every 6 page turns DRCOUNTMAX = 6 -- number of pages for hinting -- default to pre-rendering 1 page DHINTCOUNT = 1 -- full screen mode, 1 for true, 0 for false DFULL_SCREEN = 1 -- scroll mode, 1 for true, 0 for false DSCROLL_MODE = 1 -- default gamma setting: DGLOBALGAMMA = 1.0 -- DjVu page rendering mode (used in djvu.c:drawPage()) -- See comments in djvureader.lua:DJVUReader:select_render_mode() DRENDER_MODE = 0 -- 0 is COLOUR -- minimum cache size DGLOBAL_CACHE_SIZE_MINIMUM = 1024*1024*10 -- proportion of system free memory used as global cache DGLOBAL_CACHE_FREE_PROPORTION = 0.4 -- maximum cache size DGLOBAL_CACHE_SIZE_MAXIMUM = 1024*1024*60 -- background colour in non scroll mode: 8 = gray, 0 = white, 15 = black DBACKGROUND_COLOR = 0 -- outer page colour in scroll mode: 8 = gray, 0 = white, 15 = black DOUTER_PAGE_COLOR = 0 -- supported view mode includes: "scroll" and "page" DCREREADER_VIEW_MODE = "page" -- show dimmed area to indicate page overlap in "page" view mode, -- default to false DSHOWOVERLAP = false -- show hidden files in filemanager -- default to false DSHOWHIDDENFILES = false -- landscape clockwise rotation -- default to true, set to false for counterclockwise rotation DLANDSCAPE_CLOCKWISE_ROTATION = true -- default minimum screen height for reading with 2 pages in landscape mode DCREREADER_TWO_PAGE_THRESHOLD = 7 -- page overlap pixels DOVERLAPPIXELS = 30 -- timeout to show link rectangle around links -- default to 0.5 second -- set to 0 to disable showing rectangle and follow link immediately FOLLOW_LINK_TIMEOUT = 0.5 -- customizable tap zones(rectangles) -- x: x coordinate of top left corner in proportion of screen width -- y: y coordinate of top left corner in proportion of screen height -- w: width of tap zone in proportion of screen width -- h: height of tap zone in proportion of screen height DTAP_ZONE_MENU = {x = 1/8, y = 0, w = 3/4, h = 1/8} DTAP_ZONE_CONFIG = {x = 1/8, y = 7/8, w = 3/4, h = 1/8} DTAP_ZONE_MINIBAR = {x = 0, y = 15/16, w = 1, h = 1/16} DTAP_ZONE_FORWARD = {x = 1/4, y = 0, w = 3/4, h = 1} DTAP_ZONE_BACKWARD = {x = 0, y = 0, w = 1/4, h = 1} DTAP_ZONE_BOOKMARK = {x = 7/8, y = 0, w = 1/8, h = 1/8} DTAP_ZONE_FLIPPING = {x = 0, y = 0, w = 1/8, h = 1/8} DDOUBLE_TAP_ZONE_NEXT_CHAPTER = {x = 6/8, y = 0, w = 2/8, h = 2/8} DDOUBLE_TAP_ZONE_PREV_CHAPTER = {x = 0, y = 0, w = 2/8, h = 2/8} -- behaviour of swipes DCHANGE_WEST_SWIPE_TO_EAST = false DCHANGE_EAST_SWIPE_TO_WEST = false -- koptreader config defaults DKOPTREADER_CONFIG_FONT_SIZE = 1.0 -- range from 0.1 to 3.0 DKOPTREADER_CONFIG_TEXT_WRAP = 0 -- 1 = on, 0 = off DKOPTREADER_CONFIG_TRIM_PAGE = 1 -- 1 = auto, 0 = manual DKOPTREADER_CONFIG_DETECT_INDENT = 1 -- 1 = enable, 0 = disable DKOPTREADER_CONFIG_DEFECT_SIZE = 1.0 -- range from 0.0 to 3.0 DKOPTREADER_CONFIG_PAGE_MARGIN = 0.10 -- range from 0.0 to 1.0 DKOPTREADER_CONFIG_LINE_SPACING = 1.2 -- range from 0.5 to 2.0 DKOPTREADER_CONFIG_RENDER_QUALITY = 1.0 -- range from 0.5 to 2.0 DKOPTREADER_CONFIG_AUTO_STRAIGHTEN = 0 -- range from 0 to 10 DKOPTREADER_CONFIG_JUSTIFICATION = 3 -- -1 = auto, 0 = left, 1 = center, 2 = right, 3 = full DKOPTREADER_CONFIG_MAX_COLUMNS = 2 -- range from 1 to 4 DKOPTREADER_CONFIG_CONTRAST = 1.0 -- range from 0.2 to 2.0 -- word spacing for reflow DKOPTREADER_CONFIG_WORD_SPACINGS = {0.05, -0.2, 0.375} -- range from (+/-)0.05 to (+/-)0.5 DKOPTREADER_CONFIG_DEFAULT_WORD_SPACING = -0.2 -- range from (+/-)0.05 to (+/-)0.5 -- document languages for OCR DKOPTREADER_CONFIG_DOC_LANGS_TEXT = {"English", "Chinese"} DKOPTREADER_CONFIG_DOC_LANGS_CODE = {"eng", "chi_sim"} -- language code, make sure you have corresponding training data DKOPTREADER_CONFIG_DOC_DEFAULT_LANG_CODE = "eng" -- that have filenames starting with the language codes -- crereader font sizes -- feel free to add more entries in this list DCREREADER_CONFIG_FONT_SIZES = {12, 16, 20, 22, 24, 26, 28, 30, 34, 38, 44} -- option range from 12 to 44 DCREREADER_CONFIG_DEFAULT_FONT_SIZE = 22 -- default font size -- crereader margin sizes -- margin {left, top, right, bottom} in pixels DCREREADER_CONFIG_MARGIN_SIZES_SMALL = {5, 10, 5, 10} DCREREADER_CONFIG_MARGIN_SIZES_MEDIUM = {10, 15, 10, 15} DCREREADER_CONFIG_MARGIN_SIZES_LARGE = {20, 20, 20, 20} -- crereader font gamma DCREREADER_CONFIG_LIGHTER_FONT_GAMMA = 10 DCREREADER_CONFIG_DEFAULT_FONT_GAMMA = 15 DCREREADER_CONFIG_DARKER_FONT_GAMMA = 25 -- crereader line space percentage DCREREADER_CONFIG_LINE_SPACE_PERCENT_SMALL = 90 DCREREADER_CONFIG_LINE_SPACE_PERCENT_MEDIUM = 100 DCREREADER_CONFIG_LINE_SPACE_PERCENT_LARGE = 120 -- crereader progress bar -- 0 for top "full" progress bar -- 1 for bottom "mini" progress bar DCREREADER_PROGRESS_BAR = 1 -- configure "mini" progress bar DMINIBAR_TOC_MARKER_WIDTH = 2 -- Looses usefulness > 3 DMINIBAR_HEIGHT = 7 -- Should be smaller than DMINIBAR_CONTAINER_HEIGHT DMINIBAR_CONTAINER_HEIGHT = 14 -- Larger means more padding at the bottom, at the risk of eating into the last line DMINIBAR_FONT_SIZE = 14 -- change this to any numerical value if you want to automatically save settings when turning pages DAUTO_SAVE_PAGING_COUNT = nil -- dictionary font size DDICT_FONT_SIZE = 20 -- Frontlight decrease of sensitivity for two-fingered pan gesture, -- e.g. 2 changes the sensitivity by 1/2, 3 by 1/3 etc. FRONTLIGHT_SENSITIVITY_DECREASE = 2 -- Normally, KOReader will present file lists sorted in case insensitive manner -- when presenting an alphatically sorted list. So the Order is "A, b, C, d". -- You can switch to a case sensitive sort ("A", "C", "b", "d") by disabling -- insensitive sort DALPHA_SORT_CASE_INSENSITIVE = true -- Set a path to a folder that is filled by Calibre (must contain the file metadata.calibre) -- e.g. -- "/mnt/sd/.hidden" for Kobo with files in ".hidden" on the SD card -- "/mnt/onboard/MyPath" for Kobo with files in "MyPath" on the device itself -- "/mnt/us/documents/" for Kindle files in folder "documents" SEARCH_LIBRARY_PATH = "" SEARCH_LIBRARY_PATH2 = "" -- Search parameters SEARCH_CASESENSITIVE = false SEARCH_AUTHORS = true SEARCH_TITLE = true SEARCH_TAGS = true SEARCH_SERIES = true SEARCH_PATH = true -- Light parameter for Kobo KOBO_LIGHT_ON_START = -2 -- -1, -2 or 0-100. -- -1 uses previous koreader session saved brightness -- -2 uses 'Kobo eReader.conf' brighness, -- other sets light on start to a fix brighness KOBO_SYNC_BRIGHTNESS_WITH_NICKEL = true -- Save brightness set in KOreader -- with nickel's 'Kobo eReader.conf' -- Network proxy settings -- proxy url should be a string in the format of "http://localhost:3128" -- proxy authentication is not supported yet. NETWORK_PROXY = nil -- Experimental features -- Use turbo library to handle async HTTP request DUSE_TURBO_LIB = false -- Custom font dir for Android ANDROID_FONT_DIR = "/system/fonts;/sdcard/koreader/fonts" -- #################################################################### -- following features are not supported right now -- #################################################################### -- set panning distance --DSHIFT_X = 100 --DSHIFT_Y = 50 -- step to change zoom manually, default = 16% --DSTEP_MANUAL_ZOOM = 16 --DPAN_BY_PAGE = false -- using shift_[xy] or width/height --DPAN_MARGIN = 5 -- horizontal margin for two-column zoom (in pixels) --DPAN_OVERLAP_VERTICAL = 30 -- tile cache configuration: --DCACHE_MAX_MEMSIZE = 1024*1024*5 -- 5MB tile cache --DCACHE_MAX_TTL = 20 -- time to live -- renderer cache size --DCACHE_DOCUMENT_SIZE = 1024*1024*8 -- FIXME random, needs testing -- default value for battery level logging --DBATTERY_LOGGING = false -- delay for info messages in ms --DINFO_NODELAY=0 --DINFO_DELAY=1500 -- toggle defaults --DUNIREADER_SHOW_OVERLAP_ENABLE = true --DUNIREADER_SHOW_LINKS_ENABLE = true --DUNIREADER_COMICS_MODE_ENABLE = true --DUNIREADER_RTL_MODE_ENABLE = false --DUNIREADER_PAGE_MODE_ENABLE = false --DDJVUREADER_SHOW_OVERLAP_ENABLE = true --DDJVUREADER_SHOW_LINKS_ENABLE = false --DDJVUREADER_COMICS_MODE_ENABLE = true --DDJVUREADER_RTL_MODE_ENABLE = false --DDJVUREADER_PAGE_MODE_ENABLE = false --DKOPTREADER_SHOW_OVERLAP_ENABLE = true --DKOPTREADER_SHOW_LINKS_ENABLE = false --DKOPTREADER_COMICS_MODE_ENABLE = false --DKOPTREADER_RTL_MODE_ENABLE = false --DKOPTREADER_PAGE_MODE_ENABLE = false --DPICVIEWER_SHOW_OVERLAP_ENABLE = false --DPICVIEWER_SHOW_LINKS_ENABLE = false --DPICVIEWER_COMICS_MODE_ENABLE = true --DPICVIEWER_RTL_MODE_ENABLE = false --DPICVIEWER_PAGE_MODE_ENABLE = false --DKOPTREADER_CONFIG_MULTI_THREADS = 1 -- 1 = on, 0 = off --DKOPTREADER_CONFIG_SCREEN_ROTATION = 0 -- 0, 90, 180, 270 degrees
agpl-3.0
Roblox/Core-Scripts
CoreScriptsRoot/Modules/DevConsole/Constants.lua
1
6593
local Constants = { MainWindowInit = { Position = UDim2.new(.5, -486, .02, 16), Size = UDim2.new(0, 992, .96, -32), Transparency = .36, Padding = UDim.new(0, 5), MinSize = Vector2.new(400, 250), }, FormFactor = { Large = 0, Middle = 1, Small = 2, Console = 3, }, Color = { Black = Color3.fromRGB(0, 0, 0), BaseGray = Color3.fromRGB(30, 30, 30), TextBoxGray = Color3.fromRGB(45, 45, 45), ErrorRed = Color3.fromRGB(215, 90, 74), HighlightBlue = Color3.fromRGB(0, 162, 255), WarningYellow = Color3.fromRGB(255, 218, 68), SelectedBlue = Color3.fromRGB(50, 181, 255), UnselectedGray = Color3.fromRGB(78, 84, 96), SelectedGray = Color3.fromRGB(102, 108, 119), HoverGreen = Color3.fromRGB(70, 197, 124), TabUnselectedGray = Color3.fromRGB(102, 108, 119), BorderGray = Color3.fromRGB(184, 184, 184), Text = Color3.fromRGB(255, 255, 255), ActiveBox = Color3.fromRGB(63, 198, 121), InactiveBox = Color3.fromRGB(184, 184, 184), }, Icon = { -- These values appear differently because of the discrepancy between design sizes and -- the engine sizes Info = "Info.png", Error = "Error.png", Warning = "Warning.png", Close = "Close.png", Sort = "Sort.png", Search = "Search.png", Maximize = "Maximize.png", Minimize = "Minimize.png", }, Image = { Minimize = "rbxasset://textures/DevConsole/Minimize.png", Maximize = "rbxasset://textures/DevConsole/Maximize.png", Clear = "rbxasset://textures/DevConsole/Clear.png", Close = "rbxasset://textures/DevConsole/Close.png", Search = "rbxasset://textures/DevConsole/Search.png", Error = "rbxasset://textures/DevConsole/Error.png", Warning = "rbxasset://textures/DevConsole/Warning.png", Info = "rbxasset://textures/DevConsole/Info.png", Check = "rbxasset://textures/ui/LuaChat/icons/ic-check.png", FilterUnfilled = "rbxasset://textures/DevConsole/Filter-stroke.png", FilterFilled = "rbxasset://textures/DevConsole/Filter-filled.png", RightArrow = "rbxasset://textures/DevConsole/Arrow.png", -- we want rotate this for the over effects DownArrow = "rbxasset://textures/TerrainTools/button_arrow_down.png", -- we can't rotate so we define this }, Padding = { WindowPadding = 8, TabRow = 24, LinePadding = 2, MemoryIndent = 24, }, -- the commented numbers here are the font sizes given by the design spec -- they were changed because the sizing did not match the the visuals in the design spec DefaultFontSize = { TopBar = 18, TabBar = 20, DropDownTabBar = 18, UtilBar = 18, MainWindowHeader = 12, MainWindow = 15, CommandLine = 15, }, Font = { TopBar = Enum.Font.SourceSans, TabBar = Enum.Font.SourceSansBold, UtilBar = Enum.Font.SourceSans, MainWindowHeader = Enum.Font.SourceSansBold, MainWindow = Enum.Font.SourceSans, Log = Enum.Font.Code, }, GeneralFormatting = { NoResultSearchStr = "Did not find results for \"%s.\"", LineWidth = 1, LineColor = Color3.new(1, 1, 1), ArrowWidth = 8, MainRowPadding = 8, LineGraphHeight = 200, HeaderFrameHeight = 20, EntryFrameHeight = 30, DropDownEntryHeight = 40, DropDownEntryWidth = 375, DropDownArrowHeight = 12, }, TopBarFormatting = { BarTransparency = .64, FrameHeight = 30, }, TabRowFormatting = { TabDropDownWidth = 144, FrameHeight = 40, HighlightHeight = 6, SelectedTextTransparency = 0, UnselectedTextTransparency = .5, TabOverlapThreshold = 10, }, UtilityBarFormatting = { FrameHeight = 30, SmallFrameHeight = 24, SmallUtilPadding = 6, -- horizontal padding ClientServerButtonWidth = 100, ClientServerDropDownWidth = 84, CheckBoxHeight = 16, CheckBoxInnerPadding = 6 }, LogFormatting = { MaxStringSize = 16384, IconHeight = 14, TextFrameHeight = 20, TextFramePadding = 2, CommandLineHeight = 30, CommandLineIndent = 30, }, EnumToMsgTypeName = { [Enum.MessageType.MessageOutput.Value] = "Output", [Enum.MessageType.MessageInfo.Value] = "Information", [Enum.MessageType.MessageWarning.Value] = "Warning", [Enum.MessageType.MessageError.Value] = "Error" }, MsgTypeNamesOrdered = { "Output", "Information", "Warning", "Error" }, MemoryFormatting = { ChartHeaderNames = {"Name", "Value MB"}, ValueCellWidth = .2, DepthIndent = 24, CellPadding = 24, ValuePadding = 12, HeaderFrameHeight = 20, EntryFrameHeight = 30, }, NetworkFormatting = { SummaryHeaderNames = {"RequestType", "RequestCount", "FailedCount", "AvgTime(ms)", "MinTime(ms)", "MaxTime(ms)"}, HttpAnalyticsKeys = {"RequestType", "RequestCount", "FailedCount", "AverageTime", "MinTime", "MaxTime"}, ChartHeaderNames = {"No.", "Method", "Status", "Time(ms).", "RequestType", "URL"}, SummaryCellWidths = {120, 120, 120, 120, 120}, -- width of cells 2-6; cell 1 fills remainder ChartCellWidths = {72, 72, 72, 84, 140}, -- widths of cells 1-5; cell 6 is the filler CellPadding = 16, SummaryButtonHeight = 30, HeaderFrameHeight = 20, EntryFrameHeight = 30, ResponseWidthRatio = .8, ResponseStrHeight = 15, MinFrameWidth = 750, }, ServerScriptsFormatting = { ChartHeaderNames = {"Name", "Activity (%)", "Rate (/s)"}, ChartCellWidths = {.6, .2, .2}, HeaderFrameHeight = 20, EntryFrameHeight = 30, CellPadding = 16, ActivityBoxWidth = 12, ActivityBoxPadding = 14, }, DataStoresFormatting = { ChartHeaderNames = {"Name", "Value"}, ValueCellWidth = .2, CellPadding = 16, ExpandArrowPadding = 12, HeaderFrameHeight = 20, EntryFrameHeight = 30, }, ServerStatsFormatting = { ChartHeaderNames = {"Name", "Value"}, ValueCellWidth = .2, CellPadding = 14, ExpandArrowPadding = 12, HeaderFrameHeight = 20, EntryFrameHeight = 30, }, ActionBindingsFormatting = { ChartHeaderNames = {"Name", "Priority", "Security", "Action Name", "Input Types"}, ChartCellWidths = {80, 100, 185}, -- width of cells 2-4; cell 1 fills remainder CellPadding = 16, ExpandArrowPadding = 12, HeaderFrameHeight = 20, EntryFrameHeight = 30, MinFrameWidth = 654, }, ServerJobsFormatting = { ChartHeaderNames = {"Name", "DutyCycle(%)", "Steps Per Sec (/s)", "Step Time (ms)"}, ValueCellWidth = {.31, .23, .23, .23}, -- width of cells 2-4; cell 1 fills remainder CellPadding = 16, ExpandArrowPadding = 12, HeaderFrameHeight = 20, EntryFrameHeight = 30, MinFrameWidth = 654, }, Graph = { PointWidth = 4, PointOffset = 2, -- should be 1/2 pointwidth Padding = 0.15, Scale = 0.7, -- should be 1 - (2 * Padding) InnerPaddingY = 0.1, InnerScaleY = 0.8, -- should be 1 - (2 * innerPaddingY) TextPadding = 10, } } return Constants
apache-2.0
ESAI-CEU-UCH/2014EnergyAndBuildings
scripts/train-ONLINE.lua
1
8543
-- package.path=arg[0]:get_path() .. "modules/?.lua" .. ";/home/experimentos/HERRAMIENTAS/LUA_MODULES/share/;" .. package.path april_print_script_header(arg) hidden_layers = {} columns = {} cmd_opt_parser = cmdOpt{ program_name = string.basename(arg[0]), argument_description = "", main_description = "Trains a model for indoor temperature forecasting", { index_name="data", description="Load data files (a comma separated list)", long="data", argument="yes", mode="always", filter=function(value) return value:tokenize(",") end, default_value="/home/experimentos/CORPORA/SML2010/NEW-DATA-1.T15.txt,/home/experimentos/CORPORA/SML2010/NEW-DATA-2.T15.txt", }, { index_name="col", description="Column with data, the first is the forecasted column, several -c 'POS:WSIZE:MEAN:STDDEV:[diff | abs]' options are allowed", short="c", argument="yes", mode="always", filter=function(value) local t = value:tokenize(":") for i=1,4 do t[i]=tonumber(t[i]) end return t end, action=function(value) table.insert(columns, value) end, }, { index_name="hsize", description="Future horizon size", long="hsize", argument="yes", mode="always", filter=tonumber, }, { index_name="layer", description="Adds a hidden layer", long="layer", argument="yes", action=function(value) print("# Adding layer " .. value) table.insert(hidden_layers, { size = tonumber(value:match("^(.*):.*$")), actf = value:match("^.*:(.*)$"), }) end, }, { index_name="learning_rate", description="Learning rate", long="lr", argument="yes", mode="always", filter=tonumber, default_value=0.2, }, { index_name="momentum", description="Momentum", long="mt", argument="yes", mode="always", filter=tonumber, default_value=0.2, }, { index_name="weight_decay", description="Weight decay", long="wd", argument="yes", mode="always", filter=tonumber, default_value=1e-04, }, { index_name="seed", description="Random seed", long="seed", argument="yes", mode="always", default_value=825725, filter=tonumber, }, { index_name="best", description="Best filename", long="best", argument="yes", }, { description = "shows this help message", short = "h", long = "help", argument = "no", action = function (argument) print(cmd_opt_parser:generate_help()) os.exit(1) end } } local optargs = cmd_opt_parser:parse_args() if type(optargs) == "string" then error(optargs) end table.unpack_on(optargs, _G) -- this generates global variables from optargs local weights_random = random(seed) local input_size = iterator(ipairs(columns)):select(2):field(2):reduce(math.add(),0) + 24 local mlp = ann.components.stack() local input = input_size for i=1,#hidden_layers do mlp:push(ann.components.hyperplane{ input = input, output = hidden_layers[i].size, -- dot_product_weights = "w" .. i, bias_weights = "b" .. i, }) mlp:push(ann.components.actf[hidden_layers[i].actf]()) input = hidden_layers[i].size end mlp:push(ann.components.hyperplane{ input = input, output = hsize, -- dot_product_weights = "w" .. #hidden_layers+1, bias_weights = "b" .. #hidden_layers+1, }) mlp:push(ann.components.actf.linear()) local trainer = trainable.supervised_trainer(mlp, ann.loss.mse(), 1) trainer:build() trainer:randomize_weights{ random = weights_random, inf = -0.1, sup = 0.1, use_fanin = true, use_fanout = true, } -- trainer:set_option("learning_rate", learning_rate) trainer:set_option("momentum", momentum) trainer:set_option("weight_decay", weight_decay) -- trainer:set_layerwise_option("b.*", "weight_decay", 0) printf("# ANN topology: %d inputs %s %d linear\n", trainer:get_input_size(), iterator(ipairs(hidden_layers)): map(function(k,v) return v.size,v.actf end): concat(" "), trainer:get_output_size()) ---------------------- -- ONLINE ALGORITHM -- ---------------------- local TARGET_POS = columns[1][1] local MAX_WSIZE = iterator(ipairs(columns)):select(2):field(2):reduce(math.max,0) for _,filename in ipairs(data) do print("# PROCESSING ", filename) local pos = 0 local outputs = matrix.col_major(MAX_WSIZE+hsize, hsize):zeros() local buffer = matrix.col_major(MAX_WSIZE+hsize, #columns):zeros() local raw_buffer = matrix.col_major(MAX_WSIZE+hsize, #columns):zeros() -- Move up the data of a matrix function move_data(m) local slice = m("2:",":"):clone() m({1,buffer:dim(1)-1}, ":"):copy(slice) end -- Updates the buffer with a new line of data function update_buffer(buf,d) local dest = pos+1 if pos >= buf:dim(1) then move_data(buf) dest=pos end for i=1,#d do buf:set(dest, i, d[i]) end end -- Computes a line of data function compute_data(t) local raw = {} local d = {} for i=1,#columns do local p,wsize,mean,stddev,mode = table.unpack(columns[i]) local v = tonumber(t[p]) table.insert(raw, v) if mode == "diff" then if pos > 0 then v = v - raw_buffer:get(pos,i) else v = 0 end elseif mode ~= "abs" then error("Incorrect column mode") end table.insert(d, (v - mean) / stddev) end update_buffer(raw_buffer, raw) return d end -- Computes the ANN input form the given position and for the given hour function compute_input(pos, hour) local input = matrix.col_major(1,trainer:get_input_size()) -- hour input({1,1},{1,24}):zeros():set(1, hour+1, 1) -- columns local p = 24 for i=1,#columns do local _,wsize,mean,stddev,mode = table.unpack(columns[i]) local w = input({1,1},{p+1,p+wsize}) w:copy( buffer: select(2,i): slice({pos-wsize+1},{wsize}): clone(): rewrap(1,wsize) ) p = p + wsize end return input end -- Computes the ANN output target function compute_target(buf) local target = matrix.col_major(1,trainer:get_output_size()) target:copy( buf: select(2,1): slice({buf:dim(1)-hsize+1},{hsize}): clone(): rewrap(1,hsize) ) return target end -- Output reconstruction function reconstruct_output(pos,out) local p,wsize,mean,stddev,mode = table.unpack(columns[1]) out = out*stddev + mean if mode == "diff" then local aux = raw_buffer: select(2,1): slice({pos-wsize+1},{wsize}): get(wsize) local acc = aux out:map(function(x) x = x + acc acc = x return x end) end return out end -- Computes every line of the current data filename for line in io.uncommented_lines(filename) do collectgarbage("collect") local t = line:tokenize() local hour = tonumber(t[2]:match("(.+)%:.+")) update_buffer( buffer, compute_data(t) ) if pos < MAX_WSIZE + hsize then pos = pos + 1 end -- if pos >= MAX_WSIZE + hsize then -- It is ready to train with following pair of tokens local input = compute_input(pos-hsize+1, hour) local target = compute_target(buffer) target_raw = compute_target(raw_buffer) -- First, computes loss with the data forecasted hsize quarters ago -- Show the output/target pair out_raw = outputs({MAX_WSIZE+1,MAX_WSIZE+1},":") print("OUTPUT: ", table.concat(out_raw:toTable(), " ")) print("TARGET: ", table.concat(target_raw:toTable(), " ")) -- Compute the loss local mae = ann.loss.mae():compute_loss(out_raw:contiguous(), target_raw:contiguous()) local mse = ann.loss.mse():compute_loss(out_raw:contiguous(), target_raw:contiguous()) printf("ERRORS: \t MAE= %.4f MSE= %.4f RMSE= %.4f\n", mae, mse, math.sqrt(mse/hsize)) -- Finally, train using the pair of tokens trainer:train_step( input:contiguous(), target:contiguous() ) end if pos >= MAX_WSIZE then -- It is ready to produce a forward local input = compute_input(pos, hour) local out = trainer:calculate( input:contiguous() ) out = reconstruct_output(pos,out) print("FORECAST: ", table.concat(out:toTable(), " ")) update_buffer(outputs,out:toTable()) end end end if best then trainer:save(best) end
mit
kitala1/darkstar
scripts/globals/items/cup_of_chamomile_tea.lua
35
1384
----------------------------------------- -- ID: 4603 -- Item: cup_of_chamomile_tea -- Food Effect: 180Min, All Races ----------------------------------------- -- Magic 8 -- Vitality -2 -- Charisma 2 -- Magic Regen While Healing 1 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,10800,4603); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 8); target:addMod(MOD_VIT, -2); target:addMod(MOD_CHR, 2); target:addMod(MOD_MPHEAL, 1); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 8); target:delMod(MOD_VIT, -2); target:delMod(MOD_CHR, 2); target:delMod(MOD_MPHEAL, 1); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Sealions_Den/mobs/Tenzen.lua
27
1077
----------------------------------- -- Area: Sealion den -- NPC: Tenzen ----------------------------------- ----------------------------------- -- onMobSpawn ----------------------------------- function onMobSpawn(mob) end; ----------------------------------- -- onMobEngaged ----------------------------------- function onMobEngaged(mob,target) switch (mob:getID()) : caseof { [16908310] = function (x) GetMobByID(16908311):updateEnmity(target); GetMobByID(16908312):updateEnmity(target); GetMobByID(16908313):updateEnmity(target); end, [16908314] = function (x) GetMobByID(16908315):updateEnmity(target); GetMobByID(16908316):updateEnmity(target); GetMobByID(16908317):updateEnmity(target); end, [16908318] = function (x) GetMobByID(16908319):updateEnmity(target); GetMobByID(16908320):updateEnmity(target); GetMobByID(16908321):updateEnmity(target); end, } end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) end;
gpl-3.0
crabman77/minetest-minetestforfun-server
mods/maptools/aliases.lua
11
5597
--[[ Map Tools: alias definitions Copyright (c) 2012-2015 Calinou and contributors. Licensed under the zlib license. See LICENSE.md for more information. --]] minetest.register_alias("adminpick", "maptools:pick_admin") minetest.register_alias("adminpickaxe", "maptools:pick_admin") minetest.register_alias("admin_pick", "maptools:pick_admin") minetest.register_alias("admin_pickaxe", "maptools:pick_admin") minetest.register_alias("pick_admin", "maptools:pick_admin") minetest.register_alias("pickaxe_admin", "maptools:pick_admin") minetest.register_alias("pickadmin", "maptools:pick_admin") minetest.register_alias("pickaxeadmin", "maptools:pick_admin") minetest.register_alias("adminpickdrops", "maptools:pick_admin_with_drops") minetest.register_alias("adminpickaxedrops", "maptools:pick_admin_with_drops") minetest.register_alias("admin_pick_drops", "maptools:pick_admin_with_drops") minetest.register_alias("admin_pickaxe_drops", "maptools:pick_admin_with_drops") minetest.register_alias("pick_admin_drops", "maptools:pick_admin_with_drops") minetest.register_alias("pickaxe_admin_drops", "maptools:pick_admin_with_drops") minetest.register_alias("pickadmindrops", "maptools:pick_admin_with_drops") minetest.register_alias("pickaxeadmindrops", "maptools:pick_admin_with_drops") minetest.register_alias("infinitefuel", "maptools:infinitefuel") minetest.register_alias("infinite_fuel", "maptools:infinitefuel") minetest.register_alias("ifuel", "maptools:infinitefuel") minetest.register_alias("superapple", "maptools:superapple") minetest.register_alias("super_apple", "maptools:superapple") minetest.register_alias("sapple", "maptools:superapple") minetest.register_alias("nobuild", "maptools:nobuild") minetest.register_alias("nointeract", "maptools:nointeract") minetest.register_alias("damage_1", "maptools:damage_1") minetest.register_alias("damage_2", "maptools:damage_2") minetest.register_alias("damage_3", "maptools:damage_3") minetest.register_alias("damage_4", "maptools:damage_4") minetest.register_alias("damage_5", "maptools:damage_5") minetest.register_alias("pusher_1", "maptools:pusher_1") minetest.register_alias("pusher_2", "maptools:pusher_2") minetest.register_alias("pusher_3", "maptools:pusher_3") minetest.register_alias("pusher_4", "maptools:pusher_4") minetest.register_alias("pusher_5", "maptools:pusher_5") minetest.register_alias("pusher_6", "maptools:pusher_6") minetest.register_alias("pusher_7", "maptools:pusher_7") minetest.register_alias("pusher_8", "maptools:pusher_8") minetest.register_alias("pusher_9", "maptools:pusher_9") minetest.register_alias("pusher_10", "maptools:pusher_10") minetest.register_alias("killblock", "maptools:kill") minetest.register_alias("kill_block", "maptools:kill") minetest.register_alias("lightblock", "maptools:lightblock") minetest.register_alias("light_block", "maptools:lightblock") minetest.register_alias("lightbulb", "maptools:lightbulb") minetest.register_alias("light_bulb", "maptools:lightbulb") minetest.register_alias("playerclip", "maptools:playerclip") minetest.register_alias("player_clip", "maptools:playerclip") minetest.register_alias("pclip", "maptools:playerclip") minetest.register_alias("fullclip", "maptools:fullclip") minetest.register_alias("full_clip", "maptools:fullclip") minetest.register_alias("fclip", "maptools:fullclip") minetest.register_alias("full_clip", "maptools:fullclip") minetest.register_alias("full_clip_face", "maptools:fullclip_face") minetest.register_alias("fullclip_face", "maptools:fullclip_face") minetest.register_alias("fullclipface", "maptools:fullclip_face") minetest.register_alias("player_clip_bottom", "maptools:playerclip_bottom") minetest.register_alias("playerclip_bottom", "maptools:playerclip_bottom") minetest.register_alias("playerclipbottom", "maptools:playerclip_bottom") minetest.register_alias("player_clip_top", "maptools:playerclip_top") minetest.register_alias("playerclip_top", "maptools:playerclip_top") minetest.register_alias("playercliptop", "maptools:playerclip_top") minetest.register_alias("permanentfire", "maptools:permanent_fire") minetest.register_alias("permanent_fire", "maptools:permanent_fire") minetest.register_alias("pfire", "maptools:permanent_fire") minetest.register_alias("fakefire", "maptools:fake_fire") minetest.register_alias("fake_fire", "maptools:fake_fire") minetest.register_alias("ffire", "maptools:fake_fire") minetest.register_alias("igniter", "maptools:igniter") minetest.register_alias("stone_u", "maptools:stone") minetest.register_alias("tree_u", "maptools:tree") minetest.register_alias("cobble_u", "maptools:cobble") minetest.register_alias("wood_u", "maptools:wood") minetest.register_alias("sand_u", "maptools:sand") minetest.register_alias("gravel_u", "maptools:gravel") minetest.register_alias("brick_u", "maptools:brick") minetest.register_alias("dirt_u", "maptools:dirt") minetest.register_alias("glass_u", "maptools:glass") minetest.register_alias("sandstone_u", "maptools:sandstone") minetest.register_alias("desert_stone_u", "maptools:desert_stone") minetest.register_alias("desertstone_u", "maptools:desert_stone") minetest.register_alias("desert_sand_u", "maptools:desert_sand") minetest.register_alias("desertsand_u", "maptools:desert_sand") minetest.register_alias("leaves_u", "maptools:leaves") minetest.register_alias("grass_u", "maptools:grass") minetest.register_alias("fullgrass", "maptools:fullgrass") minetest.register_alias("fullgrass_u", "maptools:fullgrass") minetest.register_alias("mossycobble_u", "maptools:mossycobble") minetest.register_alias("mossy_cobble_u", "maptools:mossycobble")
unlicense
zhaoluxyz/Hugula
Client/Assets/Lua/components/cooldownLabel.lua
5
2214
------------------------------------------------ -- Copyright © 2013-2014 Hugula: Arpg game Engine -- -- author pu ------------------------------------------------ local LuaHelper=LuaHelper local CUtils=CUtils local delay = delay -- local Timer = luanet.Timer local fun = fun local CooldownLabel=class(function(self,luaObj) self.items={} self.luaObj=luaObj self.assets = nil self.enable = true end) function CooldownLabel:cutdown(time) local str = "00:00" local ts = 0 if self.beginTime then if self.type == nil then ts = time-self.beginTime else ts = self.along_time - time end if ts > 0 then local sec = string.format("%02.0f", ts % 60) local hour = string.format("%02.0f", math.modf(ts / 3600)) local min = string.format("%02.0f", math.modf((ts - hour * 3600) / 60)) if self.len == nil then str = min .. ":" .. sec else str = hour .. ":" .. min .. ":" .. sec end end end if self.label then self.label.text=str end end function CooldownLabel:call() local time = os.time() self:cutdown(time) if time>=self.along_time then self.enable = false if self.onCooldownFn then self:onCooldownFn() end elseif(self.enable==true) then delay(self.call,1,self) end end --暂停 function CooldownLabel:pause() self.pause_time = os.time() --记录暂停时间 self.enable = false end --继续 function CooldownLabel:continue() self.enable = true local dt = os.time() - self.pause_time self.beginTime=self.beginTime+dt self.along_time = self.along_time+dt self:call() -- delay(self.call,1,self) end ---------------------------------------------------------------------------------------------------- --功能:开启计时器 --参数:@total:单位秒,总计时时间 -- @type:计时类型(nil:计数器计时,notnil:倒计时) --返回: ---------------------------------------------------------------------------------------------------- function CooldownLabel:begin(total,type,len) self.type = type self.len = len self.beginTime = os.time() self.along_time = self.beginTime+total self.enable = true self:call() -- delay(self.call,1,self) end return CooldownLabel
mit
omideblisss/omid
libs/dkjson.lua
3282
26558
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.4* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.4"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.4" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
crabman77/minetest-minetestforfun-server
mods/invtweak/init.lua
6
7167
local auto_refill = minetest.setting_getbool("invtweak_auto_refill") or true local tweak = {} tweak.formspec = {} tweak.buttons = { --sort_asc "0.8,0.6;sort_asc;^]".."tooltip[sort_asc;sort Items asc.;#30434C;#FFF]", --sort_desc "0.8,0.6;sort_desc;v]".."tooltip[sort_desc;sort Items desc.;#30434C;#FFF]", --concatenate "0.8,0.6;sort;·»]".."tooltip[sort;stack Items and sort asc.;#30434C;#FFF]" } local function get_formspec_size(formspec) local w = 8 local h = 7.5 if not formspec then return end local sstring = string.find(formspec,"size[",1,true) if sstring ~= nil then sstring = string.sub(formspec, sstring+5) local p = string.find(sstring,",") w = string.sub(sstring,1,p-1) sstring = string.sub(sstring,p+1,string.find(sstring,"]")+2) p = string.find(sstring,",") if p == nil then p = string.find(sstring,"]") end h = string.sub(sstring,1,p-1) end return w,h end local function add_buttons(player, formspec) local name = player:get_player_name() if not formspec then formspec = player:get_inventory_formspec() end local w,h = get_formspec_size(formspec) if not w or not h then return end for i=1,#tweak.buttons do formspec = formspec .. "button["..w-(0.8+(i*0.8))..",0.2;" .. tweak.buttons[i] end player:set_inventory_formspec(formspec) return formspec end local armor_mod = minetest.get_modpath("3d_armor") local ui_mod = minetest.get_modpath("unified_inventory") -- override mods formspec function if ui_mod then local org = unified_inventory.get_formspec unified_inventory.get_formspec = function(player, page) local formspec = org(player, page) return add_buttons(player, formspec) end end if armor_mod and not ui_mod then local org = armor.get_armor_formspec armor.get_armor_formspec = function(self, name) local formspec = org(self, name) return add_buttons(minetest.get_player_by_name(name), formspec) end end minetest.register_on_joinplayer(function(player) local formspec = nil if armor_mod and not ui_mod then formspec = armor.get_armor_formspec(self, player:get_player_name()) end minetest.after(0.65,function() add_buttons(player, formspec) end) end) local function comp_asc(w1,w2) if w1.name < w2.name then return true end end local function comp_desc(w1,w2) if w1.name > w2.name then return true end end minetest.register_on_player_receive_fields(function(player, formname, fields) if fields.sort_asc then tweak.sort(player, comp_asc) end if fields.sort_desc then tweak.sort(player, comp_desc) end if fields.sort then tweak.sort(player, comp_asc, true) end -- player inventory if minetest.setting_getbool("creative_mode") then add_buttons(player) end end) -- sort asc without mod prefix local function comp_in(w1, w2) local w11 = string.find(w1.name, ":") local w22 = string.find(w2.name, ":") if w11 ~= nil then w11 = string.sub(w1.name,w11) else w11 = w1.name end if w22 ~= nil then w22 = string.sub(w2.name,w22) else w22 = w2.name end if w11 < w22 then return true end end tweak.concatenate = function(list) local last = nil local last_cnt = 100 local refresh = false for _,stack in ipairs(list) do local i = _ if refresh then refresh = false table.sort(list, comp_asc) list = tweak.concatenate(list) break end if stack.name ~= "zztmpsortname" and last == stack.name then if last_cnt < stack.max then local diff = stack.max - last_cnt local add = stack.count if stack.count > diff then stack.count = stack.count - diff add = diff else stack.name = "zztmpsortname" refresh = true end list[i-1].count = list[i-1].count + add end end last = stack.name last_cnt = stack.count end return list end tweak.sort = function(player, mode, con) local inv = player:get_inventory() if inv then local list = inv:get_list("main") local tmp_list = {} --write whole list as table for _,stack in ipairs(list) do local tbl_stack = stack:to_table() if tbl_stack == nil then tbl_stack = {name="zztmpsortname"} end tbl_stack.max = stack:get_stack_max() tmp_list[_]=tbl_stack end -- sort asc/desc table.sort(tmp_list, mode) if con then tmp_list = tweak.concatenate(tmp_list) table.sort(tmp_list, mode) end --write back to inventory for _,stack in ipairs(tmp_list) do stack.max = nil if stack.name ~= "zztmpsortname" then inv:set_stack("main", _, ItemStack(stack)) else inv:set_stack("main", _, ItemStack(nil)) end end end end -- tool break sound + autorefill function refill(player, stck_name, index) local inv = player:get_inventory() local old_stack = inv:get_stack("main", index) if old_stack:get_name() == stck_name then return end if inv:get_list("main") then for i,stack in ipairs(inv:get_list("main")) do if i ~= index and stack:get_name() == stck_name then inv:set_stack("main", index, stack) stack:clear() inv:set_stack("main", i, stack) minetest.log("action", "Inventory Tweaks: refilled stack("..stck_name..") of " .. player:get_player_name() ) return end end end end if auto_refill == true then minetest.register_on_placenode(function(pos, newnode, placer, oldnode) if not placer then return end local index = placer:get_wield_index() local cnt = placer:get_wielded_item():get_count()-1 if minetest.setting_getbool("creative_mode") then return else if cnt == 0 then minetest.after(0.01, refill, placer, newnode.name, index) end end end) end local wielded = {} wielded["name"] = {} wielded["wear"] = {} wielded["index"] = {} minetest.register_on_punchnode(function(pos, node, puncher) if not puncher or minetest.setting_getbool("creative_mode") then return end local name = puncher:get_player_name() if not name then return end local item = puncher:get_wielded_item() if not item then return end local index = puncher:get_wield_index() local tname = item:get_name() local def = minetest.registered_tools[tname] if not tname or tname == "" or not def then -- if empty or not tools wielded["name"][name] = "" return end wielded["name"][name] = tname wielded["index"][name] = index local typ = def.type if not typ or typ ~= "tool" then --if tools, true wielded["wear"][name] = false else wielded["wear"][name] = true end end) minetest.register_on_dignode(function(pos, oldnode, digger) if not digger then return end local name = digger:get_player_name() if not name then return end local item = digger:get_wielded_item() if not item then return end local index = digger:get_wield_index() local tname = item:get_name() if tname ~= "" then return end --new not empty, return local old_name = wielded["name"][name] if old_name == nil or old_name == "" then return end -- old empty, not replace local old_wear = wielded["wear"][name] local old_index = wielded["index"][name] if index == old_index and old_wear == true then -- if identical index and old is tools, replace minetest.sound_play("invtweak_tool_break", {pos = digger:getpos(), gain = 0.9, max_hear_distance = 5}) if auto_refill == true then minetest.after(0.01, refill, digger, old_name, index) end end end)
unlicense
JavidTeam/TeleJavid
plugins/groupmanager.lua
1
144627
local function modadd(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then if not lang then return '_You are not bot admin_' else return 'شما مدیر ربات نمیباشید' end end local data = load_data(_config.moderation.data) if data[tostring(msg.to.id)] then if not lang then return '_Group is already added_' else return 'گروه در لیست گروه های مدیریتی ربات هم اکنون موجود است' end end -- create data array in moderation.json data[tostring(msg.to.id)] = { owners = {}, mods ={}, banned ={}, is_silent_users ={}, filterlist ={}, whitelist ={}, settings = { set_name = msg.to.title, lock_link = 'yes', lock_tag = 'yes', lock_spam = 'yes', lock_webpage = 'no', lock_markdown = 'no', flood = 'yes', lock_bots = 'yes', lock_pin = 'no', welcome = 'no', lock_join = 'no', lock_edit = 'no', lock_arabic = 'no', lock_mention = 'no', lock_all = 'no', num_msg_max = '5', set_char = '40', time_check = '2', }, mutes = { mute_forward = 'no', mute_audio = 'no', mute_video = 'no', mute_contact = 'no', mute_text = 'no', mute_photo = 'no', mute_gif = 'no', mute_location = 'no', mute_document = 'no', mute_sticker = 'no', mute_voice = 'no', mute_all = 'no', mute_keyboard = 'no', mute_game = 'no', mute_inline = 'no', mute_tgservice = 'no', } } 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) if not lang then return '*Group has been added*'..msg_caption else return 'گروه با موفقیت به لیست گروه های مدیریتی ربات افزوده شد'..msg_caption end end local function modrem(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) -- superuser and admins only (because sudo are always has privilege) if not is_admin(msg) then if not lang then return '_You are not bot admin_' else return 'شما مدیر ربات نمیباشید' end end local data = load_data(_config.moderation.data) local receiver = msg.to.id if not data[tostring(msg.to.id)] then if not lang then return '_Group is not added_' else return 'گروه به لیست گروه های مدیریتی ربات اضافه نشده است' end end 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) if not lang then return '*Group has been removed*' else return 'گروه با موفیت از لیست گروه های مدیریتی ربات حذف شد' end end local function filter_word(msg, word) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)]['filterlist'] then data[tostring(msg.to.id)]['filterlist'] = {} save_data(_config.moderation.data, data) end if data[tostring(msg.to.id)]['filterlist'][(word)] then if not lang then return "_Word_ *"..word.."* _is already filtered_" else return "_کلمه_ *"..word.."* _از قبل فیلتر بود_" end end data[tostring(msg.to.id)]['filterlist'][(word)] = true save_data(_config.moderation.data, data) if not lang then return "_Word_ *"..word.."* _added to filtered words list_" else return "_کلمه_ *"..word.."* _به لیست کلمات فیلتر شده اضافه شد_" end end local function unfilter_word(msg, word) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) if not data[tostring(msg.to.id)]['filterlist'] then data[tostring(msg.to.id)]['filterlist'] = {} save_data(_config.moderation.data, data) end if data[tostring(msg.to.id)]['filterlist'][word] then data[tostring(msg.to.id)]['filterlist'][(word)] = nil save_data(_config.moderation.data, data) if not lang then return "_Word_ *"..word.."* _removed from filtered words list_" elseif lang then return "_کلمه_ *"..word.."* _از لیست کلمات فیلتر شده حذف شد_" end else if not lang then return "_Word_ *"..word.."* _is not filtered_" elseif lang then return "_کلمه_ *"..word.."* _از قبل فیلتر نبود_" end end end local function modlist(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data[tostring(msg.chat_id_)] then if not lang then return "_Group is not added_" else return "گروه به لیست گروه های مدیریتی ربات اضافه نشده است" end end -- determine if table is empty if next(data[tostring(msg.to.id)]['mods']) == nil then --fix way if not lang then return "_No_ *moderator* _in this group_" else return "در حال حاضر هیچ مدیری برای گروه انتخاب نشده است" end end if not lang then message = '*List of moderators :*\n' else message = '*لیست مدیران گروه :*\n' end for k,v in pairs(data[tostring(msg.to.id)]['mods']) do message = message ..i.. '- '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function ownerlist(msg) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local data = load_data(_config.moderation.data) local i = 1 if not data[tostring(msg.to.id)] then if not lang then return "_Group is not added_"..msg_caption else return "گروه به لیست گروه های مدیریتی ربات اضافه نشده است" end end -- determine if table is empty if next(data[tostring(msg.to.id)]['owners']) == nil then --fix way if not lang then return "_No_ *owner* _in this group_" else return "در حال حاضر هیچ مالکی برای گروه انتخاب نشده است" end end if not lang then message = '*List of moderators :*\n' else message = '*لیست مالکین گروه :*\n' end for k,v in pairs(data[tostring(msg.to.id)]['owners']) do message = message ..i.. '- '..v..' [' ..k.. '] \n' i = i + 1 end return message end local function action_by_reply(arg, data) local hash = "gp_lang:"..data.chat_id_ local lang = redis:get(hash) local cmd = arg.cmd local administration = load_data(_config.moderation.data) if not tonumber(data.sender_user_id_) then return false end if data.sender_user_id_ then if not administration[tostring(data.chat_id_)] then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md") end end if cmd == "setwhitelist" then local function setwhitelist_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید بود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been added to_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به لیست سفید اضافه شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, setwhitelist_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "remwhitelist" then local function remwhitelist_cb(arg, data) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if not administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been removed from_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از لیست سفید حذف شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, remwhitelist_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "setowner" then local function owner_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "promote" then local function promote_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, promote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "remowner" then local function rem_owner_cb(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, rem_owner_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "demote" then local function demote_cb(arg, data) local administration = load_data(_config.moderation.data) if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md") end end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, demote_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end if cmd == "id" then local function id_cb(arg, data) return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md") end tdcli_function ({ ID = "GetUser", user_id_ = data.sender_user_id_ }, id_cb, {chat_id=data.chat_id_,user_id=data.sender_user_id_}) end else if lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_username(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd local administration = load_data(_config.moderation.data) if not administration[tostring(arg.chat_id)] then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md") end end if not arg.username then return false end if data.id_ then if data.type_.user_.username_ then user_name = '@'..check_markdown(data.type_.user_.username_) else user_name = check_markdown(data.title_) end if cmd == "setwhitelist" then if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید بود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been added to_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به لیست سفید اضافه شد*", 0, "md") end end if cmd == "remwhitelist" then if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if not administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been removed from_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از لیست سفید حذف شد*", 0, "md") end end if cmd == "setowner" then if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md") end end if cmd == "promote" then if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md") end end if cmd == "remowner" then if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md") end end if cmd == "demote" then if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md") end end if cmd == "id" then return tdcli.sendMessage(arg.chat_id, "", 0, "*"..data.id_.."*", 0, "md") end if cmd == "res" then if not lang then text = "Result for [ "..check_markdown(data.type_.user_.username_).." ] :\n" .. ""..check_markdown(data.title_).."\n" .. " ["..data.id_.."]" else text = "اطلاعات برای [ "..check_markdown(data.type_.user_.username_).." ] :\n" .. "".. check_markdown(data.title_) .."\n" .. " [".. data.id_ .."]" end return tdcli.sendMessage(arg.chat_id, 0, 1, text, 1, 'md') end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end local function action_by_id(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) local cmd = arg.cmd local administration = load_data(_config.moderation.data) if not administration[tostring(arg.chat_id)] then if not lang then return tdcli.sendMessage(data.chat_id_, "", 0, "_Group is not added_", 0, "md") else return tdcli.sendMessage(data.chat_id_, "", 0, "_گروه به لیست گروه های مدیریتی ربات اضافه نشده است_", 0, "md") end end if not tonumber(arg.user_id) then return false end if data.id_ then if data.first_name_ then if data.username_ then user_name = '@'..check_markdown(data.username_) else user_name = check_markdown(data.first_name_) end if cmd == "setwhitelist" then if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید بود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been added to_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به لیست سفید اضافه شد*", 0, "md") end end if cmd == "remwhitelist" then if not administration[tostring(arg.chat_id)]['whitelist'] then administration[tostring(arg.chat_id)]['whitelist'] = {} save_data(_config.moderation.data, administration) end if not administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not in_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل در لیست سفید نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['whitelist'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been removed from_ *white list*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از لیست سفید حذف شد*", 0, "md") end end if cmd == "setowner" then if administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is now the_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام صاحب گروه منتصب شد*", 0, "md") end end if cmd == "promote" then if administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is already a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه بود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = user_name save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *promoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *به مقام مدیر گروه منتصب شد*", 0, "md") end end if cmd == "remowner" then if not administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* *از قبل صاحب گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['owners'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is no longer a_ *group owner*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام صاحب گروه برکنار شد*", 0, "md") end end if cmd == "demote" then if not administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] then if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _is not a_ *moderator*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از قبل مدیر گروه نبود*", 0, "md") end end administration[tostring(arg.chat_id)]['mods'][tostring(data.id_)] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User_ "..user_name.." *"..data.id_.."* _has been_ *demoted*", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر_ "..user_name.." *"..data.id_.."* *از مقام مدیر گروه برکنار شد*", 0, "md") end end if cmd == "whois" then if data.username_ then username = '@'..check_markdown(data.username_) else if not lang then username = 'not found' else username = 'ندارد' end end if not lang then return tdcli.sendMessage(arg.chat_id, 0, 1, 'Info for [ '..data.id_..' ] :\nUserName : '..username..'\nName : '..data.first_name_, 1) else return tdcli.sendMessage(arg.chat_id, 0, 1, 'اطلاعات برای [ '..data.id_..' ] :\nیوزرنیم : '..username..'\nنام : '..data.first_name_, 1) end end else if not lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_User not founded_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") end end else if lang then return tdcli.sendMessage(arg.chat_id, "", 0, "_کاربر یافت نشد_", 0, "md") else return tdcli.sendMessage(arg.chat_id, "", 0, "*User Not Found*", 0, "md") end end end ---------------Lock Link------------------- local function lock_link(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_link = data[tostring(target)]["settings"]["lock_link"] if lock_link == "yes" then if not lang then return "*Link* _Posting Is Already Locked_" elseif lang then return "ارسال لینک در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_link"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Link* _Posting Has Been Locked_" else return "ارسال لینک در گروه ممنوع شد" end end end local function unlock_link(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_link = data[tostring(target)]["settings"]["lock_link"] if lock_link == "no" then if not lang then return "*Link* _Posting Is Not Locked_" elseif lang then return "ارسال لینک در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_link"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Link* _Posting Has Been Unlocked_" else return "ارسال لینک در گروه آزاد شد" end end end ---------------Lock Tag------------------- local function lock_tag(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_tag = data[tostring(target)]["settings"]["lock_tag"] if lock_tag == "yes" then if not lang then return "*Tag* _Posting Is Already Locked_" elseif lang then return "ارسال تگ در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_tag"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Tag* _Posting Has Been Locked_" else return "ارسال تگ در گروه ممنوع شد" end end end local function unlock_tag(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_tag = data[tostring(target)]["settings"]["lock_tag"] if lock_tag == "no" then if not lang then return "*Tag* _Posting Is Not Locked_" elseif lang then return "ارسال تگ در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_tag"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Tag* _Posting Has Been Unlocked_" else return "ارسال تگ در گروه آزاد شد" end end end ---------------Lock Mention------------------- local function lock_mention(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_mention = data[tostring(target)]["settings"]["lock_mention"] if lock_mention == "yes" then if not lang then return "*Mention* _Posting Is Already Locked_" elseif lang then return "ارسال فراخوانی افراد هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_mention"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mention* _Posting Has Been Locked_" else return "ارسال فراخوانی افراد در گروه ممنوع شد" end end end local function unlock_mention(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_mention = data[tostring(target)]["settings"]["lock_mention"] if lock_mention == "no" then if not lang then return "*Mention* _Posting Is Not Locked_" elseif lang then return "ارسال فراخوانی افراد در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_mention"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mention* _Posting Has Been Unlocked_" else return "ارسال فراخوانی افراد در گروه آزاد شد" end end end ---------------Lock Arabic-------------- local function lock_arabic(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"] if lock_arabic == "yes" then if not lang then return "*Arabic/Persian* _Posting Is Already Locked_" elseif lang then return "ارسال کلمات عربی/فارسی در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_arabic"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Arabic/Persian* _Posting Has Been Locked_" else return "ارسال کلمات عربی/فارسی در گروه ممنوع شد" end end end local function unlock_arabic(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_arabic = data[tostring(target)]["settings"]["lock_arabic"] if lock_arabic == "no" then if not lang then return "*Arabic/Persian* _Posting Is Not Locked_" elseif lang then return "ارسال کلمات عربی/فارسی در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_arabic"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Arabic/Persian* _Posting Has Been Unlocked_" else return "ارسال کلمات عربی/فارسی در گروه آزاد شد" end end end ---------------Lock Edit------------------- local function lock_edit(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_edit = data[tostring(target)]["settings"]["lock_edit"] if lock_edit == "yes" then if not lang then return "*Editing* _Is Already Locked_" elseif lang then return "ویرایش پیام هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_edit"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Editing* _Has Been Locked_" else return "ویرایش پیام در گروه ممنوع شد" end end end local function unlock_edit(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_edit = data[tostring(target)]["settings"]["lock_edit"] if lock_edit == "no" then if not lang then return "*Editing* _Is Not Locked_" elseif lang then return "ویرایش پیام در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_edit"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Editing* _Has Been Unlocked_" else return "ویرایش پیام در گروه آزاد شد" end end end ---------------Lock spam------------------- local function lock_spam(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_spam = data[tostring(target)]["settings"]["lock_spam"] if lock_spam == "yes" then if not lang then return "*Spam* _Is Already Locked_" elseif lang then return "ارسال هرزنامه در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_spam"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Spam* _Has Been Locked_" else return "ارسال هرزنامه در گروه ممنوع شد" end end end local function unlock_spam(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_spam = data[tostring(target)]["settings"]["lock_spam"] if lock_spam == "no" then if not lang then return "*Spam* _Posting Is Not Locked_" elseif lang then return "ارسال هرزنامه در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_spam"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Spam* _Posting Has Been Unlocked_" else return "ارسال هرزنامه در گروه آزاد شد" end end end ---------------Lock Flood------------------- local function lock_flood(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_flood = data[tostring(target)]["settings"]["flood"] if lock_flood == "yes" then if not lang then return "*Flooding* _Is Already Locked_" elseif lang then return "ارسال پیام مکرر در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["flood"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Flooding* _Has Been Locked_" else return "ارسال پیام مکرر در گروه ممنوع شد" end end end local function unlock_flood(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_flood = data[tostring(target)]["settings"]["flood"] if lock_flood == "no" then if not lang then return "*Flooding* _Is Not Locked_" elseif lang then return "ارسال پیام مکرر در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["flood"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Flooding* _Has Been Unlocked_" else return "ارسال پیام مکرر در گروه آزاد شد" end end end ---------------Lock Bots------------------- local function lock_bots(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_bots = data[tostring(target)]["settings"]["lock_bots"] if lock_bots == "yes" then if not lang then return "*Bots* _Protection Is Already Enabled_" elseif lang then return "محافظت از گروه در برابر ربات ها هم اکنون فعال است" end else data[tostring(target)]["settings"]["lock_bots"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Bots* _Protection Has Been Enabled_" else return "محافظت از گروه در برابر ربات ها فعال شد" end end end local function unlock_bots(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_bots = data[tostring(target)]["settings"]["lock_bots"] if lock_bots == "no" then if not lang then return "*Bots* _Protection Is Not Enabled_" elseif lang then return "محافظت از گروه در برابر ربات ها غیر فعال است" end else data[tostring(target)]["settings"]["lock_bots"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Bots* _Protection Has Been Disabled_" else return "محافظت از گروه در برابر ربات ها غیر فعال شد" end end end ---------------Lock Join------------------- local function lock_join(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_join = data[tostring(target)]["settings"]["lock_join"] if lock_join == "yes" then if not lang then return "*Lock Join* _Is Already Locked_" elseif lang then return "ورود به گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_join"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Lock Join* _Has Been Locked_" else return "ورود به گروه ممنوع شد" end end end local function unlock_join(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_join = data[tostring(target)]["settings"]["lock_join"] if lock_join == "no" then if not lang then return "*Lock Join* _Is Not Locked_" elseif lang then return "ورود به گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_join"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Lock Join* _Has Been Unlocked_" else return "ورود به گروه آزاد شد" end end end ---------------Lock Markdown------------------- local function lock_markdown(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"] if lock_markdown == "yes" then if not lang then return "*Markdown* _Posting Is Already Locked_" elseif lang then return "ارسال پیام های دارای فونت در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_markdown"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Markdown* _Posting Has Been Locked_" else return "ارسال پیام های دارای فونت در گروه ممنوع شد" end end end local function unlock_markdown(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_markdown = data[tostring(target)]["settings"]["lock_markdown"] if lock_markdown == "no" then if not lang then return "*Markdown* _Posting Is Not Locked_" elseif lang then return "ارسال پیام های دارای فونت در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_markdown"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Markdown* _Posting Has Been Unlocked_" else return "ارسال پیام های دارای فونت در گروه آزاد شد" end end end ---------------Lock Webpage------------------- local function lock_webpage(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"] if lock_webpage == "yes" then if not lang then return "*Webpage* _Is Already Locked_" elseif lang then return "ارسال صفحات وب در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_webpage"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Webpage* _Has Been Locked_" else return "ارسال صفحات وب در گروه ممنوع شد" end end end local function unlock_webpage(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_webpage = data[tostring(target)]["settings"]["lock_webpage"] if lock_webpage == "no" then if not lang then return "*Webpage* _Is Not Locked_" elseif lang then return "ارسال صفحات وب در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_webpage"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Webpage* _Has Been Unlocked_" else return "ارسال صفحات وب در گروه آزاد شد" end end end ---------------Lock Pin------------------- local function lock_pin(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_pin = data[tostring(target)]["settings"]["lock_pin"] if lock_pin == "yes" then if not lang then return "*Pinned Message* _Is Already Locked_" elseif lang then return "سنجاق کردن پیام در گروه هم اکنون ممنوع است" end else data[tostring(target)]["settings"]["lock_pin"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Pinned Message* _Has Been Locked_" else return "سنجاق کردن پیام در گروه ممنوع شد" end end end local function unlock_pin(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local lock_pin = data[tostring(target)]["settings"]["lock_pin"] if lock_pin == "no" then if not lang then return "*Pinned Message* _Is Not Locked_" elseif lang then return "سنجاق کردن پیام در گروه ممنوع نمیباشد" end else data[tostring(target)]["settings"]["lock_pin"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Pinned Message* _Has Been Unlocked_" else return "سنجاق کردن پیام در گروه آزاد شد" end end end function group_settings(msg, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local data = load_data(_config.moderation.data) local target = msg.to.id if data[tostring(target)] then if data[tostring(target)]["settings"]["num_msg_max"] then NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['num_msg_max']) print('custom'..NUM_MSG_MAX) else NUM_MSG_MAX = 5 end if data[tostring(target)]["settings"]["set_char"] then SETCHAR = tonumber(data[tostring(target)]['settings']['set_char']) print('custom'..SETCHAR) else SETCHAR = 40 end if data[tostring(target)]["settings"]["time_check"] then TIME_CHECK = tonumber(data[tostring(target)]['settings']['time_check']) print('custom'..TIME_CHECK) else TIME_CHECK = 2 end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_link"] then data[tostring(target)]["settings"]["lock_link"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_tag"] then data[tostring(target)]["settings"]["lock_tag"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_mention"] then data[tostring(target)]["settings"]["lock_mention"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_arabic"] then data[tostring(target)]["settings"]["lock_arabic"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_edit"] then data[tostring(target)]["settings"]["lock_edit"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_spam"] then data[tostring(target)]["settings"]["lock_spam"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_flood"] then data[tostring(target)]["settings"]["lock_flood"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_bots"] then data[tostring(target)]["settings"]["lock_bots"] = "yes" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_markdown"] then data[tostring(target)]["settings"]["lock_markdown"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_webpage"] then data[tostring(target)]["settings"]["lock_webpage"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["welcome"] then data[tostring(target)]["settings"]["welcome"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_pin"] then data[tostring(target)]["settings"]["lock_pin"] = "no" end end if data[tostring(target)]["settings"] then if not data[tostring(target)]["settings"]["lock_join"] then data[tostring(target)]["settings"]["lock_join"] = "no" end end local expire_date = '' local expi = redis:ttl('ExpireDate:'..msg.to.id) if expi == -1 then if lang then expire_date = 'نامحدود!' else expire_date = 'Unlimited!' end else local day = math.floor(expi / 86400) + 1 if lang then expire_date = day..' روز' else expire_date = day..' Days' end end if not lang then local settings = data[tostring(target)]["settings"] text = "*Group Settings:*\n_Lock edit :_ *"..settings.lock_edit.."*\n_Lock links :_ *"..settings.lock_link.."*\n_Lock tags :_ *"..settings.lock_tag.."*\n_Lock Join :_ *"..settings.lock_join.."*\n_Lock flood :_ *"..settings.flood.."*\n_Lock spam :_ *"..settings.lock_spam.."*\n_Lock mention :_ *"..settings.lock_mention.."*\n_Lock arabic :_ *"..settings.lock_arabic.."*\n_Lock webpage :_ *"..settings.lock_webpage.."*\n_Lock markdown :_ *"..settings.lock_markdown.."*\n_Group welcome :_ *"..settings.welcome.."*\n_Lock pin message :_ *"..settings.lock_pin.."*\n_Bots protection :_ *"..settings.lock_bots.."*\n_Flood sensitivity :_ *"..NUM_MSG_MAX.."*\n_Character sensitivity :_ *"..SETCHAR.."*\n_Flood check time :_ *"..TIME_CHECK.."*\n*____________________*\n_Expire Date :_ *"..expire_date.."*\n*Bot channel*: @TeleJavidBot\n*Group Language* : *EN*" else local settings = data[tostring(target)]["settings"] text = "*تنظیمات گروه:*\n_قفل ویرایش پیام :_ *"..settings.lock_edit.."*\n_قفل لینک :_ *"..settings.lock_link.."*\n_قفل ورود :_ *"..settings.lock_join.."*\n_قفل تگ :_ *"..settings.lock_tag.."*\n_قفل پیام مکرر :_ *"..settings.flood.."*\n_قفل هرزنامه :_ *"..settings.lock_spam.."*\n_قفل فراخوانی :_ *"..settings.lock_mention.."*\n_قفل عربی :_ *"..settings.lock_arabic.."*\n_قفل صفحات وب :_ *"..settings.lock_webpage.."*\n_قفل فونت :_ *"..settings.lock_markdown.."*\n_پیام خوشآمد گویی :_ *"..settings.welcome.."*\n_قفل سنجاق کردن :_ *"..settings.lock_pin.."*\n_محافظت در برابر ربات ها :_ *"..settings.lock_bots.."*\n_حداکثر پیام مکرر :_ *"..NUM_MSG_MAX.."*\n_حداکثر حروف مجاز :_ *"..SETCHAR.."*\n_زمان بررسی پیام های مکرر :_ *"..TIME_CHECK.."*\n*____________________*\n_تاریخ انقضا :_ *"..expire_date.."*\n*کانال ما*: @TeleJavidBot\n_زبان سوپرگروه_ : *FA*" end return text end --------Mutes--------- --------Mute all-------------------------- local function mute_all(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_all = data[tostring(target)]["mutes"]["mute_all"] if mute_all == "yes" then if not lang then return "*Mute All* _Is Already Enabled_" elseif lang then return "بیصدا کردن همه فعال است" end else data[tostring(target)]["mutes"]["mute_all"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute All* _Has Been Enabled_" else return "بیصدا کردن همه فعال شد" end end end local function unmute_all(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_all = data[tostring(target)]["mutes"]["mute_all"] if mute_all == "no" then if not lang then return "*Mute All* _Is Already Disabled_" elseif lang then return "بیصدا کردن همه غیر فعال است" end else data[tostring(target)]["mutes"]["mute_all"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute All* _Has Been Disabled_" else return "بیصدا کردن همه غیر فعال شد" end end end ---------------Mute Gif------------------- local function mute_gif(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_gif = data[tostring(target)]["mutes"]["mute_gif"] if mute_gif == "yes" then if not lang then return "*Mute Gif* _Is Already Enabled_" elseif lang then return "بیصدا کردن تصاویر متحرک فعال است" end else data[tostring(target)]["mutes"]["mute_gif"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Gif* _Has Been Enabled_" else return "بیصدا کردن تصاویر متحرک فعال شد" end end end local function unmute_gif(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_gif = data[tostring(target)]["mutes"]["mute_gif"] if mute_gif == "no" then if not lang then return "*Mute Gif* _Is Already Disabled_" elseif lang then return "بیصدا کردن تصاویر متحرک غیر فعال بود" end else data[tostring(target)]["mutes"]["mute_gif"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Gif* _Has Been Disabled_" else return "بیصدا کردن تصاویر متحرک غیر فعال شد" end end end ---------------Mute Game------------------- local function mute_game(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_game = data[tostring(target)]["mutes"]["mute_game"] if mute_game == "yes" then if not lang then return "*Mute Game* _Is Already Enabled_" elseif lang then return "بیصدا کردن بازی های تحت وب فعال است" end else data[tostring(target)]["mutes"]["mute_game"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Game* _Has Been Enabled_" else return "بیصدا کردن بازی های تحت وب فعال شد" end end end local function unmute_game(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_game = data[tostring(target)]["mutes"]["mute_game"] if mute_game == "no" then if not lang then return "*Mute Game* _Is Already Disabled_" elseif lang then return "بیصدا کردن بازی های تحت وب غیر فعال است" end else data[tostring(target)]["mutes"]["mute_game"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Game* _Has Been Disabled_" else return "بیصدا کردن بازی های تحت وب غیر فعال شد" end end end ---------------Mute Inline------------------- local function mute_inline(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_inline = data[tostring(target)]["mutes"]["mute_inline"] if mute_inline == "yes" then if not lang then return "*Mute Inline* _Is Already Enabled_" elseif lang then return "بیصدا کردن کیبورد شیشه ای فعال است" end else data[tostring(target)]["mutes"]["mute_inline"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Inline* _Has Been Enabled_" else return "بیصدا کردن کیبورد شیشه ای فعال شد" end end end local function unmute_inline(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_inline = data[tostring(target)]["mutes"]["mute_inline"] if mute_inline == "no" then if not lang then return "*Mute Inline* _Is Already Disabled_" elseif lang then return "بیصدا کردن کیبورد شیشه ای غیر فعال است" end else data[tostring(target)]["mutes"]["mute_inline"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Inline* _Has Been Disabled_" else return "بیصدا کردن کیبورد شیشه ای غیر فعال شد" end end end ---------------Mute Text------------------- local function mute_text(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_text = data[tostring(target)]["mutes"]["mute_text"] if mute_text == "yes" then if not lang then return "*Mute Text* _Is Already Enabled_" elseif lang then return "بیصدا کردن متن فعال است" end else data[tostring(target)]["mutes"]["mute_text"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Text* _Has Been Enabled_" else return "بیصدا کردن متن فعال شد" end end end local function unmute_text(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_text = data[tostring(target)]["mutes"]["mute_text"] if mute_text == "no" then if not lang then return "*Mute Text* _Is Already Disabled_" elseif lang then return "بیصدا کردن متن غیر فعال است" end else data[tostring(target)]["mutes"]["mute_text"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Text* _Has Been Disabled_" else return "بیصدا کردن متن غیر فعال شد" end end end ---------------Mute photo------------------- local function mute_photo(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_photo = data[tostring(target)]["mutes"]["mute_photo"] if mute_photo == "yes" then if not lang then return "*Mute Photo* _Is Already Enabled_" elseif lang then return "بیصدا کردن عکس فعال است" end else data[tostring(target)]["mutes"]["mute_photo"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Photo* _Has Been Enabled_" else return "بیصدا کردن عکس فعال شد" end end end local function unmute_photo(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_photo = data[tostring(target)]["mutes"]["mute_photo"] if mute_photo == "no" then if not lang then return "*Mute Photo* _Is Already Disabled_" elseif lang then return "بیصدا کردن عکس غیر فعال است" end else data[tostring(target)]["mutes"]["mute_photo"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Photo* _Has Been Disabled_" else return "بیصدا کردن عکس غیر فعال شد" end end end ---------------Mute Video------------------- local function mute_video(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_video = data[tostring(target)]["mutes"]["mute_video"] if mute_video == "yes" then if not lang then return "*Mute Video* _Is Already Enabled_" elseif lang then return "بیصدا کردن فیلم فعال است" end else data[tostring(target)]["mutes"]["mute_video"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Video* _Has Been Enabled_" else return "بیصدا کردن فیلم فعال شد" end end end local function unmute_video(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_video = data[tostring(target)]["mutes"]["mute_video"] if mute_video == "no" then if not lang then return "*Mute Video* _Is Already Disabled_" elseif lang then return "بیصدا کردن فیلم غیر فعال است" end else data[tostring(target)]["mutes"]["mute_video"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Video* _Has Been Disabled_" else return "بیصدا کردن فیلم غیر فعال شد" end end end ---------------Mute Audio------------------- local function mute_audio(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_audio = data[tostring(target)]["mutes"]["mute_audio"] if mute_audio == "yes" then if not lang then return "*Mute Audio* _Is Already Enabled_" elseif lang then return "بیصدا کردن آهنگ فعال است" end else data[tostring(target)]["mutes"]["mute_audio"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Audio* _Has Been Enabled_" else return "بیصدا کردن آهنگ فعال شد" end end end local function unmute_audio(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_audio = data[tostring(target)]["mutes"]["mute_audio"] if mute_audio == "no" then if not lang then return "*Mute Audio* _Is Already Disabled_" elseif lang then return "بیصدا کردن آهنک غیر فعال است" end else data[tostring(target)]["mutes"]["mute_audio"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Audio* _Has Been Disabled_" else return "بیصدا کردن آهنگ غیر فعال شد" end end end ---------------Mute Voice------------------- local function mute_voice(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_voice = data[tostring(target)]["mutes"]["mute_voice"] if mute_voice == "yes" then if not lang then return "*Mute Voice* _Is Already Enabled_" elseif lang then return "بیصدا کردن صدا فعال است" end else data[tostring(target)]["mutes"]["mute_voice"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Voice* _Has Been Enabled_" else return "بیصدا کردن صدا فعال شد" end end end local function unmute_voice(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_voice = data[tostring(target)]["mutes"]["mute_voice"] if mute_voice == "no" then if not lang then return "*Mute Voice* _Is Already Disabled_" elseif lang then return "بیصدا کردن صدا غیر فعال است" end else data[tostring(target)]["mutes"]["mute_voice"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Voice* _Has Been Disabled_" else return "بیصدا کردن صدا غیر فعال شد" end end end ---------------Mute Sticker------------------- local function mute_sticker(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_sticker = data[tostring(target)]["mutes"]["mute_sticker"] if mute_sticker == "yes" then if not lang then return "*Mute Sticker* _Is Already Enabled_" elseif lang then return "بیصدا کردن برچسب فعال است" end else data[tostring(target)]["mutes"]["mute_sticker"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Sticker* _Has Been Enabled_" else return "بیصدا کردن برچسب فعال شد" end end end local function unmute_sticker(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_sticker = data[tostring(target)]["mutes"]["mute_sticker"] if mute_sticker == "no" then if not lang then return "*Mute Sticker* _Is Already Disabled_" elseif lang then return "بیصدا کردن برچسب غیر فعال است" end else data[tostring(target)]["mutes"]["mute_sticker"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Sticker* _Has Been Disabled_" else return "بیصدا کردن برچسب غیر فعال شد" end end end ---------------Mute Contact------------------- local function mute_contact(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_contact = data[tostring(target)]["mutes"]["mute_contact"] if mute_contact == "yes" then if not lang then return "*Mute Contact* _Is Already Enabled_" elseif lang then return "بیصدا کردن مخاطب فعال است" end else data[tostring(target)]["mutes"]["mute_contact"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Contact* _Has Been Enabled_" else return "بیصدا کردن مخاطب فعال شد" end end end local function unmute_contact(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_contact = data[tostring(target)]["mutes"]["mute_contact"] if mute_contact == "no" then if not lang then return "*Mute Contact* _Is Already Disabled_" elseif lang then return "بیصدا کردن مخاطب غیر فعال است" end else data[tostring(target)]["mutes"]["mute_contact"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Contact* _Has Been Disabled_" else return "بیصدا کردن مخاطب غیر فعال شد" end end end ---------------Mute Forward------------------- local function mute_forward(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_forward = data[tostring(target)]["mutes"]["mute_forward"] if mute_forward == "yes" then if not lang then return "*Mute Forward* _Is Already Enabled_" elseif lang then return "بیصدا کردن نقل قول فعال است" end else data[tostring(target)]["mutes"]["mute_forward"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Forward* _Has Been Enabled_" else return "بیصدا کردن نقل قول فعال شد" end end end local function unmute_forward(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_forward = data[tostring(target)]["mutes"]["mute_forward"] if mute_forward == "no" then if not lang then return "*Mute Forward* _Is Already Disabled_" elseif lang then return "بیصدا کردن نقل قول غیر فعال است" end else data[tostring(target)]["mutes"]["mute_forward"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Forward* _Has Been Disabled_" else return "بیصدا کردن نقل قول غیر فعال شد" end end end ---------------Mute Location------------------- local function mute_location(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_location = data[tostring(target)]["mutes"]["mute_location"] if mute_location == "yes" then if not lang then return "*Mute Location* _Is Already Enabled_" elseif lang then return "بیصدا کردن موقعیت فعال است" end else data[tostring(target)]["mutes"]["mute_location"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Location* _Has Been Enabled_" else return "بیصدا کردن موقعیت فعال شد" end end end local function unmute_location(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_location = data[tostring(target)]["mutes"]["mute_location"] if mute_location == "no" then if not lang then return "*Mute Location* _Is Already Disabled_" elseif lang then return "بیصدا کردن موقعیت غیر فعال است" end else data[tostring(target)]["mutes"]["mute_location"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Location* _Has Been Disabled_" else return "بیصدا کردن موقعیت غیر فعال شد" end end end ---------------Mute Document------------------- local function mute_document(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_document = data[tostring(target)]["mutes"]["mute_document"] if mute_document == "yes" then if not lang then return "*Mute Document* _Is Already Enabled_" elseif lang then return "بیصدا کردن اسناد فعال لست" end else data[tostring(target)]["mutes"]["mute_document"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Document* _Has Been Enabled_" else return "بیصدا کردن اسناد فعال شد" end end end local function unmute_document(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_document = data[tostring(target)]["mutes"]["mute_document"] if mute_document == "no" then if not lang then return "*Mute Document* _Is Already Disabled_" elseif lang then return "بیصدا کردن اسناد غیر فعال است" end else data[tostring(target)]["mutes"]["mute_document"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Document* _Has Been Disabled_" else return "بیصدا کردن اسناد غیر فعال شد" end end end ---------------Mute TgService------------------- local function mute_tgservice(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_tgservice = data[tostring(target)]["mutes"]["mute_tgservice"] if mute_tgservice == "yes" then if not lang then return "*Mute TgService* _Is Already Enabled_" elseif lang then return "بیصدا کردن خدمات تلگرام فعال است" end else data[tostring(target)]["mutes"]["mute_tgservice"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute TgService* _Has Been Enabled_" else return "بیصدا کردن خدمات تلگرام فعال شد" end end end local function unmute_tgservice(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نیستید" end end local mute_tgservice = data[tostring(target)]["mutes"]["mute_tgservice"] if mute_tgservice == "no" then if not lang then return "*Mute TgService* _Is Already Disabled_" elseif lang then return "بیصدا کردن خدمات تلگرام غیر فعال است" end else data[tostring(target)]["mutes"]["mute_tgservice"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute TgService* _Has Been Disabled_" else return "بیصدا کردن خدمات تلگرام غیر فعال شد" end end end ---------------Mute Keyboard------------------- local function mute_keyboard(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نمیباشید" end end local mute_keyboard = data[tostring(target)]["mutes"]["mute_keyboard"] if mute_keyboard == "yes" then if not lang then return "*Mute Keyboard* _Is Already Enabled_" elseif lang then return "بیصدا کردن صفحه کلید فعال است" end else data[tostring(target)]["mutes"]["mute_keyboard"] = "yes" save_data(_config.moderation.data, data) if not lang then return "*Mute Keyboard* _Has Been Enabled_" else return "بیصدا کردن صفحه کلید فعال شد" end end end local function unmute_keyboard(msg, data, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نیستید" end end local mute_keyboard = data[tostring(target)]["mutes"]["mute_keyboard"] if mute_keyboard == "no" then if not lang then return "*Mute Keyboard* _Is Already Disabled_" elseif lang then return "بیصدا کردن صفحه کلید غیرفعال است" end else data[tostring(target)]["mutes"]["mute_keyboard"] = "no" save_data(_config.moderation.data, data) if not lang then return "*Mute Keyboard* _Has Been Disabled_" else return "بیصدا کردن صفحه کلید غیرفعال شد" end end end ----------MuteList--------- local function mutes(msg, target) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) if not is_mod(msg) then if not lang then return "_You're Not_ *Moderator*" else return "شما مدیر گروه نیستید" end end local data = load_data(_config.moderation.data) local target = msg.to.id if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_all"] then data[tostring(target)]["mutes"]["mute_all"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_gif"] then data[tostring(target)]["mutes"]["mute_gif"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_text"] then data[tostring(target)]["mutes"]["mute_text"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_photo"] then data[tostring(target)]["mutes"]["mute_photo"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_video"] then data[tostring(target)]["mutes"]["mute_video"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_audio"] then data[tostring(target)]["mutes"]["mute_audio"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_voice"] then data[tostring(target)]["mutes"]["mute_voice"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_sticker"] then data[tostring(target)]["mutes"]["mute_sticker"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_contact"] then data[tostring(target)]["mutes"]["mute_contact"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_forward"] then data[tostring(target)]["mutes"]["mute_forward"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_location"] then data[tostring(target)]["mutes"]["mute_location"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_document"] then data[tostring(target)]["mutes"]["mute_document"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_tgservice"] then data[tostring(target)]["mutes"]["mute_tgservice"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_inline"] then data[tostring(target)]["mutes"]["mute_inline"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_game"] then data[tostring(target)]["mutes"]["mute_game"] = "no" end end if data[tostring(target)]["mutes"] then if not data[tostring(target)]["mutes"]["mute_keyboard"] then data[tostring(target)]["mutes"]["mute_keyboard"] = "no" end end if not lang then local mutes = data[tostring(target)]["mutes"] text = " *Group Mute List* : \n_Mute all : _ *"..mutes.mute_all.."*\n_Mute gif :_ *"..mutes.mute_gif.."*\n_Mute text :_ *"..mutes.mute_text.."*\n_Mute inline :_ *"..mutes.mute_inline.."*\n_Mute game :_ *"..mutes.mute_game.."*\n_Mute photo :_ *"..mutes.mute_photo.."*\n_Mute video :_ *"..mutes.mute_video.."*\n_Mute audio :_ *"..mutes.mute_audio.."*\n_Mute voice :_ *"..mutes.mute_voice.."*\n_Mute sticker :_ *"..mutes.mute_sticker.."*\n_Mute contact :_ *"..mutes.mute_contact.."*\n_Mute forward :_ *"..mutes.mute_forward.."*\n_Mute location :_ *"..mutes.mute_location.."*\n_Mute document :_ *"..mutes.mute_document.."*\n_Mute TgService :_ *"..mutes.mute_tgservice.."*\n_Mute Keyboard :_ *"..mutes.mute_keyboard.."*\n*____________________*\n*Bot channel*: @TeleJavidBot\n*Group Language* : *EN*" else local mutes = data[tostring(target)]["mutes"] text = " *لیست بیصدا ها* : \n_بیصدا همه : _ *"..mutes.mute_all.."*\n_بیصدا تصاویر متحرک :_ *"..mutes.mute_gif.."*\n_بیصدا متن :_ *"..mutes.mute_text.."*\n_بیصدا کیبورد شیشه ای :_ *"..mutes.mute_inline.."*\n_بیصدا بازی های تحت وب :_ *"..mutes.mute_game.."*\n_بیصدا عکس :_ *"..mutes.mute_photo.."*\n_بیصدا فیلم :_ *"..mutes.mute_video.."*\n_بیصدا آهنگ :_ *"..mutes.mute_audio.."*\n_بیصدا صدا :_ *"..mutes.mute_voice.."*\n_بیصدا برچسب :_ *"..mutes.mute_sticker.."*\n_بیصدا مخاطب :_ *"..mutes.mute_contact.."*\n_بیصدا نقل قول :_ *"..mutes.mute_forward.."*\n_بیصدا موقعیت :_ *"..mutes.mute_location.."*\n_بیصدا اسناد :_ *"..mutes.mute_document.."*\n_بیصدا خدمات تلگرام :_ *"..mutes.mute_tgservice.."*\n_بیصدا صفحه کلید :_ *"..mutes.mute_keyboard.."*\n*____________________*\n*Bot channel*: @TeleJavidBot\n_زبان سوپرگروه_ : *FA*" end return text end local function run(msg, matches) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local Chash = "cmd_lang:"..msg.to.id local Clang = redis:get(Chash) local data = load_data(_config.moderation.data) local chat = msg.to.id local user = msg.from.id if msg.to.type ~= 'pv' then if ((matches[1] == "add" and not Clang) or (matches[1] == "افزودن" and Clang)) then return modadd(msg) end if ((matches[1] == "rem" and not Clang) or (matches[1] == "حذف گروه" and Clang)) then return modrem(msg) end if not data[tostring(msg.to.id)] then return end if (matches[1] == "id" and not Clang) or (matches[1] == "ایدی" and Clang) then if not matches[2] and not msg.reply_id then local function getpro(arg, data) if data.photos_[0] then if not lang then tdcli.sendPhoto(msg.chat_id_, msg.id_, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,'Chat ID : '..msg.to.id..'\nUser ID : '..msg.from.id,dl_cb,nil) elseif lang then tdcli.sendPhoto(msg.chat_id_, msg.id_, 0, 1, nil, data.photos_[0].sizes_[1].photo_.persistent_id_,'شناسه گروه : '..msg.to.id..'\nشناسه شما : '..msg.from.id,dl_cb,nil) end else if not lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, "`You Have Not Profile Photo...!`\n\n> *Chat ID :* `"..msg.to.id.."`\n*User ID :* `"..msg.from.id.."`", 1, 'md') elseif lang then tdcli.sendMessage(msg.to.id, msg.id_, 1, "_شما هیچ عکسی ندارید...!_\n\n> _شناسه گروه :_ `"..msg.to.id.."`\n_شناسه شما :_ `"..msg.from.id.."`", 1, 'md') end end end tdcli_function ({ ID = "GetUserProfilePhotos", user_id_ = msg.from.id, offset_ = 0, limit_ = 1 }, getpro, nil) end if msg.reply_id and not matches[2] and is_mod(msg) then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="id"}) end if matches[2] and is_mod(msg) then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="id"}) end end if ((matches[1] == "pin" and not Clang) or (matches[1] == "سنجاق" and Clang)) and is_mod(msg) and msg.reply_id then local lock_pin = data[tostring(msg.to.id)]["settings"]["lock_pin"] if lock_pin == 'yes' then if is_owner(msg) then data[tostring(chat)]['pin'] = msg.reply_id save_data(_config.moderation.data, data) tdcli.pinChannelMessage(msg.to.id, msg.reply_id, 1) if not lang then return "*Message Has Been Pinned*" elseif lang then return "پیام سجاق شد" end elseif not is_owner(msg) then return end elseif lock_pin == 'no' then data[tostring(chat)]['pin'] = msg.reply_id save_data(_config.moderation.data, data) tdcli.pinChannelMessage(msg.to.id, msg.reply_id, 1) if not lang then return "*Message Has Been Pinned*" elseif lang then return "پیام سجاق شد" end end end if ((matches[1] == 'unpin' and not Clang) or (matches[1] == "حذف سنجاق" and Clang)) and is_mod(msg) then local lock_pin = data[tostring(msg.to.id)]["settings"]["lock_pin"] if lock_pin == 'yes' then if is_owner(msg) then tdcli.unpinChannelMessage(msg.to.id) if not lang then return "*Pin message has been unpinned*" elseif lang then return "پیام سنجاق شده پاک شد" end elseif not is_owner(msg) then return end elseif lock_pin == 'no' then tdcli.unpinChannelMessage(msg.to.id) if not lang then return "*Pin message has been unpinned*" elseif lang then return "پیام سنجاق شده پاک شد" end end end if ((matches[1]:lower() == "whitelist" and not Clang) or (matches[1] == "لیست سفید" and Clang)) and matches[2] == "+" and is_mod(msg) then if not matches[3] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="setwhitelist"}) end if matches[3] and string.match(matches[3], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[3], }, action_by_id, {chat_id=msg.to.id,user_id=matches[3],cmd="setwhitelist"}) end if matches[3] and not string.match(matches[3], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[3] }, action_by_username, {chat_id=msg.to.id,username=matches[3],cmd="setwhitelist"}) end end if ((matches[1]:lower() == "whitelist" and not Clang) or (matches[1] == "لیست سفید" and Clang)) and matches[2] == "-" and is_mod(msg) then if not matches[3] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="remwhitelist"}) end if matches[3] and string.match(matches[3], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[3], }, action_by_id, {chat_id=msg.to.id,user_id=matches[3],cmd="remwhitelist"}) end if matches[3] and not string.match(matches[3], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[3] }, action_by_username, {chat_id=msg.to.id,username=matches[3],cmd="remwhitelist"}) end end if ((matches[1] == "setowner" and not Clang) or (matches[1] == 'مالک' and Clang)) and is_admin(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="setowner"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="setowner"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="setowner"}) end end if ((matches[1] == "remowner" and not Clang) or (matches[1] == "حذف مالک" and Clang)) and is_admin(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="remowner"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="remowner"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="remowner"}) end end if ((matches[1] == "promote" and not Clang) or (matches[1] == "مدیر" and Clang)) and is_owner(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="promote"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="promote"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="promote"}) end end if ((matches[1] == "demote" and not Clang) or (matches[1] == "حذف مدیر" and Clang)) and is_owner(msg) then if not matches[2] and msg.reply_id then tdcli_function ({ ID = "GetMessage", chat_id_ = msg.to.id, message_id_ = msg.reply_id }, action_by_reply, {chat_id=msg.to.id,cmd="demote"}) end if matches[2] and string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="demote"}) end if matches[2] and not string.match(matches[2], '^%d+$') then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="demote"}) end end if ((matches[1] == "lock" and not Clang) or (matches[1] == "قفل" and Clang)) and is_mod(msg) then local target = msg.to.id if ((matches[2] == "link" and not Clang) or (matches[2] == "لینک" and Clang)) then return lock_link(msg, data, target) end if ((matches[2] == "tag" and not Clang) or (matches[2] == "تگ" and Clang)) then return lock_tag(msg, data, target) end if ((matches[2] == "mention" and not Clang) or (matches[2] == "فراخوانی" and Clang)) then return lock_mention(msg, data, target) end if ((matches[2] == "arabic" and not Clang) or (matches[2] == "عربی" and Clang)) then return lock_arabic(msg, data, target) end if ((matches[2] == "edit" and not Clang) or (matches[2] == "ویرایش" and Clang)) then return lock_edit(msg, data, target) end if ((matches[2] == "spam" and not Clang) or (matches[2] == "هرزنامه" and Clang)) then return lock_spam(msg, data, target) end if ((matches[2] == "flood" and not Clang) or (matches[2] == "پیام مکرر" and Clang)) then return lock_flood(msg, data, target) end if ((matches[2] == "bots" and not Clang) or (matches[2] == "ربات" and Clang)) then return lock_bots(msg, data, target) end if ((matches[2] == "markdown" and not Clang) or (matches[2] == "فونت" and Clang)) then return lock_markdown(msg, data, target) end if ((matches[2] == "webpage" and not Clang) or (matches[2] == "وب" and Clang)) then return lock_webpage(msg, data, target) end if ((matches[2] == "pin" and not Clang) or (matches[2] == "سنجاق" and Clang)) and is_owner(msg) then return lock_pin(msg, data, target) end if ((matches[2] == "join" and not Clang) or (matches[2] == "ورود" and Clang)) then return lock_join(msg, data, target) end end if ((matches[1] == "unlock" and not Clang) or (matches[1] == "باز کردن" and Clang)) and is_mod(msg) then local target = msg.to.id if ((matches[2] == "link" and not Clang) or (matches[2] == "لینک" and Clang)) then return unlock_link(msg, data, target) end if ((matches[2] == "tag" and not Clang) or (matches[2] == "تگ" and Clang)) then return unlock_tag(msg, data, target) end if ((matches[2] == "mention" and not Clang) or (matches[2] == "فراخوانی" and Clang)) then return unlock_mention(msg, data, target) end if ((matches[2] == "arabic" and not Clang) or (matches[2] == "عربی" and Clang)) then return unlock_arabic(msg, data, target) end if ((matches[2] == "edit" and not Clang) or (matches[2] == "ویرایش" and Clang)) then return unlock_edit(msg, data, target) end if ((matches[2] == "spam" and not Clang) or (matches[2] == "هرزنامه" and Clang)) then return unlock_spam(msg, data, target) end if ((matches[2] == "flood" and not Clang) or (matches[2] == "پیام مکرر" and Clang)) then return unlock_flood(msg, data, target) end if ((matches[2] == "bots" and not Clang) or (matches[2] == "ربات" and Clang)) then return unlock_bots(msg, data, target) end if ((matches[2] == "markdown" and not Clang) or (matches[2] == "فونت" and Clang)) then return unlock_markdown(msg, data, target) end if ((matches[2] == "webpage" and not Clang) or (matches[2] == "وب" and Clang)) then return unlock_webpage(msg, data, target) end if ((matches[2] == "pin" and not Clang) or (matches[2] == "سنجاق" and Clang)) and is_owner(msg) then return unlock_pin(msg, data, target) end if ((matches[2] == "join" and not Clang) or (matches[2] == "ورود" and Clang)) then return unlock_join(msg, data, target) end end if ((matches[1] == "mute" and not Clang) or (matches[1] == "بیصدا" and Clang)) and is_mod(msg) then local target = msg.to.id if ((matches[2] == "all" and not Clang) or (matches[2] == "همه" and Clang)) then return mute_all(msg, data, target) end if ((matches[2] == "gif" and not Clang) or (matches[2] == "تصاویر متحرک" and Clang)) then return mute_gif(msg, data, target) end if ((matches[2] == "text" and not Clang) or (matches[2] == "متن" and Clang)) then return mute_text(msg ,data, target) end if ((matches[2] == "photo" and not Clang) or (matches[2] == "عکس" and Clang)) then return mute_photo(msg ,data, target) end if ((matches[2] == "video" and not Clang) or (matches[2] == "فیلم" and Clang)) then return mute_video(msg ,data, target) end if ((matches[2] == "audio" and not Clang) or (matches[2] == "اهنگ" and Clang)) then return mute_audio(msg ,data, target) end if ((matches[2] == "voice" and not Clang) or (matches[2] == "صدا" and Clang)) then return mute_voice(msg ,data, target) end if ((matches[2] == "sticker" and not Clang) or (matches[2] == "برچسب" and Clang)) then return mute_sticker(msg ,data, target) end if ((matches[2] == "contact" and not Clang) or (matches[2] == "مخاطب" and Clang)) then return mute_contact(msg ,data, target) end if ((matches[2] == "forward" and not Clang) or (matches[2] == "نقل قول" and Clang)) then return mute_forward(msg ,data, target) end if ((matches[2] == "location" and not Clang) or (matches[2] == "موقعیت" and Clang)) then return mute_location(msg ,data, target) end if ((matches[2] == "document" and not Clang) or (matches[2] == "اسناد" and Clang)) then return mute_document(msg ,data, target) end if ((matches[2] == "tgservice" and not Clang) or (matches[2] == "خدمات تلگرام" and Clang)) then return mute_tgservice(msg ,data, target) end if ((matches[2] == "inline" and not Clang) or (matches[2] == "کیبورد شیشه ای" and Clang)) then return mute_inline(msg ,data, target) end if ((matches[2] == "game" and not Clang) or (matches[2] == "بازی" and Clang)) then return mute_game(msg ,data, target) end if ((matches[2] == "keyboard" and not Clang) or (matches[2] == "صفحه کلید" and Clang)) then return mute_keyboard(msg ,data, target) end end if ((matches[1] == "unmute" and not Clang) or (matches[1] == "باصدا" and Clang)) and is_mod(msg) then local target = msg.to.id if ((matches[2] == "all" and not Clang) or (matches[2] == "همه" and Clang)) then return unmute_all(msg, data, target) end if ((matches[2] == "gif" and not Clang) or (matches[2] == "تصاویر متحرک" and Clang)) then return unmute_gif(msg, data, target) end if ((matches[2] == "text" and not Clang) or (matches[2] == "متن" and Clang)) then return unmute_text(msg, data, target) end if ((matches[2] == "photo" and not Clang) or (matches[2] == "عکس" and Clang)) then return unmute_photo(msg ,data, target) end if ((matches[2] == "video" and not Clang) or (matches[2] == "فیلم" and Clang)) then return unmute_video(msg ,data, target) end if ((matches[2] == "audio" and not Clang) or (matches[2] == "اهنگ" and Clang)) then return unmute_audio(msg ,data, target) end if ((matches[2] == "voice" and not Clang) or (matches[2] == "صدا" and Clang)) then return unmute_voice(msg ,data, target) end if ((matches[2] == "sticker" and not Clang) or (matches[2] == "برچسب" and Clang)) then return unmute_sticker(msg ,data, target) end if ((matches[2] == "contact" and not Clang) or (matches[2] == "مخاطب" and Clang)) then return unmute_contact(msg ,data, target) end if ((matches[2] == "forward" and not Clang) or (matches[2] == "نقل قول" and Clang)) then return unmute_forward(msg ,data, target) end if ((matches[2] == "location" and not Clang) or (matches[2] == "موقعیت" and Clang)) then return unmute_location(msg ,data, target) end if ((matches[2] == "document" and not Clang) or (matches[2] == "اسناد" and Clang)) then return unmute_document(msg ,data, target) end if ((matches[2] == "tgservice" and not Clang) or (matches[2] == "خدمات تلگرام" and Clang)) then return unmute_tgservice(msg ,data, target) end if ((matches[2] == "inline" and not Clang) or (matches[2] == "کیبورد شیشه ای" and Clang)) then return unmute_inline(msg ,data, target) end if ((matches[2] == "game" and not Clang) or (matches[2] == "بازی" and Clang)) then return unmute_game(msg ,data, target) end if ((matches[2] == "keyboard" and not Clang) or (matches[2] == "صفحه کلید" and Clang)) then return unmute_keyboard(msg ,data, target) end end if ((matches[1] == "gpinfo" and not Clang) or (matches[1] == "اطلاعات گروه" and Clang)) and is_mod(msg) and msg.to.type == "channel" then local function group_info(arg, data) local hash = "gp_lang:"..arg.chat_id local lang = redis:get(hash) if not lang then ginfo = "*Group Info :*\n_Admin Count :_ *"..data.administrator_count_.."*\n_Member Count :_ *"..data.member_count_.."*\n_Kicked Count :_ *"..data.kicked_count_.."*\n_Group ID :_ *"..data.channel_.id_.."*" print(serpent.block(data)) elseif lang then ginfo = "*اطلاعات گروه :*\n_تعداد مدیران :_ *"..data.administrator_count_.."*\n_تعداد اعضا :_ *"..data.member_count_.."*\n_تعداد اعضای حذف شده :_ *"..data.kicked_count_.."*\n_شناسه گروه :_ *"..data.channel_.id_.."*" print(serpent.block(data)) end tdcli.sendMessage(arg.chat_id, arg.msg_id, 1, ginfo, 1, 'md') end tdcli.getChannelFull(msg.to.id, group_info, {chat_id=msg.to.id,msg_id=msg.id}) end if ((matches[1] == 'newlink' and not Clang) or (matches[1] == "لینک جدید" and Clang)) and is_mod(msg) then local function callback_link (arg, data) local hash = "gp_lang:"..msg.to.id local lang = redis:get(hash) local administration = load_data(_config.moderation.data) if not data.invite_link_ then administration[tostring(msg.to.id)]['settings']['linkgp'] = nil save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 1, "_Bot is not group creator_\n_set a link for group with using_ /setlink"..msg_caption, 1, 'md') elseif lang then return tdcli.sendMessage(msg.to.id, msg.id, 1, "_ربات سازنده گروه نیست_\n_با دستور_ setlink/ _لینک جدیدی برای گروه ثبت کنید_"..msg_caption, 1, 'md') end else administration[tostring(msg.to.id)]['settings']['linkgp'] = data.invite_link_ save_data(_config.moderation.data, administration) if not lang then return tdcli.sendMessage(msg.to.id, msg.id, 1, "*Newlink Created*", 1, 'md') elseif lang then return tdcli.sendMessage(msg.to.id, msg.id, 1, "_لینک جدید ساخته شد_", 1, 'md') end end end tdcli.exportChatInviteLink(msg.to.id, callback_link, nil) end if ((matches[1] == 'setlink' and not Clang) or (matches[1] == "تنظیم لینک" and Clang)) and is_owner(msg) then data[tostring(chat)]['settings']['linkgp'] = 'waiting' save_data(_config.moderation.data, data) if not lang then return '_Please send the new group_ *link* _now_' else return 'لطفا لینک گروه خود را ارسال کنید' end end if msg.text then local is_link = msg.text:match("^([https?://w]*.?telegram.me/joinchat/%S+)$") or msg.text:match("^([https?://w]*.?t.me/joinchat/%S+)$") if is_link and data[tostring(chat)]['settings']['linkgp'] == 'waiting' and is_owner(msg) then data[tostring(chat)]['settings']['linkgp'] = msg.text save_data(_config.moderation.data, data) if not lang then return "*Newlink* _has been set_" else return "لینک جدید ذخیره شد" end end end if ((matches[1] == 'link' and not Clang) or (matches[1] == "لینک" and Clang)) and is_mod(msg) then local linkgp = data[tostring(chat)]['settings']['linkgp'] if not linkgp then if not lang then return "_First create a link for group with using_ /newlink\n_If bot not group creator set a link with using_ /setlink" else return "ابتدا با دستور newlink/ لینک جدیدی برای گروه بسازید\nو اگر ربات سازنده گروه نیس با دستور setlink/ لینک جدیدی برای گروه ثبت کنید" end end if not lang then text = "<b>Group Link :</b>\n"..linkgp..msg_caption else text = "<b>لینک گروه :</b>\n"..linkgp..msg_caption end return tdcli.sendMessage(chat, msg.id, 1, text, 1, 'html') end if ((matches[1] == 'linkpv' and not Clang) or (matches[1] == "لینک خصوصی" and Clang)) and is_mod(msg) then local linkgp = data[tostring(chat)]['settings']['linkgp'] if not linkgp then if not lang then return "_First create a link for group with using_ /newlink\n_If bot not group creator set a link with using_ /setlink" else return "ابتدا با دستور newlink/ لینک جدیدی برای گروه بسازید\nو اگر ربات سازنده گروه نیس با دستور setlink/ لینک جدیدی برای گروه ثبت کنید" end end if not lang then tdcli.sendMessage(user, "", 1, "<b>Group Link "..msg.to.title.." :</b>\n"..linkgp..msg_caption, 1, 'html') else tdcli.sendMessage(user, "", 1, "<b>لینک گروه "..msg.to.title.." :</b>\n"..linkgp..msg_caption, 1, 'html') end if not lang then return "*Group Link Was Send In Your Private Message*" else return "_لینک گروه به چت خصوصی شما ارسال شد_" end end if ((matches[1] == "setrules" and not Clang) or (matches[1] == "تنظیم قوانین" and Clang)) and matches[2] and is_mod(msg) then data[tostring(chat)]['rules'] = matches[2] save_data(_config.moderation.data, data) if not lang then return "*Group rules* _has been set_" else return "قوانین گروه ثبت شد" end end if ((matches[1] == "rules" and not Clang) or (matches[1] == "قوانین" and Clang)) then if not data[tostring(chat)]['rules'] then if not lang then rules = "ℹ️ The Default Rules :\n1⃣ No Flood.\n2⃣ No Spam.\n3⃣ No Advertising.\n4⃣ Try to stay on topic.\n5⃣ Forbidden any racist, sexual, homophobic or gore content.\n➡️ Repeated failure to comply with these rules will cause ban."..msg_caption elseif lang then rules = "ℹ️ قوانین پپیشفرض:\n1⃣ ارسال پیام مکرر ممنوع.\n2⃣ اسپم ممنوع.\n3⃣ تبلیغ ممنوع.\n4⃣ سعی کنید از موضوع خارج نشید.\n5⃣ هرنوع نژاد پرستی, شاخ بازی و پورنوگرافی ممنوع .\n➡️ از قوانین پیروی کنید, در صورت عدم رعایت قوانین اول اخطار و در صورت تکرار مسدود."..msg_caption end else rules = "*Group Rules :*\n"..data[tostring(chat)]['rules'] end return rules end if ((matches[1] == "res" and not Clang) or (matches[1] == "کاربری" and Clang)) and matches[2] and is_mod(msg) then tdcli_function ({ ID = "SearchPublicChat", username_ = matches[2] }, action_by_username, {chat_id=msg.to.id,username=matches[2],cmd="res"}) end if ((matches[1] == "whois" and not Clang) or (matches[1] == "شناسه" and Clang)) and matches[2] and is_mod(msg) then tdcli_function ({ ID = "GetUser", user_id_ = matches[2], }, action_by_id, {chat_id=msg.to.id,user_id=matches[2],cmd="whois"}) end if ((matches[1]:lower() == 'setchar' and not Clang) or (matches[1] == "حداکثر حروف مجاز" and Clang)) then if not is_mod(msg) then return end local chars_max = matches[2] data[tostring(msg.to.id)]['settings']['set_char'] = chars_max save_data(_config.moderation.data, data) if not lang then return "*Character sensitivity* _has been set to :_ *[ "..matches[2].." ]*" else return "_حداکثر حروف مجاز در پیام تنظیم شد به :_ *[ "..matches[2].." ]*" end end if ((matches[1]:lower() == 'setflood' and not Clang) or (matches[1] == "تنظیم پیام مکرر" and Clang)) and is_mod(msg) then if tonumber(matches[2]) < 1 or tonumber(matches[2]) > 50 then return "_Wrong number, range is_ *[2-50]*" end local flood_max = matches[2] data[tostring(chat)]['settings']['num_msg_max'] = flood_max save_data(_config.moderation.data, data) if not lang then return "_Group_ *flood* _sensitivity has been set to :_ *[ "..matches[2].." ]*" else return '_محدودیت پیام مکرر به_ *'..tonumber(matches[2])..'* _تنظیم شد._' end end if ((matches[1]:lower() == 'setfloodtime' and not Clang) or (matches[1] == "تنظیم زمان بررسی" and Clang)) and is_mod(msg) then if tonumber(matches[2]) < 2 or tonumber(matches[2]) > 10 then return "_Wrong number, range is_ *[2-10]*" end local time_max = matches[2] data[tostring(chat)]['settings']['time_check'] = time_max save_data(_config.moderation.data, data) if not lang then return "_Group_ *flood* _check time has been set to :_ *[ "..matches[2].." ]*" else return "_حداکثر زمان بررسی پیام های مکرر تنظیم شد به :_ *[ "..matches[2].." ]*" end end if ((matches[1]:lower() == 'clean' and not Clang) or (matches[1] == "پاک کردن" and Clang)) and is_owner(msg) then if ((matches[2] == 'mods' and not Clang) or (matches[2] == "مدیران" and Clang)) then if next(data[tostring(chat)]['mods']) == nil then if not lang then return "_No_ *moderators* _in this group_" else return "هیچ مدیری برای گروه انتخاب نشده است" end end for k,v in pairs(data[tostring(chat)]['mods']) do data[tostring(chat)]['mods'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "_All_ *moderators* _has been demoted_" else return "تمام مدیران گروه تنزیل مقام شدند" end end if ((matches[2] == 'filterlist' and not Clang) or (matches[2] == "لیست فیلتر" and Clang)) then if next(data[tostring(chat)]['filterlist']) == nil then if not lang then return "*Filtered words list* _is empty_" else return "_لیست کلمات فیلتر شده خالی است_" end end for k,v in pairs(data[tostring(chat)]['filterlist']) do data[tostring(chat)]['filterlist'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "*Filtered words list* _has been cleaned_" else return "_لیست کلمات فیلتر شده پاک شد_" end end if ((matches[2] == 'rules' and not Clang) or (matches[2] == "قوانین" and Clang)) then if not data[tostring(chat)]['rules'] then if not lang then return "_No_ *rules* _available_" else return "قوانین برای گروه ثبت نشده است" end end data[tostring(chat)]['rules'] = nil save_data(_config.moderation.data, data) if not lang then return "*Group rules* _has been cleaned_" else return "قوانین گروه پاک شد" end end if ((matches[2] == 'welcome' and not Clang) or (matches[2] == "خوشامد" and Clang)) then if not data[tostring(chat)]['setwelcome'] then if not lang then return "*Welcome Message not set*" else return "پیام خوشآمد گویی ثبت نشده است" end end data[tostring(chat)]['setwelcome'] = nil save_data(_config.moderation.data, data) if not lang then return "*Welcome message* _has been cleaned_" else return "پیام خوشآمد گویی پاک شد" end end if ((matches[2] == 'about' and not Clang) or (matches[2] == "درباره" and Clang)) then if msg.to.type == "chat" then if not data[tostring(chat)]['about'] then if not lang then return "_No_ *description* _available_" else return "پیامی مبنی بر درباره گروه ثبت نشده است" end end data[tostring(chat)]['about'] = nil save_data(_config.moderation.data, data) elseif msg.to.type == "channel" then tdcli.changeChannelAbout(chat, "", dl_cb, nil) end if not lang then return "*Group description* _has been cleaned_" else return "پیام مبنی بر درباره گروه پاک شد" end end end if ((matches[1]:lower() == 'clean' and not Clang) or (matches[1] == "پاک کردن" and Clang)) and is_admin(msg) then if ((matches[2] == 'owners' and not Clang) or (matches[2] == "مالکان" and Clang)) then if next(data[tostring(chat)]['owners']) == nil then if not lang then return "_No_ *owners* _in this group_" else return "مالکی برای گروه انتخاب نشده است" end end for k,v in pairs(data[tostring(chat)]['owners']) do data[tostring(chat)]['owners'][tostring(k)] = nil save_data(_config.moderation.data, data) end if not lang then return "_All_ *owners* _has been demoted_" else return "تمامی مالکان گروه تنزیل مقام شدند" end end end if ((matches[1] == "setname" and not Clang) or (matches[1] == "تنظیم نام" and Clang)) and matches[2] and is_mod(msg) then local gp_name = matches[2] tdcli.changeChatTitle(chat, gp_name, dl_cb, nil) end if ((matches[1] == "setabout" and not Clang) or (matches[1] == "تنظیم درباره" and Clang)) and matches[2] and is_mod(msg) then if msg.to.type == "channel" then tdcli.changeChannelAbout(chat, matches[2], dl_cb, nil) elseif msg.to.type == "chat" then data[tostring(chat)]['about'] = matches[2] save_data(_config.moderation.data, data) end if not lang then return "*Group description* _has been set_" else return "پیام مبنی بر درباره گروه ثبت شد" end end if ((matches[1] == "about" and not Clang) or (matches[1] == "درباره" and Clang)) and msg.to.type == "chat" and is_owner(msg) then if not data[tostring(chat)]['about'] then if not lang then about = "_No_ *description* _available_" elseif lang then about = "پیامی مبنی بر درباره گروه ثبت نشده است" end else about = "*Group Description :*\n"..data[tostring(chat)]['about'] end return about end if ((matches[1] == 'filter' and not Clang) or (matches[1] == "فیلتر" and Clang)) and is_mod(msg) then return filter_word(msg, matches[2]) end if ((matches[1] == 'unfilter' and not Clang) or (matches[1] == "حذف فیلتر" and Clang)) and is_mod(msg) then return unfilter_word(msg, matches[2]) end if ((matches[1] == 'filterlist' and not Clang) or (matches[1] == "لیست فیلتر" and Clang)) and is_mod(msg) then return filter_list(msg) end if ((matches[1] == "settings" and not Clang) or (matches[1] == "تنظیمات" and Clang)) and is_mod(msg) then return group_settings(msg, target) end if ((matches[1] == "mutelist" and not Clang) or (matches[1] == "لیست بیصدا" and Clang)) and is_mod(msg) then return mutes(msg, target) end if ((matches[1] == "modlist" and not Clang) or (matches[1] == "لیست مدیران" and Clang)) and is_mod(msg) then return modlist(msg) end if ((matches[1] == "ownerlist" and not Clang) or (matches[1] == "لیست مالکان" and Clang)) and is_owner(msg) then return ownerlist(msg) end if ((matches[1] == "whitelist" and not Clang) or (matches[1] == "لیست سفید" and Clang)) and not matches[2] and is_mod(msg) then return whitelist(msg.to.id) end if ((matches[1]:lower() == "option" and not Clang) or (matches[1] == "تنظیمات کلی" and Clang)) and is_mod(msg) then local function found_helper(TM, Beyond) local function inline_query_cb(TM, BD) if BD.results_ and BD.results_[0] then tdcli.sendInlineQueryResultMessage(msg.to.id, 0, 0, 1, BD.inline_query_id_, BD.results_[0].id_, dl_cb, nil) else if not lang then text = "*Helper is offline*\n\n" elseif lang then text = "_ربات هلپر خاموش است_\n\n" end return tdcli.sendMessage(msg.to.id, msg.id, 0, text, 0, "md") end end tdcli.getInlineQueryResults(Beyond.id_, msg.to.id, 0, 0, msg.to.id, 0, inline_query_cb, nil) end tdcli.searchPublicChat(tostring(helper_username), found_helper, nil) end if (matches[1]:lower() == "setlang" and not Clang) and is_owner(msg) then local hash = "gp_lang:"..msg.to.id if matches[2] == "fa" then redis:set(hash, true) return "*زبان گروه تنظیم شد به : فارسی*"..msg_caption elseif matches[2] == "en" then redis:del(hash) return "_Group Language Set To:_ EN"..msg_caption end end if (matches[1] == 'زبان' and Clang) and is_owner(msg) then local hash = "gp_lang:"..msg.to.id if matches[2] == "فارسی" then redis:set(hash, true) return "*زبان گروه تنظیم شد به : فارسی*"..msg_caption elseif matches[2] == "انگلیسی" then redis:del(hash) return "_Group Language Set To:_ EN"..msg_caption end end if (matches[1]:lower() == "setcmd" and not Clang) and is_owner(msg) then local hash = "cmd_lang:"..msg.to.id if matches[2] == "fa" then redis:set(hash, true) if lang then return "*زبان دستورات ربات تنظیم شد به : فارسی*"..msg_caption else return "_Bot Commands Language Set To:_ Fa"..msg_caption end end end if (matches[1]:lower() == "دستورات انگلیسی" and Clang) and is_owner(msg) then local hash = "cmd_lang:"..msg.to.id redis:del(hash) if lang then return "*زبان دستورات ربات تنظیم شد به : انگلیسی*"..msg_caption else return "_Bot Commands Language Set To:_ EN"..msg_caption end end if (matches[1] == "help" and not Clang) and is_mod(msg) then if not lang then text = [[ *TeleJavid Bot Commands:* *setowner* `[username|id|reply]` _Set Group Owner(Multi Owner)_ *remowner* `[username|id|reply]` _Remove User From Owner List_ *promote* `[username|id|reply]` _Promote User To Group Admin_ *demote* `[username|id|reply]` _Demote User From Group Admins List_ *setflood* `[1-50]` _Set Flooding Number_ *setchar* `[Number]` _Set Flooding Characters_ *setfloodtime* `[1-10]` _Set Flooding Time_ *silent* `[username|id|reply]` _Silent User From Group_ *unsilent* `[username|id|reply]` _Unsilent User From Group_ *kick* `[username|id|reply]` _Kick User From Group_ *ban* `[username|id|reply]` _Ban User From Group_ *unban* `[username|id|reply]` _UnBan User From Group_ *whitelist* [+-] `[username|id|reply]` _Add Or Remove User From White List_ *res* `[username]` _Show User ID_ *id* `[reply]` _Show User ID_ *whois* `[id]` _Show User's Username And Name_ *lock* `[link | join | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | pin | cmds]` _If This Actions Lock, Bot Check Actions And Delete Them_ *unlock* `[link | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | pin]` _If This Actions Unlock, Bot Not Delete Them_ *mute* `[gif | photo | document | sticker | keyboard | video | text | forward | location | audio | voice | contact | all]` _If This Actions Lock, Bot Check Actions And Delete Them_ *unmute* `[gif | photo | document | sticker | keyboard | video | text | forward | location | audio | voice | contact | all]` _If This Actions Unlock, Bot Not Delete Them_ *set*`[rules | name | photo | link | about | welcome]` _Bot Set Them_ *clean* `[bans | mods | bots | rules | about | silentlist | filtelist | welcome]` _Bot Clean Them_ *filter* `[word]` _Word filter_ *unfilter* `[word]` _Word unfilter_ *pin* `[reply]` _Pin Your Message_ *unpin* _Unpin Pinned Message_ *welcome enable/disable* _Enable Or Disable Group Welcome_ *settings* _Show Group Settings_ *mutelist* _Show Mutes List_ *silentlist* _Show Silented Users List_ *filterlist* _Show Filtered Words List_ *banlist* _Show Banned Users List_ *ownerlist* _Show Group Owners List_ *modlist* _Show Group Moderators List_ *whitelist* _Show Group White List Users_ *rules* _Show Group Rules_ *about* _Show Group Description_ *id* _Show Your And Chat ID_ *gpinfo* _Show Group Information_ *newlink* _Create A New Link_ *link* _Show Group Link_ *linkpv* _Send Group Link In Your Private Message_ *setwelcome [text]* _set Welcome Message_ *setlang [fa | en]* _Set Persian/English Language_ *setcmd [fa | en]* _Set CMD Persian/English Language_ *helptools* _Show Tools Help_ *!helpfun* _Show Fun Help_ _This Help List Only For_ *Moderators/Owners!* _Its Means, Only Group_ *Moderators/Owners* _Can Use It!_ *Good luck ;)*]] elseif lang then text = [[ _دستورات ربات تله جاوید:_ *setowner* `[username|id|reply]` _انتخاب مالک گروه(قابل انتخاب چند مالک)_ *remowner* `[username|id|reply]` _حذف کردن فرد از فهرست مالکان گروه_ *promote* `[username|id|reply]` _ارتقا مقام کاربر به مدیر گروه_ *demote* `[username|id|reply]` _تنزیل مقام مدیر به کاربر_ *setflood* `[1-50]` _تنظیم حداکثر تعداد پیام مکرر_ *setchar* `[Number]` _تنظیم حداکثر کاراکتر پیام مکرر_ *setfloodtime* `[1-10]` _تنظیم زمان ارسال پیام مکرر_ *silent* `[username|id|reply]` _بیصدا کردن کاربر در گروه_ *unsilent* `[username|id|reply]` _در آوردن کاربر از حالت بیصدا در گروه_ *kick* `[username|id|reply]` _حذف کاربر از گروه_ *ban* `[username|id|reply]` _مسدود کردن کاربر از گروه_ *unban* `[username|id|reply]` _در آوردن از حالت مسدودیت کاربر از گروه_ *whitelist* `[+|-]` `[یوزرنیم|ایدی|ریپلی]` _افزودن افراد به لیست سفید_ *res* `[username]` _نمایش شناسه کاربر_ *id* `[reply]` نمایش شناسه کاربر *whois* `[id]` _نمایش نام کاربر, نام کاربری و اطلاعات حساب_ *lock* `[link | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | pin]` _در صورت قفل بودن فعالیت ها, ربات آنهارا حذف خواهد کرد_ *unlock* `[link | tag | edit | arabic | webpage | bots | spam | flood | markdown | mention | pin]` _در صورت قفل نبودن فعالیت ها, ربات آنهارا حذف نخواهد کرد_ *mute* `[gif | photo | document | sticker | keyboard | video | text | forward | location | audio | voice | contact | all]` _در صورت بیصدد بودن فعالیت ها, ربات آنهارا حذف خواهد کرد_ *unmute* `[gif | photo | document | sticker | keyboard | video | text | forward | location | audio | voice | contact | all]` _در صورت بیصدا نبودن فعالیت ها, ربات آنهارا حذف نخواهد کرد_ *set*`[rules | name | photo | link | about | welcome]` _ربات آنهارا ثبت خواهد کرد_ *clean* `[bans | mods | rules | about | silentlist | filterlist | welcome]` _ربات آنهارا پاک خواهد کرد_ *filter* `[word]` _فیلتر‌کلمه مورد نظر_ *unfilter* `[word]` _ازاد کردن کلمه مورد نظر_ *pin* `[reply]` _ربات پیام شمارا در گروه سنجاق خواهد کرد_ *unpin * ربات پیام سنجاق شده در گروه را حذف خواهد کرد *welcome* `enable/disable` _فعال یا غیرفعال کردن خوشامد گویی_ *settings* _نمایش تنظیمات گروه_ *mutelist* _نمایش فهرست بیصدا های گروه_ *silentlist* _نمایش فهرست افراد بیصدا_ *filterlist* _نمایش لیست کلمات فیلتر شده_ *banlist* _نمایش افراد مسدود شده از گروه_ *ownerlist* _نمایش فهرست مالکان گروه_ *modlist* _نمایش فهرست مدیران گروه_ *whitelist* _نمایش افراد سفید شده از گروه_ *rules* _نمایش قوانین گروه_ *about* _نمایش درباره گروه_ *id* _نمایش شناسه شما و گروه_ *gpinfo* _نمایش اطلاعات گروه_ *newlink* _ساخت لینک جدید_ *setlink* _تنظیم لینک جدید_ *link* _نمایش لینک گروه_ *linkpv* _ارسال لینک گروه به چت خصوصی شما_ *setwelcome* `[text]` _ثبت پیام خوش آمد گویی_ *setlang* `[fa | en]` _تنظیم زبان ربات به فارسی یا انگلیسی_ *setcmd* `[fa | en]` _تنظیم زبان دستورات ربات به فارسی یا انگلیسی_ *helptools* _نمایش راهنمای ابزار_ *helpfun* _نمایش راهنمای سرگرمی_ _این راهنما فقط برای مدیران/مالکان گروه میباشد!_ _این به این معناست که فقط مدیران/مالکان گروه میتوانند از دستورات بالا استفاده کنند!_ _موفق باشید_ *;)* ]] end return text..msg_caption end if (matches[1] == "راهنما" and Clang) and is_mod(msg) then if not lang then text = [[ *TeleJavid Bot Commands:* *مالک* `[username|id|reply]` _Set Group Owner(Multi Owner)_ *حذف مالک* `[username|id|reply]` _Remove User From Owner List_ *مدیر* `[username|id|reply]` _Promote User To Group Admin_ *حذف مدیر* `[username|id|reply]` _Demote User From Group Admins List_ *تنظیم پیام مکرر* `[1-50]` _Set Flooding Number_ *حداکثر حروف مجاز* `[عدد]` _Set Flooding Characters_ *تنظیم زمان بررسی* `[1-10]` _Set Flooding Time_ *سکوت* `[username|id|reply]` _Silent User From Group_ *حذف سکوت* `[username|id|reply]` _Unsilent User From Group_ *اخراج* `[username|id|reply]` _Kick User From Group_ *بن* `[username|id|reply]` _Ban User From Group_ *حذف بن* `[username|id|reply]` _UnBan User From Group_ *لیست سفید* [+-] `[username|id|reply]` _Add Or Remove User From White List_ *کاربری* `[username]` _Show User ID_ *ایدی* `[reply]` _Show User ID_ *شناسه* `[id]` _Show User's Username And Name_ *قفل* `[لینک | ورود | تگ | ویرایش | عربی | وب | ربات |هرزنامه | پیام مکرر | فونت | فراخوانی | سنجاق]` _If This Actions Lock, Bot Check Actions And Delete Them_ *باز کردن* `[لینک | ورود | تگ | ویرایش | عربی | وب | ربات |هرزنامه | پیام مکرر | فونت | فراخوانی | سنجاق]` _If This Actions Unlock, Bot Not Delete Them_ *بیصدا* `[همه | تصاویر متحرک | عکس | اسناد | برچسب | صفحه کلید | فیلم | متن | نقل قول | موقعیت | اهنگ | صدا | مخاطب | کیبورد شیشه ای|بازی|خدمات تلگرام]` _If This Actions Lock, Bot Check Actions And Delete Them_ *باصدا* `[همه | تصاویر متحرک | عکس | اسناد | برچسب | صفحه کلید | فیلم | متن | نقل قول | موقعیت | اهنگ | صدا | مخاطب | کیبورد شیشه ای|بازی|خدمات تلگرام]` _If This Actions Unlock, Bot Not Delete Them_ *تنظیم*`[قوانین | نام | لینک | درباره | خوشامد]` _Bot Set Them_ *پاک کردن* `[بن | مدیران | ربات | قوانین | درباره | لیست سکوت | خوشامد]` _Bot Clean Them_ *فیلتر* `[word]` _Word filter_ *حذف فیلتر* `[word]` _Word unfilter_ *سنجاق* `[reply]` _Pin Your Message_ *حذف سنجاق* _Unpin Pinned Message_ *خوشامد فعال/غیرفعال* _Enable Or Disable Group Welcome_ *تنظیمات* _Show Group Settings_ *لیست بیصدا* _Show Mutes List_ *لیست سکوت* _Show Silented Users List_ *لیست فیلتر* _Show Filtered Words List_ *لیست بن* _Show Banned Users List_ *لیست مالکان* _Show Group Owners List_ *لیست مدیران* _Show Group Moderators List_ *لیست سفید* _Show Group White List Users_ *قوانین* _Show Group Rules_ *درباره* _Show Group Description_ *ایدی* _Show Your And Chat ID_ *اطلاعات گروه* _Show Group Information_ *لینک جدید* _Create A New Link_ *تنظیم لینک* _Set A New Link_ *لینک* _Show Group Link_ *لینک خصوصی* _Send Group Link In Your Private Message_ *تنظیم خوشامد [text]* _set Welcome Message_ *زبان [فارسی | انگلیسی]* _Set Persian/English Language_ *دستورات [فارسی | انگلیسی]* _Set CMD Persian/English Language_ *راهنمای ابزار* _Show Tools Help_ *راهنمای سرگرمی* _Show Fun Help_ _This Help List Only For_ *Moderators/Owners!* _Its Means, Only Group_ *Moderators/Owners* _Can Use It!_ *Good luck ;)*]] elseif lang then text = [[ *دستورات ربات تله جاوید:* *مالک* `[یوزرنیم|ایدی|ریپلی]` _انتخاب مالک گروه(قابل انتخاب چند مالک)_ *حذف مالک* `[یوزرنیم|ایدی|ریپلی]` _حذف کردن فرد از فهرست مالکان گروه_ *مدیر* `[یوزرنیم|ایدی|ریپلی]` _ارتقا مقام کاربر به مدیر گروه_ *حذف مدیر* `[یوزرنیم|ایدی|ریپلی]` _تنزیل مقام مدیر به کاربر_ *تنظیم پیام مکرر* `[2-50]` _تنظیم حداکثر تعداد پیام مکرر_ *حداکثر حروف مجاز* `[عدد]` _تنظیم حداکثر کاراکتر پیام مکرر_ *تنظیم زمان بررسی* `[1-10]` _تنظیم زمان ارسال پیام مکرر_ *سکوت* `[یوزرنیم|ایدی|ریپلی]` _بیصدا کردن کاربر در گروه_ *حذف سکوت* `[یوزرنیم|ایدی|ریپلی]` _در آوردن کاربر از حالت بیصدا در گروه_ *اخراج* `[یوزرنیم|ایدی|ریپلی]` _حذف کاربر از گروه_ *بن* `[یوزرنیم|ایدی|ریپلی]` _مسدود کردن کاربر از گروه_ *حذف بن* `[یوزرنیم|ایدی|ریپلی]` _در آوردن از حالت مسدودیت کاربر از گروه_ *کاربری* `[یوزرنیم]` _نمایش شناسه کاربر_ *ایدی* `[ریپلی]` _نمایش شناسه کاربر_ *شناسه* `[ایدی]` _نمایش نام کاربر, نام کاربری و اطلاعات حساب_ *قفل* `[لینک | ورود | تگ | ویرایش | عربی | وب | ربات |هرزنامه | پیام مکرر | فونت | فراخوانی | سنجاق]` _در صورت قفل بودن فعالیت ها, ربات آنهارا حذف خواهد کرد_ *باز کردن* `[لینک | ورود | تگ | ویرایش | عربی | وب | ربات |هرزنامه | پیام مکرر | فونت | فراخوانی | سنجاق]` _در صورت قفل نبودن فعالیت ها, ربات آنهارا حذف نخواهد کرد_ *بیصدا* `[همه | تصاویر متحرک | عکس | اسناد | برچسب | صفحه کلید | فیلم | متن | نقل قول | موقعیت | اهنگ | صدا | مخاطب | کیبورد شیشه ای|بازی|خدمات تلگرام]` _در صورت بیصدا بودن فعالیت ها, ربات آنهارا حذف خواهد کرد_ *باصدا* `[همه | تصاویر متحرک | عکس | اسناد | برچسب | صفحه کلید | فیلم | متن | نقل قول | موقعیت | اهنگ | صدا | مخاطب | کیبورد شیشه ای|بازی|خدمات تلگرام]` _در صورت بیصدا نبودن فعالیت ها, ربات آنهارا حذف نخواهد کرد_ *تنظیم*`[قوانین | نام | لینک | درباره | خوشامد]` _ربات آنهارا ثبت خواهد کرد_ *پاک کردن* `[بن | مدیران | ربات | قوانین | درباره | لیست سکوت | خوشامد]` _ربات آنهارا پاک خواهد کرد_ *لیست سفید* `[+|-]` `[یوزرنیم|ایدی|ریپلی]` _افزودن افراد به لیست سفید_ *فیلتر* `[کلمه]` _فیلتر‌کلمه مورد نظر_ *حذف فیلتر* `[کلمه]` _ازاد کردن کلمه مورد نظر_ *سنجاق* `[reply]` _ربات پیام شمارا در گروه سنجاق خواهد کرد_ *حذف سنجاق* _ربات پیام سنجاق شده در گروه را حذف خواهد کرد_ *!خوشامد فعال/غیرفعال* _فعال یا غیرفعال کردن خوشامد گویی_ *تنظیمات* _نمایش تنظیمات گروه_ *لیست بیصدا* _نمایش فهرست بیصدا های گروه_ *لیست سکوت* _نمایش فهرست افراد بیصدا_ *لیست فیلتر* _نمایش لیست کلمات فیلتر شده_ *لیست سفید* _نمایش افراد سفید شده از گروه_ *لیست بن* _نمایش افراد مسدود شده از گروه_ *لیست مالکان* _نمایش فهرست مالکان گروه_ *لیست مدیران* _نمایش فهرست مدیران گروه_ *قوانین* _نمایش قوانین گروه_ *درباره* _نمایش درباره گروه_ *ایدی* _نمایش شناسه شما و گروه_ *اطلاعات گروه* _نمایش اطلاعات گروه_ *لینک جدید* _ساخت لینک جدید_ *لینک* _نمایش لینک گروه_ *تنظیم لینک* _تنظیم لینک جدید برای گروه_ *لینک خصوصی* _ارسال لینک گروه به چت خصوصی شما_ *زبان انگلیسی* _تنظیم زبان انگلیسی_ *زبان فارسی* _تنظیم زبان فارسی_ *دستورات انگلیسی* _تنظیم دستورات انگلیسی_ *دستورات فارسی* _تنظیم دستورات فارسی_ *تنظیم خوشامد [متن]* _ثبت پیام خوش آمد گویی_ *راهنمای ابزار* _نمایش راهنمای ابزار_ *راهنمای سرگرمی* _نمایش راهنمای سرگرمی_ _این راهنما فقط برای مدیران/مالکان گروه میباشد! این به این معناست که فقط مدیران/مالکان گروه میتوانند از دستورات بالا استفاده کنند!_ *موفق باشید ;)*]] end return text..msg_caption end --------------------- Welcome ----------------------- if ((matches[1] == "welcome" and not Clang) or (matches[1] == "خوشامد" and Clang)) and is_mod(msg) then if ((matches[2] == "enable" and not Clang) or (matches[2] == "فعال" and Clang)) then welcome = data[tostring(chat)]['settings']['welcome'] if welcome == "yes" then if not lang then return "_Group_ *welcome* _is already enabled_" elseif lang then return "_خوشآمد گویی از قبل فعال بود_" end else data[tostring(chat)]['settings']['welcome'] = "yes" save_data(_config.moderation.data, data) if not lang then return "_Group_ *welcome* _has been enabled_" elseif lang then return "_خوشآمد گویی فعال شد_" end end end if ((matches[2] == "disable" and not Clang) or (matches[2] == "غیرفعال" and Clang)) then welcome = data[tostring(chat)]['settings']['welcome'] if welcome == "no" then if not lang then return "_Group_ *Welcome* _is already disabled_" elseif lang then return "_خوشآمد گویی از قبل فعال نبود_" end else data[tostring(chat)]['settings']['welcome'] = "no" save_data(_config.moderation.data, data) if not lang then return "_Group_ *welcome* _has been disabled_" elseif lang then return "_خوشآمد گویی غیرفعال شد_" end end end end if ((matches[1] == "setwelcome" and not Clang) or (matches[1] == "تنظیم خوشامد" and Clang)) and matches[2] and is_mod(msg) then data[tostring(chat)]['setwelcome'] = matches[2] save_data(_config.moderation.data, data) if not lang then return "_Welcome Message Has Been Set To :_\n*"..matches[2].."*\n\n*You can use :*\n_{gpname} Group Name_\n_{rules} ➣ Show Group Rules_\n_{time} ➣ Show time english _\n_{date} ➣ Show date english _\n_{timefa} ➣ Show time persian _\n_{datefa} ➣ show date persian _\n_{name} ➣ New Member First Name_\n_{username} ➣ New Member Username_"..msg_caption else return "_پیام خوشآمد گویی تنظیم شد به :_\n*"..matches[2].."*\n\n*شما میتوانید از*\n_{gpname} نام گروه_\n_{rules} ➣ نمایش قوانین گروه_\n_{time} ➣ ساعت به زبان انگلیسی _\n_{date} ➣ تاریخ به زبان انگلیسی _\n_{timefa} ➣ ساعت به زبان فارسی _\n_{datefa} ➣ تاریخ به زبان فارسی _\n_{name} ➣ نام کاربر جدید_\n_{username} ➣ نام کاربری کاربر جدید_\n_استفاده کنید_"..msg_caption end end end end ----------------------------------------- local checkmod = true local function pre_process(msg) local chat = msg.to.id local user = msg.from.id local hash = "gp_lang:"..chat local lang = redis:get(hash) local data = load_data(_config.moderation.data) if checkmod and msg.text and msg.to.type == 'channel' then checkmod = false tdcli.getChannelMembers(msg.to.id, 0, 'Administrators', 200, function(a, b) local secchk = true for k,v in pairs(b.members_) do if v.user_id_ == tonumber(our_id) then secchk = false end end if secchk then checkmod = false if not lang then return tdcli.sendMessage(msg.to.id, 0, 1, '_Robot isn\'t Administrator, Please promote to Admin!_', 1, "md") else return tdcli.sendMessage(msg.to.id, 0, 1, '_لطفا برای کارکرد کامل دستورات، ربات را به مدیر گروه ارتقا دهید._', 1, "md") end end end, nil) end local function welcome_cb(arg, data) local url , res = http.request('http://irapi.ir/time/') if res ~= 200 then return "No connection" end local jdat = json:decode(url) administration = load_data(_config.moderation.data) if administration[arg.chat_id]['setwelcome'] then welcome = administration[arg.chat_id]['setwelcome'] else if not lang then welcome = "*Welcome Dude*" elseif lang then welcome = "_خوش آمدید_" end end if administration[tostring(arg.chat_id)]['rules'] then rules = administration[arg.chat_id]['rules'] else if not lang then rules = "ℹ️ The Default Rules :\n1⃣ No Flood.\n2⃣ No Spam.\n3⃣ No Advertising.\n4⃣ Try to stay on topic.\n5⃣ Forbidden any racist, sexual, homophobic or gore content.\n➡️ Repeated failure to comply with these rules will cause ban.\n@TeleJavidBot" elseif lang then rules = "ℹ️ قوانین پپیشفرض:\n1⃣ ارسال پیام مکرر ممنوع.\n2⃣ اسپم ممنوع.\n3⃣ تبلیغ ممنوع.\n4⃣ سعی کنید از موضوع خارج نشید.\n5⃣ هرنوع نژاد پرستی, شاخ بازی و پورنوگرافی ممنوع .\n➡️ از قوانین پیروی کنید, در صورت عدم رعایت قوانین اول اخطار و در صورت تکرار مسدود.\n@TeleJavidBot" end end if data.username_ then user_name = "@"..check_markdown(data.username_) else user_name = "" end local welcome = welcome:gsub("{rules}", rules) local welcome = welcome:gsub("{name}", check_markdown(data.first_name_..' '..(data.last_name_ or ''))) local welcome = welcome:gsub("{username}", user_name) local welcome = welcome:gsub("{time}", jdat.ENtime) local welcome = welcome:gsub("{date}", jdat.ENdate) local welcome = welcome:gsub("{timefa}", jdat.FAtime) local welcome = welcome:gsub("{datefa}", jdat.FAdate) local welcome = welcome:gsub("{gpname}", arg.gp_name) tdcli.sendMessage(arg.chat_id, arg.msg_id, 0, welcome, 0, "md") end if data[tostring(chat)] and data[tostring(chat)]['settings'] then if msg.adduser then welcome = data[tostring(msg.to.id)]['settings']['welcome'] if welcome == "yes" then tdcli.getUser(msg.adduser, welcome_cb, {chat_id=chat,msg_id=msg.id_,gp_name=msg.to.title}) else return false end end if msg.joinuser then welcome = data[tostring(msg.to.id)]['settings']['welcome'] if welcome == "yes" then tdcli.getUser(msg.sender_user_id_, welcome_cb, {chat_id=chat,msg_id=msg.id_,gp_name=msg.to.title}) else return false end end end end return { patterns ={ "^(id)$", "^(id) (.*)$", "^(pin)$", "^(unpin)$", "^(gpinfo)$", "^(test)$", "^(add)$", "^(rem)$", "^(option)$", "^(whitelist) ([+-])$", "^(whitelist) ([+-]) (.*)$", "^[#!/](whitelist)$", "^(setowner)$", "^(setowner) (.*)$", "^(remowner)$", "^(remowner) (.*)$", "^(promote)$", "^(promote) (.*)$", "^(demote)$", "^(demote) (.*)$", "^(modlist)$", "^(ownerlist)$", "^(lock) (.*)$", "^(unlock) (.*)$", "^(settings)$", "^(mutelist)$", "^(mute) (.*)$", "^(unmute) (.*)$", "^(link)$", "^(linkpv)$", "^(setlink)$", "^(newlink)$", "^(rules)$", "^(setrules) (.*)$", "^(about)$", "^(setabout) (.*)$", "^(setname) (.*)$", "^(clean) (.*)$", "^(setflood) (%d+)$", "^(setchar) (%d+)$", "^(setfloodtime) (%d+)$", "^(res) (.*)$", "^(whois) (%d+)$", "^(help)$", "^(setlang) (.*)$", "^(setcmd) (.*)$", "^(filter) (.*)$", "^(unfilter) (.*)$", "^(filterlist)$", "^([https?://w]*.?t.me/joinchat/%S+)$", "^([https?://w]*.?telegram.me/joinchat/%S+)$", "^(setwelcome) (.*)", "^(welcome) (.*)$", "^(زبان) (.*)$", "^(دستورات انگلیسی)$", "^(ایدی)$", "^(ایدی) (.*)$", '^(تنظیمات)$', '^(تنظیمات کلی)$', '^(سنجاق)$', '^(حذف سنجاق)$', '^(افزودن)$', '^(حذف گروه)$', '^(ادمین گروه)$', '^(ادمین گروه) (.*)$', '^(حذف ادمین گروه) (.*)$', '^(حذف ادمین گروه)$', '^(لیست سفید) ([+-]) (.*)$', '^(لیست سفید) ([+-])$', '^(لیست سفید)$', '^(مالک)$', '^(مالک) (.*)$', '^(حذف مالک) (.*)$', '^(حذف مالک)$', '^(مدیر)$', '^(مدیر) (.*)$', '^(حذف مدیر)$', '^(حذف مدیر) (.*)$', '^(قفل) (.*)$', '^(باز کردن) (.*)$', '^(بیصدا) (.*)$', '^(باصدا) (.*)$', '^(لینک جدید)$', '^(لینک جدید) (خصوصی)$', '^(اطلاعات گروه)$', '^(دستورات) (.*)$', '^(قوانین)$', '^(لینک)$', '^(تنظیم لینک)$', '^(تنظیم قوانین) (.*)$', '^(لینک) (خصوصی)$', '^(کاربری) (.*)$', '^(شناسه) (%d+)$', '^(تنظیم پیام مکرر) (%d+)$', '^(تنظیم زمان بررسی) (%d+)$', '^(حداکثر حروف مجاز) (%d+)$', '^(پاک کردن) (.*)$', '^(درباره)$', '^(تنظیم نام) (.*)$', '^(تنظیم درباره) (.*)$', '^(لیست فیلتر)$', '^(لیست بیصدا)$', '^(لیست مالکان)$', '^(لیست مدیران)$', '^(راهنما)$', '^(فیلتر) (.*)$', '^(حذف فیلتر) (.*)$', '^(خوشامد) (.*)$', '^(تنظیم خوشامد) (.*)$', }, run=run, pre_process = pre_process } --end groupmanager.lua #Javid_Team#
gpl-3.0
ZenityRTS/Zenity
lups/ParticleClasses/UnitPieceLight.lua
1
10283
-- $Id: UnitPieceLight.lua 3171 2008-11-06 09:06:29Z det $ ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- local UnitPieceLight = {} UnitPieceLight.__index = UnitPieceLight local depthtex, offscreentex, blurtex local offscreen4, offscreen8 local blur4, blur8 local depthShader local blurShader local uniformScreenXY, uniformPixelSize, uniformDirection local GL_DEPTH_BITS = 0x0D56 local GL_DEPTH_COMPONENT = 0x1902 local GL_DEPTH_COMPONENT16 = 0x81A5 local GL_DEPTH_COMPONENT24 = 0x81A6 local GL_DEPTH_COMPONENT32 = 0x81A7 ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitPieceLight.GetInfo() return { name = "UnitPieceLight", backup = "", --// backup class, if this class doesn't work (old cards,ati's,etc.) desc = "", layer = 32, --// extreme simply z-ordering :x --// gfx requirement fbo = true, shader = true, rtt = true, ctt = true, ms = 0, } end UnitPieceLight.Default = { layer = 32, life = math.huge, worldspace = true, piecenum = 0, colormap = { {1,1,1,0} }, repeatEffect = true, --// internal color = {1,1,1,0}, } ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitPieceLight:BeginDraw() gl.CopyToTexture(depthtex, 0, 0, 0, 0, vsx, vsy) gl.Texture(depthtex) gl.UseShader(depthShader) gl.Uniform(uniformScreenXY, math.ceil(vsx*0.5),math.ceil(vsy*0.5) ) gl.RenderToTexture(offscreentex, gl.Clear, GL.COLOR_BUFFER_BIT ,0,0,0,0) end function UnitPieceLight:EndDraw() gl.Color(1,1,1,1) gl.UseShader(0) gl.RenderToTexture(offscreen4, function() gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) gl.Texture(offscreentex) gl.TexRect(-1,1,1,-1) end) gl.Texture(offscreentex) gl.UseShader(blurShader) gl.RenderToTexture(blurtex, function() gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) gl.Uniform(uniformDirection, 1,0 ) gl.Uniform(uniformPixelSize, 1.0/math.ceil(vsx*0.5) ) gl.TexRect(-1-0.25/vsx,1+0.25/vsy,1+0.25/vsx,-1-0.25/vsy) end) gl.Texture(blurtex) gl.RenderToTexture(offscreentex, function() gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) gl.Uniform(uniformDirection, 0,1 ) gl.Uniform(uniformPixelSize, math.ceil(vsy*0.5) ) gl.TexRect(-1-0.25/vsx,1+0.25/vsy,1+0.25/vsx,-1-0.25/vsy) end) gl.Texture(offscreen4) gl.RenderToTexture(blur4, function() gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) gl.Uniform(uniformDirection, 1,0 ) gl.Uniform(uniformPixelSize, 1.0/math.ceil(vsx*0.25) ) gl.TexRect(-1-0.125/vsx,1+0.125/vsy,1+0.125/vsx,-1-0.125/vsy) end) gl.Texture(blur4) gl.RenderToTexture(offscreen4, function() gl.Clear(GL.COLOR_BUFFER_BIT,0,0,0,0) gl.Uniform(uniformDirection, 0,1 ) gl.Uniform(uniformPixelSize, 1.0/math.ceil(vsy*0.25) ) gl.TexRect(-1-0.125/vsx,1+0.125/vsy,1+0.125/vsx,-1-0.125/vsy) end) gl.UseShader(0) gl.Blending(GL.ONE,GL.ONE) gl.MatrixMode(GL.PROJECTION); gl.PushMatrix(); gl.LoadIdentity() gl.MatrixMode(GL.MODELVIEW); gl.PushMatrix(); gl.LoadIdentity() gl.Texture(offscreentex) gl.TexRect(-1-0.5/vsx,1+0.5/vsy,1+0.5/vsx,-1-0.5/vsy) gl.Texture(offscreen4) gl.TexRect(-1-0.5/vsx,1+0.5/vsy,1+0.5/vsx,-1-0.5/vsy) gl.MatrixMode(GL.PROJECTION); gl.PopMatrix() gl.MatrixMode(GL.MODELVIEW); gl.PopMatrix() gl.Blending(GL.SRC_ALPHA, GL.ONE_MINUS_SRC_ALPHA) gl.Texture(false) gl.UseShader(0) end function UnitPieceLight:Draw() gl.Color(self.color) gl.RenderToTexture(offscreentex, function() gl.PushMatrix() gl.ResetMatrices() gl.UnitMultMatrix(self.unit) gl.UnitPieceMultMatrix(self.unit,self.piecenum) gl.UnitPiece(self.unit,self.piecenum) gl.PopMatrix() end) end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitPieceLight:Update() self.life = self.life + self.life_incr self.color = {GetColor(self.colormap,self.life)} end -- used if repeatEffect=true; function UnitPieceLight:ReInitialize() self.life = 0 self.dieGameFrame = self.dieGameFrame + self.clife end function UnitPieceLight.Initialize() depthShader = gl.CreateShader({ fragment = [[ uniform sampler2D tex0; uniform vec2 screenXY; void main(void) { vec2 texCoord = vec2( gl_FragCoord.x/screenXY.x , gl_FragCoord.y/screenXY.y ); float depth = texture2D(tex0, texCoord ).z; if (depth <= gl_FragCoord.z-0.0005) { discard; } gl_FragColor = gl_Color; } ]], uniformInt = { tex0 = 0, }, uniform = { screenXY = {math.ceil(vsx*0.5),math.ceil(vsy*0.5)}, }, }) if (depthShader == nil) then print(PRIO_MAJOR,"LUPS->UnitPieceLights: Critical Shader Error: DepthShader: "..gl.GetShaderLog()) return false end blurShader = gl.CreateShader({ fragment = [[ float kernel[7]; uniform sampler2D tex0; uniform float pixelsize; uniform vec2 dir; void InitKernel(void) { kernel[0] = 0.013; kernel[1] = 0.054; kernel[2] = 0.069; kernel[3] = 0.129; kernel[4] = 0.212; kernel[5] = 0.301; kernel[6] = 0.372; } void main(void) { InitKernel(); vec2 texCoord = vec2(gl_TextureMatrix[0] * gl_TexCoord[0]); gl_FragColor = vec4(0.0); int n,i; i=1; for(n=6; n >= 0; --n){ gl_FragColor += kernel[n] * texture2D(tex0, texCoord.st + dir * float(i)*pixelsize ); ++i; } gl_FragColor += 0.4 * texture2D(tex0, texCoord ); i = -7; for(n=0; n <= 6; ++n){ gl_FragColor += kernel[n] * texture2D(tex0, texCoord.st + dir * float(i)*pixelsize ); ++i; } } ]], uniformInt = { tex0 = 0, pixelsize = 1.0/math.ceil(vsx*0.5), }, }) if (blurShader == nil) then print(PRIO_MAJOR,"LUPS->UnitPieceLights: Critical Shader Error: BlurShader: "..gl.GetShaderLog()) return false end uniformScreenXY = gl.GetUniformLocation(depthShader, 'screenXY') uniformPixelSize = gl.GetUniformLocation(blurShader, 'pixelsize') uniformDirection = gl.GetUniformLocation(blurShader, 'dir') UnitPieceLight.ViewResize(vsx, vsy) end function UnitPieceLight.Finalize() gl.DeleteTexture(depthtex) if (gl.DeleteTextureFBO) then gl.DeleteTextureFBO(offscreentex) gl.DeleteTextureFBO(blurtex) end if (gl.DeleteShader) then gl.DeleteShader(depthShader or 0) gl.DeleteShader(blurShader or 0) end end function UnitPieceLight.ViewResize(vsx, vsy) gl.DeleteTexture(depthtex or 0) gl.DeleteTextureFBO(offscreentex or 0) gl.DeleteTextureFBO(blurtex or 0) gl.DeleteTextureFBO(offscreen4 or 0) gl.DeleteTextureFBO(blur4 or 0) depthtex = gl.CreateTexture(vsx,vsy, { border = false, format = GL_DEPTH_COMPONENT24, min_filter = GL.NEAREST, mag_filter = GL.NEAREST, }) offscreentex = gl.CreateTexture(math.ceil(vsx*0.5),math.ceil(vsy*0.5), { border = false, min_filter = GL.LINEAR, mag_filter = GL.LINEAR, wrap_s = GL.CLAMP_TO_BORDER, wrap_t = GL.CLAMP_TO_BORDER, fbo = true, }) offscreen4 = gl.CreateTexture(math.ceil(vsx*0.25),math.ceil(vsy*0.25), { border = false, min_filter = GL.LINEAR, mag_filter = GL.LINEAR, wrap_s = GL.CLAMP_TO_BORDER, wrap_t = GL.CLAMP_TO_BORDER, fbo = true, }) blurtex = gl.CreateTexture(math.ceil(vsx*0.5),math.ceil(vsy*0.5), { border = false, min_filter = GL.LINEAR, mag_filter = GL.LINEAR, wrap_s = GL.CLAMP_TO_BORDER, wrap_t = GL.CLAMP_TO_BORDER, fbo = true, }) blur4 = gl.CreateTexture(math.ceil(vsx*0.25),math.ceil(vsy*0.25), { border = false, min_filter = GL.LINEAR, mag_filter = GL.LINEAR, wrap_s = GL.CLAMP_TO_BORDER, wrap_t = GL.CLAMP_TO_BORDER, fbo = true, }) end function UnitPieceLight:Visible() local ux,uy,uz = Spring.GetUnitViewPosition(self.unit) if not ux then return false end local pos = {0,0,0} pos[1],pos[2],pos[3] = pos[1]+ux,pos[2]+uy,pos[3]+uz local radius = 300 + Spring.GetUnitRadius(self.unit) local losState = Spring.GetUnitLosState(self.unit, LocalAllyTeamID) return (losState and losState.los)and(Spring.IsSphereInView(pos[1],pos[2],pos[3],radius)) end function UnitPieceLight:Valid() local ux = Spring.GetUnitViewPosition(self.unit) if (ux) then return true else return false end end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitPieceLight:CreateParticle() self.clife = self.life self.life_incr = 1/self.life self.life = 0 self.dieGameFrame = Spring.GetGameFrame() + self.clife end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- function UnitPieceLight.Create(Options) local newObject = MergeTable(Options, UnitPieceLight.Default) setmetatable(newObject,UnitPieceLight) -- make handle lookup newObject:CreateParticle() return newObject end function UnitPieceLight:Destroy() end ----------------------------------------------------------------------------------------------------------------- ----------------------------------------------------------------------------------------------------------------- return UnitPieceLight
gpl-2.0
umbrellaTG/sphero
libs/dkjson.lua
3282
26558
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.4* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.4"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.4" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
dani-sj/danyalevil
libs/dkjson.lua
3282
26558
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.4* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.4"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.4" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
jjimenezg93/ai-state_machines
moai/3rdparty/luasocket-2.0.2/samples/tinyirc.lua
58
2789
----------------------------------------------------------------------------- -- Select sample: simple text line server -- LuaSocket sample files. -- Author: Diego Nehab -- RCS ID: $Id: tinyirc.lua,v 1.14 2005/11/22 08:33:29 diego Exp $ ----------------------------------------------------------------------------- local socket = require("socket") host = host or "*" port1 = port1 or 8080 port2 = port2 or 8181 if arg then host = arg[1] or host port1 = arg[2] or port1 port2 = arg[3] or port2 end server1 = assert(socket.bind(host, port1)) server2 = assert(socket.bind(host, port2)) server1:settimeout(1) -- make sure we don't block in accept server2:settimeout(1) io.write("Servers bound\n") -- simple set implementation -- the select function doesn't care about what is passed to it as long as -- it behaves like a table -- creates a new set data structure function newset() local reverse = {} local set = {} return setmetatable(set, {__index = { insert = function(set, value) if not reverse[value] then table.insert(set, value) reverse[value] = table.getn(set) end end, remove = function(set, value) local index = reverse[value] if index then reverse[value] = nil local top = table.remove(set) if top ~= value then reverse[top] = index set[index] = top end end end }}) end set = newset() io.write("Inserting servers in set\n") set:insert(server1) set:insert(server2) while 1 do local readable, _, error = socket.select(set, nil) for _, input in ipairs(readable) do -- is it a server socket? if input == server1 or input == server2 then io.write("Waiting for clients\n") local new = input:accept() if new then new:settimeout(1) io.write("Inserting client in set\n") set:insert(new) end -- it is a client socket else local line, error = input:receive() if error then input:close() io.write("Removing client from set\n") set:remove(input) else io.write("Broadcasting line '", line, "'\n") writable, error = socket.skip(1, socket.select(nil, set, 1)) if not error then for __, output in ipairs(writable) do if output ~= input then output:send(line .. "\n") end end else io.write("No client ready to receive!!!\n") end end end end end
mit
kitala1/darkstar
scripts/zones/Northern_San_dOria/npcs/Pagisalis.lua
17
2921
----------------------------------- -- Area: Northern San d'Oria -- NPC: Pagisalis -- Involved In Quest: Enveloped in Darkness -- @zone 231 -- @pos ----------------------------------- package.loaded["scripts/zones/Northern_San_dOria/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/globals/shop"); require("scripts/globals/quests"); require("scripts/zones/Northern_San_dOria/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) if(player:getQuestStatus(SANDORIA,UNDYING_FLAMES) == QUEST_ACCEPTED) then if(trade:hasItemQty(913,2) and trade:getItemCount() == 2) then -- Trade Lump of Beeswax player:startEvent(0x0233); end end if(player:hasKeyItem(OLD_POCKET_WATCH) and player:hasKeyItem(OLD_BOOTS) == false) then if(trade:hasItemQty(828,1) and trade:getItemCount() == 1) then -- Trade Velvet Cloth player:startEvent(0x0025); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) sanFame = player:getFameLevel(SANDORIA); undyingFlames = player:getQuestStatus(SANDORIA,UNDYING_FLAMES); if(player:hasKeyItem(OLD_POCKET_WATCH)) then player:startEvent(0x0030); elseif(player:hasKeyItem(OLD_BOOTS)) then player:startEvent(0x003A); elseif(sanFame >= 2 and undyingFlames == QUEST_AVAILABLE) then player:startEvent(0x0232); elseif(undyingFlames == QUEST_ACCEPTED) then player:startEvent(0x0235); elseif(undyingFlames == QUEST_COMPLETED) then player:startEvent(0x0236); else player:startEvent(0x0234) end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0232 and option == 0) then player:addQuest(SANDORIA,UNDYING_FLAMES); elseif(csid == 0x0233) then if (player:getFreeSlotsCount() == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,13211); -- Friars Rope else player:tradeComplete(); player:addTitle(FAITH_LIKE_A_CANDLE); player:addItem(13211); player:messageSpecial(ITEM_OBTAINED,13211); -- Friars Rope player:addFame(SANDORIA,SAN_FAME*30); player:completeQuest(SANDORIA,UNDYING_FLAMES); end elseif(csid == 0x0025) then player:tradeComplete(); player:delKeyItem(OLD_POCKET_WATCH); player:addKeyItem(OLD_BOOTS); player:messageSpecial(KEYITEM_OBTAINED,OLD_BOOTS); end end;
gpl-3.0
aliyousefi8370/Srdarbot
libs/dkjson.lua
3282
26558
-- Module options: local always_try_using_lpeg = true local register_global_module_table = false local global_module_name = 'json' --[==[ David Kolf's JSON module for Lua 5.1/5.2 ======================================== *Version 2.4* In the default configuration this module writes no global values, not even the module table. Import it using json = require ("dkjson") In environments where `require` or a similiar function are not available and you cannot receive the return value of the module, you can set the option `register_global_module_table` to `true`. The module table will then be saved in the global variable with the name given by the option `global_module_name`. Exported functions and values: `json.encode (object [, state])` -------------------------------- Create a string representing the object. `Object` can be a table, a string, a number, a boolean, `nil`, `json.null` or any object with a function `__tojson` in its metatable. A table can only use strings and numbers as keys and its values have to be valid objects as well. It raises an error for any invalid data types or reference cycles. `state` is an optional table with the following fields: - `indent` When `indent` (a boolean) is set, the created string will contain newlines and indentations. Otherwise it will be one long line. - `keyorder` `keyorder` is an array to specify the ordering of keys in the encoded output. If an object has keys which are not in this array they are written after the sorted keys. - `level` This is the initial level of indentation used when `indent` is set. For each level two spaces are added. When absent it is set to 0. - `buffer` `buffer` is an array to store the strings for the result so they can be concatenated at once. When it isn't given, the encode function will create it temporary and will return the concatenated result. - `bufferlen` When `bufferlen` is set, it has to be the index of the last element of `buffer`. - `tables` `tables` is a set to detect reference cycles. It is created temporary when absent. Every table that is currently processed is used as key, the value is `true`. When `state.buffer` was set, the return value will be `true` on success. Without `state.buffer` the return value will be a string. `json.decode (string [, position [, null]])` -------------------------------------------- Decode `string` starting at `position` or at 1 if `position` was omitted. `null` is an optional value to be returned for null values. The default is `nil`, but you could set it to `json.null` or any other value. The return values are the object or `nil`, the position of the next character that doesn't belong to the object, and in case of errors an error message. Two metatables are created. Every array or object that is decoded gets a metatable with the `__jsontype` field set to either `array` or `object`. If you want to provide your own metatables use the syntax json.decode (string, position, null, objectmeta, arraymeta) To prevent the assigning of metatables pass `nil`: json.decode (string, position, null, nil) `<metatable>.__jsonorder` ------------------------- `__jsonorder` can overwrite the `keyorder` for a specific table. `<metatable>.__jsontype` ------------------------ `__jsontype` can be either `"array"` or `"object"`. This value is only checked for empty tables. (The default for empty tables is `"array"`). `<metatable>.__tojson (self, state)` ------------------------------------ You can provide your own `__tojson` function in a metatable. In this function you can either add directly to the buffer and return true, or you can return a string. On errors nil and a message should be returned. `json.null` ----------- You can use this value for setting explicit `null` values. `json.version` -------------- Set to `"dkjson 2.4"`. `json.quotestring (string)` --------------------------- Quote a UTF-8 string and escape critical characters using JSON escape sequences. This function is only necessary when you build your own `__tojson` functions. `json.addnewline (state)` ------------------------- When `state.indent` is set, add a newline to `state.buffer` and spaces according to `state.level`. LPeg support ------------ When the local configuration variable `always_try_using_lpeg` is set, this module tries to load LPeg to replace the `decode` function. The speed increase is significant. You can get the LPeg module at <http://www.inf.puc-rio.br/~roberto/lpeg/>. When LPeg couldn't be loaded, the pure Lua functions stay active. In case you don't want this module to require LPeg on its own, disable the option `always_try_using_lpeg` in the options section at the top of the module. In this case you can later load LPeg support using ### `json.use_lpeg ()` Require the LPeg module and replace the functions `quotestring` and and `decode` with functions that use LPeg patterns. This function returns the module table, so you can load the module using: json = require "dkjson".use_lpeg() Alternatively you can use `pcall` so the JSON module still works when LPeg isn't found. json = require "dkjson" pcall (json.use_lpeg) ### `json.using_lpeg` This variable is set to `true` when LPeg was loaded successfully. --------------------------------------------------------------------- Contact ------- You can contact the author by sending an e-mail to 'david' at the domain 'dkolf.de'. --------------------------------------------------------------------- *Copyright (C) 2010-2013 David Heiko Kolf* Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. <!-- This documentation can be parsed using Markdown to generate HTML. The source code is enclosed in a HTML comment so it won't be displayed by browsers, but it should be removed from the final HTML file as it isn't a valid HTML comment (and wastes space). --> <!--]==] -- global dependencies: local pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset = pairs, type, tostring, tonumber, getmetatable, setmetatable, rawset local error, require, pcall, select = error, require, pcall, select local floor, huge = math.floor, math.huge local strrep, gsub, strsub, strbyte, strchar, strfind, strlen, strformat = string.rep, string.gsub, string.sub, string.byte, string.char, string.find, string.len, string.format local strmatch = string.match local concat = table.concat local json = { version = "dkjson 2.4" } if register_global_module_table then _G[global_module_name] = json end local _ENV = nil -- blocking globals in Lua 5.2 pcall (function() -- Enable access to blocked metatables. -- Don't worry, this module doesn't change anything in them. local debmeta = require "debug".getmetatable if debmeta then getmetatable = debmeta end end) json.null = setmetatable ({}, { __tojson = function () return "null" end }) local function isarray (tbl) local max, n, arraylen = 0, 0, 0 for k,v in pairs (tbl) do if k == 'n' and type(v) == 'number' then arraylen = v if v > max then max = v end else if type(k) ~= 'number' or k < 1 or floor(k) ~= k then return false end if k > max then max = k end n = n + 1 end end if max > 10 and max > arraylen and max > n * 2 then return false -- don't create an array with too many holes end return true, max end local escapecodes = { ["\""] = "\\\"", ["\\"] = "\\\\", ["\b"] = "\\b", ["\f"] = "\\f", ["\n"] = "\\n", ["\r"] = "\\r", ["\t"] = "\\t" } local function escapeutf8 (uchar) local value = escapecodes[uchar] if value then return value end local a, b, c, d = strbyte (uchar, 1, 4) a, b, c, d = a or 0, b or 0, c or 0, d or 0 if a <= 0x7f then value = a elseif 0xc0 <= a and a <= 0xdf and b >= 0x80 then value = (a - 0xc0) * 0x40 + b - 0x80 elseif 0xe0 <= a and a <= 0xef and b >= 0x80 and c >= 0x80 then value = ((a - 0xe0) * 0x40 + b - 0x80) * 0x40 + c - 0x80 elseif 0xf0 <= a and a <= 0xf7 and b >= 0x80 and c >= 0x80 and d >= 0x80 then value = (((a - 0xf0) * 0x40 + b - 0x80) * 0x40 + c - 0x80) * 0x40 + d - 0x80 else return "" end if value <= 0xffff then return strformat ("\\u%.4x", value) elseif value <= 0x10ffff then -- encode as UTF-16 surrogate pair value = value - 0x10000 local highsur, lowsur = 0xD800 + floor (value/0x400), 0xDC00 + (value % 0x400) return strformat ("\\u%.4x\\u%.4x", highsur, lowsur) else return "" end end local function fsub (str, pattern, repl) -- gsub always builds a new string in a buffer, even when no match -- exists. First using find should be more efficient when most strings -- don't contain the pattern. if strfind (str, pattern) then return gsub (str, pattern, repl) else return str end end local function quotestring (value) -- based on the regexp "escapable" in https://github.com/douglascrockford/JSON-js value = fsub (value, "[%z\1-\31\"\\\127]", escapeutf8) if strfind (value, "[\194\216\220\225\226\239]") then value = fsub (value, "\194[\128-\159\173]", escapeutf8) value = fsub (value, "\216[\128-\132]", escapeutf8) value = fsub (value, "\220\143", escapeutf8) value = fsub (value, "\225\158[\180\181]", escapeutf8) value = fsub (value, "\226\128[\140-\143\168-\175]", escapeutf8) value = fsub (value, "\226\129[\160-\175]", escapeutf8) value = fsub (value, "\239\187\191", escapeutf8) value = fsub (value, "\239\191[\176-\191]", escapeutf8) end return "\"" .. value .. "\"" end json.quotestring = quotestring local function replace(str, o, n) local i, j = strfind (str, o, 1, true) if i then return strsub(str, 1, i-1) .. n .. strsub(str, j+1, -1) else return str end end -- locale independent num2str and str2num functions local decpoint, numfilter local function updatedecpoint () decpoint = strmatch(tostring(0.5), "([^05+])") -- build a filter that can be used to remove group separators numfilter = "[^0-9%-%+eE" .. gsub(decpoint, "[%^%$%(%)%%%.%[%]%*%+%-%?]", "%%%0") .. "]+" end updatedecpoint() local function num2str (num) return replace(fsub(tostring(num), numfilter, ""), decpoint, ".") end local function str2num (str) local num = tonumber(replace(str, ".", decpoint)) if not num then updatedecpoint() num = tonumber(replace(str, ".", decpoint)) end return num end local function addnewline2 (level, buffer, buflen) buffer[buflen+1] = "\n" buffer[buflen+2] = strrep (" ", level) buflen = buflen + 2 return buflen end function json.addnewline (state) if state.indent then state.bufferlen = addnewline2 (state.level or 0, state.buffer, state.bufferlen or #(state.buffer)) end end local encode2 -- forward declaration local function addpair (key, value, prev, indent, level, buffer, buflen, tables, globalorder) local kt = type (key) if kt ~= 'string' and kt ~= 'number' then return nil, "type '" .. kt .. "' is not supported as a key by JSON." end if prev then buflen = buflen + 1 buffer[buflen] = "," end if indent then buflen = addnewline2 (level, buffer, buflen) end buffer[buflen+1] = quotestring (key) buffer[buflen+2] = ":" return encode2 (value, indent, level, buffer, buflen + 2, tables, globalorder) end encode2 = function (value, indent, level, buffer, buflen, tables, globalorder) local valtype = type (value) local valmeta = getmetatable (value) valmeta = type (valmeta) == 'table' and valmeta -- only tables local valtojson = valmeta and valmeta.__tojson if valtojson then if tables[value] then return nil, "reference cycle" end tables[value] = true local state = { indent = indent, level = level, buffer = buffer, bufferlen = buflen, tables = tables, keyorder = globalorder } local ret, msg = valtojson (value, state) if not ret then return nil, msg end tables[value] = nil buflen = state.bufferlen if type (ret) == 'string' then buflen = buflen + 1 buffer[buflen] = ret end elseif value == nil then buflen = buflen + 1 buffer[buflen] = "null" elseif valtype == 'number' then local s if value ~= value or value >= huge or -value >= huge then -- This is the behaviour of the original JSON implementation. s = "null" else s = num2str (value) end buflen = buflen + 1 buffer[buflen] = s elseif valtype == 'boolean' then buflen = buflen + 1 buffer[buflen] = value and "true" or "false" elseif valtype == 'string' then buflen = buflen + 1 buffer[buflen] = quotestring (value) elseif valtype == 'table' then if tables[value] then return nil, "reference cycle" end tables[value] = true level = level + 1 local isa, n = isarray (value) if n == 0 and valmeta and valmeta.__jsontype == 'object' then isa = false end local msg if isa then -- JSON array buflen = buflen + 1 buffer[buflen] = "[" for i = 1, n do buflen, msg = encode2 (value[i], indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end if i < n then buflen = buflen + 1 buffer[buflen] = "," end end buflen = buflen + 1 buffer[buflen] = "]" else -- JSON object local prev = false buflen = buflen + 1 buffer[buflen] = "{" local order = valmeta and valmeta.__jsonorder or globalorder if order then local used = {} n = #order for i = 1, n do local k = order[i] local v = value[k] if v then used[k] = true buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) prev = true -- add a seperator before the next element end end for k,v in pairs (value) do if not used[k] then buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end else -- unordered for k,v in pairs (value) do buflen, msg = addpair (k, v, prev, indent, level, buffer, buflen, tables, globalorder) if not buflen then return nil, msg end prev = true -- add a seperator before the next element end end if indent then buflen = addnewline2 (level - 1, buffer, buflen) end buflen = buflen + 1 buffer[buflen] = "}" end tables[value] = nil else return nil, "type '" .. valtype .. "' is not supported by JSON." end return buflen end function json.encode (value, state) state = state or {} local oldbuffer = state.buffer local buffer = oldbuffer or {} updatedecpoint() local ret, msg = encode2 (value, state.indent, state.level or 0, buffer, state.bufferlen or 0, state.tables or {}, state.keyorder) if not ret then error (msg, 2) elseif oldbuffer then state.bufferlen = ret return true else return concat (buffer) end end local function loc (str, where) local line, pos, linepos = 1, 1, 0 while true do pos = strfind (str, "\n", pos, true) if pos and pos < where then line = line + 1 linepos = pos pos = pos + 1 else break end end return "line " .. line .. ", column " .. (where - linepos) end local function unterminated (str, what, where) return nil, strlen (str) + 1, "unterminated " .. what .. " at " .. loc (str, where) end local function scanwhite (str, pos) while true do pos = strfind (str, "%S", pos) if not pos then return nil end if strsub (str, pos, pos + 2) == "\239\187\191" then -- UTF-8 Byte Order Mark pos = pos + 3 else return pos end end end local escapechars = { ["\""] = "\"", ["\\"] = "\\", ["/"] = "/", ["b"] = "\b", ["f"] = "\f", ["n"] = "\n", ["r"] = "\r", ["t"] = "\t" } local function unichar (value) if value < 0 then return nil elseif value <= 0x007f then return strchar (value) elseif value <= 0x07ff then return strchar (0xc0 + floor(value/0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0xffff then return strchar (0xe0 + floor(value/0x1000), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) elseif value <= 0x10ffff then return strchar (0xf0 + floor(value/0x40000), 0x80 + (floor(value/0x1000) % 0x40), 0x80 + (floor(value/0x40) % 0x40), 0x80 + (floor(value) % 0x40)) else return nil end end local function scanstring (str, pos) local lastpos = pos + 1 local buffer, n = {}, 0 while true do local nextpos = strfind (str, "[\"\\]", lastpos) if not nextpos then return unterminated (str, "string", pos) end if nextpos > lastpos then n = n + 1 buffer[n] = strsub (str, lastpos, nextpos - 1) end if strsub (str, nextpos, nextpos) == "\"" then lastpos = nextpos + 1 break else local escchar = strsub (str, nextpos + 1, nextpos + 1) local value if escchar == "u" then value = tonumber (strsub (str, nextpos + 2, nextpos + 5), 16) if value then local value2 if 0xD800 <= value and value <= 0xDBff then -- we have the high surrogate of UTF-16. Check if there is a -- low surrogate escaped nearby to combine them. if strsub (str, nextpos + 6, nextpos + 7) == "\\u" then value2 = tonumber (strsub (str, nextpos + 8, nextpos + 11), 16) if value2 and 0xDC00 <= value2 and value2 <= 0xDFFF then value = (value - 0xD800) * 0x400 + (value2 - 0xDC00) + 0x10000 else value2 = nil -- in case it was out of range for a low surrogate end end end value = value and unichar (value) if value then if value2 then lastpos = nextpos + 12 else lastpos = nextpos + 6 end end end end if not value then value = escapechars[escchar] or escchar lastpos = nextpos + 2 end n = n + 1 buffer[n] = value end end if n == 1 then return buffer[1], lastpos elseif n > 1 then return concat (buffer), lastpos else return "", lastpos end end local scanvalue -- forward declaration local function scantable (what, closechar, str, startpos, nullval, objectmeta, arraymeta) local len = strlen (str) local tbl, n = {}, 0 local pos = startpos + 1 if what == 'object' then setmetatable (tbl, objectmeta) else setmetatable (tbl, arraymeta) end while true do pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end local char = strsub (str, pos, pos) if char == closechar then return tbl, pos + 1 end local val1, err val1, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) if char == ":" then if val1 == nil then return nil, pos, "cannot use nil as table index (at " .. loc (str, pos) .. ")" end pos = scanwhite (str, pos + 1) if not pos then return unterminated (str, what, startpos) end local val2 val2, pos, err = scanvalue (str, pos, nullval, objectmeta, arraymeta) if err then return nil, pos, err end tbl[val1] = val2 pos = scanwhite (str, pos) if not pos then return unterminated (str, what, startpos) end char = strsub (str, pos, pos) else n = n + 1 tbl[n] = val1 end if char == "," then pos = pos + 1 end end end scanvalue = function (str, pos, nullval, objectmeta, arraymeta) pos = pos or 1 pos = scanwhite (str, pos) if not pos then return nil, strlen (str) + 1, "no valid JSON value (reached the end)" end local char = strsub (str, pos, pos) if char == "{" then return scantable ('object', "}", str, pos, nullval, objectmeta, arraymeta) elseif char == "[" then return scantable ('array', "]", str, pos, nullval, objectmeta, arraymeta) elseif char == "\"" then return scanstring (str, pos) else local pstart, pend = strfind (str, "^%-?[%d%.]+[eE]?[%+%-]?%d*", pos) if pstart then local number = str2num (strsub (str, pstart, pend)) if number then return number, pend + 1 end end pstart, pend = strfind (str, "^%a%w*", pos) if pstart then local name = strsub (str, pstart, pend) if name == "true" then return true, pend + 1 elseif name == "false" then return false, pend + 1 elseif name == "null" then return nullval, pend + 1 end end return nil, pos, "no valid JSON value at " .. loc (str, pos) end end local function optionalmetatables(...) if select("#", ...) > 0 then return ... else return {__jsontype = 'object'}, {__jsontype = 'array'} end end function json.decode (str, pos, nullval, ...) local objectmeta, arraymeta = optionalmetatables(...) return scanvalue (str, pos, nullval, objectmeta, arraymeta) end function json.use_lpeg () local g = require ("lpeg") if g.version() == "0.11" then error "due to a bug in LPeg 0.11, it cannot be used for JSON matching" end local pegmatch = g.match local P, S, R = g.P, g.S, g.R local function ErrorCall (str, pos, msg, state) if not state.msg then state.msg = msg .. " at " .. loc (str, pos) state.pos = pos end return false end local function Err (msg) return g.Cmt (g.Cc (msg) * g.Carg (2), ErrorCall) end local Space = (S" \n\r\t" + P"\239\187\191")^0 local PlainChar = 1 - S"\"\\\n\r" local EscapeSequence = (P"\\" * g.C (S"\"\\/bfnrt" + Err "unsupported escape sequence")) / escapechars local HexDigit = R("09", "af", "AF") local function UTF16Surrogate (match, pos, high, low) high, low = tonumber (high, 16), tonumber (low, 16) if 0xD800 <= high and high <= 0xDBff and 0xDC00 <= low and low <= 0xDFFF then return true, unichar ((high - 0xD800) * 0x400 + (low - 0xDC00) + 0x10000) else return false end end local function UTF16BMP (hex) return unichar (tonumber (hex, 16)) end local U16Sequence = (P"\\u" * g.C (HexDigit * HexDigit * HexDigit * HexDigit)) local UnicodeEscape = g.Cmt (U16Sequence * U16Sequence, UTF16Surrogate) + U16Sequence/UTF16BMP local Char = UnicodeEscape + EscapeSequence + PlainChar local String = P"\"" * g.Cs (Char ^ 0) * (P"\"" + Err "unterminated string") local Integer = P"-"^(-1) * (P"0" + (R"19" * R"09"^0)) local Fractal = P"." * R"09"^0 local Exponent = (S"eE") * (S"+-")^(-1) * R"09"^1 local Number = (Integer * Fractal^(-1) * Exponent^(-1))/str2num local Constant = P"true" * g.Cc (true) + P"false" * g.Cc (false) + P"null" * g.Carg (1) local SimpleValue = Number + String + Constant local ArrayContent, ObjectContent -- The functions parsearray and parseobject parse only a single value/pair -- at a time and store them directly to avoid hitting the LPeg limits. local function parsearray (str, pos, nullval, state) local obj, cont local npos local t, nt = {}, 0 repeat obj, cont, npos = pegmatch (ArrayContent, str, pos, nullval, state) if not npos then break end pos = npos nt = nt + 1 t[nt] = obj until cont == 'last' return pos, setmetatable (t, state.arraymeta) end local function parseobject (str, pos, nullval, state) local obj, key, cont local npos local t = {} repeat key, obj, cont, npos = pegmatch (ObjectContent, str, pos, nullval, state) if not npos then break end pos = npos t[key] = obj until cont == 'last' return pos, setmetatable (t, state.objectmeta) end local Array = P"[" * g.Cmt (g.Carg(1) * g.Carg(2), parsearray) * Space * (P"]" + Err "']' expected") local Object = P"{" * g.Cmt (g.Carg(1) * g.Carg(2), parseobject) * Space * (P"}" + Err "'}' expected") local Value = Space * (Array + Object + SimpleValue) local ExpectedValue = Value + Space * Err "value expected" ArrayContent = Value * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local Pair = g.Cg (Space * String * Space * (P":" + Err "colon expected") * ExpectedValue) ObjectContent = Pair * Space * (P"," * g.Cc'cont' + g.Cc'last') * g.Cp() local DecodeValue = ExpectedValue * g.Cp () function json.decode (str, pos, nullval, ...) local state = {} state.objectmeta, state.arraymeta = optionalmetatables(...) local obj, retpos = pegmatch (DecodeValue, str, pos, nullval, state) if state.msg then return nil, state.pos, state.msg else return obj, retpos end end -- use this function only once: json.use_lpeg = function () return json end json.using_lpeg = true return json -- so you can get the module using json = require "dkjson".use_lpeg() end if always_try_using_lpeg then pcall (json.use_lpeg) end return json -->
gpl-2.0
kitala1/darkstar
scripts/zones/Crawlers_Nest/mobs/Aqrabuamelu.lua
21
1463
----------------------------------- -- Area: Maze of Shakhrami -- NM: Aqrabuamelu ----------------------------------- require("scripts/globals/status"); ----------------------------------- ----------------------------------- -- onMobInitialize Action ----------------------------------- function onMobInitialize(mob) mob:setMobMod(MOBMOD_AUTO_SPIKES,mob:getShortID()); mob:addStatusEffect(EFFECT_ICE_SPIKES,45,0,0); mob:getStatusEffect(EFFECT_ICE_SPIKES):setFlag(32); end; ----------------------------------- -- onSpikesDamage ----------------------------------- function onSpikesDamage(mob,target,damage) local INT_diff = mob:getStat(MOD_INT) - target:getStat(MOD_INT); if (INT_diff > 20) then INT_diff = 20 + (INT_diff - 20) / 2; end local dmg = INT_diff+damage/2; local params = {}; params.bonusmab = 0; params.includemab = false; dmg = addBonusesAbility(mob, ELE_ICE, target, dmg, params); dmg = dmg * applyResistanceAddEffect(mob,target,ELE_ICE,0); dmg = adjustForTarget(target,dmg,ELE_ICE); if (dmg < 0) then dmg = 10 end dmg = finalMagicNonSpellAdjustments(mob,target,ELE_ICE,dmg); return SUBEFFECT_ICE_SPIKES,44,dmg; end; ----------------------------------- -- onMobDeath ----------------------------------- function onMobDeath(mob, killer) UpdateNMSpawnPoint(mob:getID()); mob:setRespawnTime(math.random((7200),(7800))); -- 120 to 130 min end;
gpl-3.0
kitala1/darkstar
scripts/commands/togglegm.lua
26
1924
--------------------------------------------------------------------------------------------------- -- func: togglegm -- desc: Toggles a GMs nameflags/icon. --------------------------------------------------------------------------------------------------- cmdprops = { permission = 1, parameters = "" }; function onTrigger(player) -- GM Flag Definitions local FLAG_GM = 0x04000000; local FLAG_GM_SENIOR = 0x05000000; local FLAG_GM_LEAD = 0x06000000; local FLAG_GM_PRODUCER = 0x07000000; local FLAG_SENIOR = 0x01000000; -- Do NOT set these flags. These are here to local FLAG_LEAD = 0x02000000; -- ensure all GM status is removed. -- Configurable Options local MINLVL_GM = 1; -- For "whitelisting" players to have some commands, but not GM tier commands. local MINLVL_GM_SENIOR = 2; -- These are configurable so that commands may be restricted local MINLVL_GM_LEAD = 3; -- between different levels of GM's with the same icon. local MINLVL_GM_PRODUCER = 4; if (player:checkNameFlags(FLAG_GM)) then if (player:checkNameFlags(FLAG_GM)) then player:setFlag(FLAG_GM); end if (player:checkNameFlags(FLAG_SENIOR)) then player:setFlag(FLAG_SENIOR); end if (player:checkNameFlags(FLAG_LEAD)) then player:setFlag(FLAG_LEAD); end else local gmlvl = player:getGMLevel(); if (gmlvl >= MINLVL_GM_PRODUCER) then player:setFlag(FLAG_GM_PRODUCER); elseif (gmlvl >= MINLVL_GM_LEAD) then player:setFlag(FLAG_GM_LEAD); elseif (gmlvl >= MINLVL_GM_SENIOR) then player:setFlag(FLAG_GM_SENIOR); elseif (gmlvl >= MINLVL_GM) then player:setFlag(FLAG_GM); end end end
gpl-3.0
kitala1/darkstar
scripts/globals/items/sis_kebabi.lua
35
1656
----------------------------------------- -- ID: 5598 -- Item: sis_kebabi -- Food Effect: 30Min, All Races ----------------------------------------- -- Strength 6 -- Vitality -2 -- Intelligence -2 -- Attack % 20 -- Attack Cap 70 -- Ranged ATT % 20 -- Ranged ATT Cap 70 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,5598); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_STR, 6); target:addMod(MOD_VIT, -2); target:addMod(MOD_INT, -2); target:addMod(MOD_FOOD_ATTP, 20); target:addMod(MOD_FOOD_ATT_CAP, 70); target:addMod(MOD_FOOD_RATTP, 20); target:addMod(MOD_FOOD_RATT_CAP, 70); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_STR, 6); target:delMod(MOD_VIT, -2); target:delMod(MOD_INT, -2); target:delMod(MOD_FOOD_ATTP, 20); target:delMod(MOD_FOOD_ATT_CAP, 70); target:delMod(MOD_FOOD_RATTP, 20); target:delMod(MOD_FOOD_RATT_CAP, 70); end;
gpl-3.0
fastmailops/prosody
plugins/mod_storage_sql.lua
4
13370
--[[ DB Tables: Prosody - key-value, map | host | user | store | key | type | value | ProsodyArchive - list | host | user | store | key | time | stanzatype | jsonvalue | Mapping: Roster - Prosody | host | user | "roster" | "contactjid" | type | value | | host | user | "roster" | NULL | "json" | roster[false] data | Account - Prosody | host | user | "accounts" | "username" | type | value | Offline - ProsodyArchive | host | user | "offline" | "contactjid" | time | "message" | json|XML | ]] local type = type; local tostring = tostring; local tonumber = tonumber; local pairs = pairs; local next = next; local setmetatable = setmetatable; local xpcall = xpcall; local json = require "util.json"; local build_url = require"socket.url".build; local DBI; local connection; local host,user,store = module.host; local params = module:get_option("sql"); local dburi; local connections = module:shared "/*/sql/connection-cache"; local function db2uri(params) return build_url{ scheme = params.driver, user = params.username, password = params.password, host = params.host, port = params.port, path = params.database, }; end local resolve_relative_path = require "core.configmanager".resolve_relative_path; local function test_connection() if not connection then return nil; end if connection:ping() then return true; else module:log("debug", "Database connection closed"); connection = nil; connections[dburi] = nil; end end local function connect() if not test_connection() then prosody.unlock_globals(); local dbh, err = DBI.Connect( params.driver, params.database, params.username, params.password, params.host, params.port ); prosody.lock_globals(); if not dbh then module:log("debug", "Database connection failed: %s", tostring(err)); return nil, err; end module:log("debug", "Successfully connected to database"); dbh:autocommit(false); -- don't commit automatically connection = dbh; connections[dburi] = dbh; end return connection; end local function create_table() if not module:get_option("sql_manage_tables", true) then return; end local create_sql = "CREATE TABLE `prosody` (`host` TEXT, `user` TEXT, `store` TEXT, `key` TEXT, `type` TEXT, `value` TEXT);"; if params.driver == "PostgreSQL" then create_sql = create_sql:gsub("`", "\""); elseif params.driver == "MySQL" then create_sql = create_sql:gsub("`value` TEXT", "`value` MEDIUMTEXT"); end local stmt, err = connection:prepare(create_sql); if stmt then local ok = stmt:execute(); local commit_ok = connection:commit(); if ok and commit_ok then module:log("info", "Initialized new %s database with prosody table", params.driver); local index_sql = "CREATE INDEX `prosody_index` ON `prosody` (`host`, `user`, `store`, `key`)"; if params.driver == "PostgreSQL" then index_sql = index_sql:gsub("`", "\""); elseif params.driver == "MySQL" then index_sql = index_sql:gsub("`([,)])", "`(20)%1"); end local stmt, err = connection:prepare(index_sql); local ok, commit_ok, commit_err; if stmt then ok, err = stmt:execute(); commit_ok, commit_err = connection:commit(); end if not(ok and commit_ok) then module:log("warn", "Failed to create index (%s), lookups may not be optimised", err or commit_err); end elseif params.driver == "MySQL" then -- COMPAT: Upgrade tables from 0.8.0 -- Failed to create, but check existing MySQL table here local stmt = connection:prepare("SHOW COLUMNS FROM prosody WHERE Field='value' and Type='text'"); local ok = stmt:execute(); local commit_ok = connection:commit(); if ok and commit_ok then if stmt:rowcount() > 0 then module:log("info", "Upgrading database schema..."); local stmt = connection:prepare("ALTER TABLE prosody MODIFY COLUMN `value` MEDIUMTEXT"); local ok, err = stmt:execute(); local commit_ok = connection:commit(); if ok and commit_ok then module:log("info", "Database table automatically upgraded"); else module:log("error", "Failed to upgrade database schema (%s), please see " .."http://prosody.im/doc/mysql for help", err or "unknown error"); end end repeat until not stmt:fetch(); end end elseif params.driver ~= "SQLite3" then -- SQLite normally fails to prepare for existing table module:log("warn", "Prosody was not able to automatically check/create the database table (%s), " .."see http://prosody.im/doc/modules/mod_storage_sql#table_management for help.", err or "unknown error"); end end do -- process options to get a db connection local ok; prosody.unlock_globals(); ok, DBI = pcall(require, "DBI"); if not ok then package.loaded["DBI"] = {}; module:log("error", "Failed to load the LuaDBI library for accessing SQL databases: %s", DBI); module:log("error", "More information on installing LuaDBI can be found at http://prosody.im/doc/depends#luadbi"); end prosody.lock_globals(); if not ok or not DBI.Connect then return; -- Halt loading of this module end params = params or { driver = "SQLite3" }; if params.driver == "SQLite3" then params.database = resolve_relative_path(prosody.paths.data or ".", params.database or "prosody.sqlite"); end assert(params.driver and params.database, "Both the SQL driver and the database need to be specified"); dburi = db2uri(params); connection = connections[dburi]; assert(connect()); -- Automatically create table, ignore failure (table probably already exists) create_table(); end local function serialize(value) local t = type(value); if t == "string" or t == "boolean" or t == "number" then return t, tostring(value); elseif t == "table" then local value,err = json.encode(value); if value then return "json", value; end return nil, err; end return nil, "Unhandled value type: "..t; end local function deserialize(t, value) if t == "string" then return value; elseif t == "boolean" then if value == "true" then return true; elseif value == "false" then return false; end elseif t == "number" then return tonumber(value); elseif t == "json" then return json.decode(value); end end local function dosql(sql, ...) if params.driver == "PostgreSQL" then sql = sql:gsub("`", "\""); end -- do prepared statement stuff local stmt, err = connection:prepare(sql); if not stmt and not test_connection() then error("connection failed"); end if not stmt then module:log("error", "QUERY FAILED: %s %s", err, debug.traceback()); return nil, err; end -- run query local ok, err = stmt:execute(...); if not ok and not test_connection() then error("connection failed"); end if not ok then return nil, err; end return stmt; end local function getsql(sql, ...) return dosql(sql, host or "", user or "", store or "", ...); end local function setsql(sql, ...) local stmt, err = getsql(sql, ...); if not stmt then return stmt, err; end return stmt:affected(); end local function transact(...) -- ... end local function rollback(...) if connection then connection:rollback(); end -- FIXME check for rollback error? return ...; end local function commit(...) local success,err = connection:commit(); if not success then return nil, "SQL commit failed: "..tostring(err); end return ...; end local function keyval_store_get() local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?"); if not stmt then return rollback(nil, err); end local haveany; local result = {}; for row in stmt:rows(true) do haveany = true; local k = row.key; local v = deserialize(row.type, row.value); if k and v then if k ~= "" then result[k] = v; elseif type(v) == "table" then for a,b in pairs(v) do result[a] = b; end end end end return commit(haveany and result or nil); end local function keyval_store_set(data) local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=?"); if not affected then return rollback(affected, err); end if data and next(data) ~= nil then local extradata = {}; for key, value in pairs(data) do if type(key) == "string" and key ~= "" then local t, value = serialize(value); if not t then return rollback(t, value); end local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value); if not ok then return rollback(ok, err); end else extradata[key] = value; end end if next(extradata) ~= nil then local t, extradata = serialize(extradata); if not t then return rollback(t, extradata); end local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", "", t, extradata); if not ok then return rollback(ok, err); end end end return commit(true); end local keyval_store = {}; keyval_store.__index = keyval_store; function keyval_store:get(username) user,store = username,self.store; if not connection and not connect() then return nil, "Unable to connect to database"; end local success, ret, err = xpcall(keyval_store_get, debug.traceback); if not connection and connect() then success, ret, err = xpcall(keyval_store_get, debug.traceback); end if success then return ret, err; else return rollback(nil, ret); end end function keyval_store:set(username, data) user,store = username,self.store; if not connection and not connect() then return nil, "Unable to connect to database"; end local success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback); if not connection and connect() then success, ret, err = xpcall(function() return keyval_store_set(data); end, debug.traceback); end if success then return ret, err; else return rollback(nil, ret); end end function keyval_store:users() local stmt, err = dosql("SELECT DISTINCT `user` FROM `prosody` WHERE `host`=? AND `store`=?", host, self.store); if not stmt then return rollback(nil, err); end local next = stmt:rows(); return commit(function() local row = next(); return row and row[1]; end); end local function map_store_get(key) local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or ""); if not stmt then return rollback(nil, err); end local haveany; local result = {}; for row in stmt:rows(true) do haveany = true; local k = row.key; local v = deserialize(row.type, row.value); if k and v then if k ~= "" then result[k] = v; elseif type(v) == "table" then for a,b in pairs(v) do result[a] = b; end end end end return commit(haveany and result[key] or nil); end local function map_store_set(key, data) local affected, err = setsql("DELETE FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or ""); if not affected then return rollback(affected, err); end if data and next(data) ~= nil then if type(key) == "string" and key ~= "" then local t, value = serialize(data); if not t then return rollback(t, value); end local ok, err = setsql("INSERT INTO `prosody` (`host`,`user`,`store`,`key`,`type`,`value`) VALUES (?,?,?,?,?,?)", key, t, value); if not ok then return rollback(ok, err); end else -- TODO non-string keys end end return commit(true); end local map_store = {}; map_store.__index = map_store; function map_store:get(username, key) user,store = username,self.store; local success, ret, err = xpcall(function() return map_store_get(key); end, debug.traceback); if success then return ret, err; else return rollback(nil, ret); end end function map_store:set(username, key, data) user,store = username,self.store; local success, ret, err = xpcall(function() return map_store_set(key, data); end, debug.traceback); if success then return ret, err; else return rollback(nil, ret); end end local list_store = {}; list_store.__index = list_store; function list_store:scan(username, from, to, jid, typ) user,store = username,self.store; local cols = {"from", "to", "jid", "typ"}; local vals = { from , to , jid , typ }; local stmt, err; local query = "SELECT * FROM `prosodyarchive` WHERE `host`=? AND `user`=? AND `store`=?"; query = query.." ORDER BY time"; --local stmt, err = getsql("SELECT * FROM `prosody` WHERE `host`=? AND `user`=? AND `store`=? AND `key`=?", key or ""); return nil, "not-implemented" end local driver = {}; function driver:open(store, typ) if not typ then -- default key-value store return setmetatable({ store = store }, keyval_store); end return nil, "unsupported-store"; end function driver:stores(username) local sql = "SELECT DISTINCT `store` FROM `prosody` WHERE `host`=? AND `user`" .. (username == true and "!=?" or "=?"); if username == true or not username then username = ""; end local stmt, err = dosql(sql, host, username); if not stmt then return rollback(nil, err); end local next = stmt:rows(); return commit(function() local row = next(); return row and row[1]; end); end function driver:purge(username) local stmt, err = dosql("DELETE FROM `prosody` WHERE `host`=? AND `user`=?", host, username); if not stmt then return rollback(stmt, err); end local changed, err = stmt:affected(); if not changed then return rollback(changed, err); end return commit(true, changed); end module:provides("storage", driver);
mit
marczych/PeggleDamacy
utils/utils.lua
1
3835
local Utils = {} -- Make sure we get "real random" numbers math.randomseed(os.time()) -- It's not really random. We want the sparkles to be somewhat bright -- so we don't allow low values. function Utils.randomSparkleColorValue() return math.random(60, 255) end -- Don't allow pegs to spawn in the top 25%, bottom 10%, or in the -- left 5% or right 5% of the screen. Return a random Vector of x & y -- coordinates to spawn the peg. function Utils.randomPegLocation(existingPegs) potentialLocation = nil -- Keep trying new positions as long as we haven't found a good one yet while Utils.invalidPosition(potentialLocation, existingPegs) do potentialLocation = Vector(math.random(Constants.SCREEN_WIDTH * .05, Constants.SCREEN_WIDTH * .95), math.random(Constants.SCREEN_HEIGHT * .25, Constants.SCREEN_HEIGHT * .90)) end return potentialLocation; end function Utils.invalidPosition(potentialLocation, existingPegs) -- This is needed because of the way invalidPosition is written above if potentialLocation == nil then return true end for i, peg in ipairs(existingPegs) do if potentialLocation:dist(Vector(peg.position.x, peg.position.y)) < 40 then return true end end return false end -- Given a peg of a given wavelength, which section of the available -- spectrum can collect it? Return 1-indexed section, or Nil function Utils.getSection(pegWavelength, availableSpectrum) for i, spectrumSection in ipairs(availableSpectrum) do if pegWavelength >= spectrumSection.lower and pegWavelength <= spectrumSection.upper then return i end end return false end -- Increase the spectrum in the section of the collected peg's wavelength function Utils.increaseSpectrumSection(section, availableSpectrum) -- We assume the peg's wavelength is only inside one spectrum section. availableSpectrum[section].lower = availableSpectrum[section].lower - Constants.SPECTRUM_SECTION_INCREASE availableSpectrum[section].upper = availableSpectrum[section].upper + Constants.SPECTRUM_SECTION_INCREASE end function Utils.clamp(x, lower, upper) return math.max(lower, math.min(upper, x)) end function Utils.randomWavelength() return math.floor(math.random(Constants.MIN_WAVELENGTH, Constants.MAX_WAVELENGTH)) end function Utils.numberInterpolate(oldValue, min, max, u) return oldValue + (max-min)*u end --TODO vector interpolates function Utils.wavelengthToRGB(wavelength) local r, g, b wavelength = Utils.clamp(wavelength, Constants.MIN_WAVELENGTH, Constants.MAX_WAVELENGTH) -- violet if wavelength < 410 then r = 0.6 - 0.41 * (410 - wavelength) / 30; g = 0; b = 0.39 + 0.6 * (410 - wavelength) / 30; -- purple to blue elseif wavelength < 440 then r = 0.19 - 0.19 * (440 - wavelength) / 30; g = 0; b = 1; -- blue to teal elseif wavelength < 490 then r = 0; g = 1 - (490 - wavelength) / 50; b = 1; -- teal to green elseif wavelength < 510 then r = 0; g = 1; b = (510 - wavelength) / 20; -- green to yellow elseif wavelength < 580 then r = 1 - (580 - wavelength) / 70; g = 1; b = 0; -- yellow to orange elseif wavelength < 640 then r = 1; g = (640 - wavelength) / 60; b = 0; -- red elseif wavelength < 700 then r = 1; g = 0; b = 0; -- dark red else r = 0.35 + 0.65 * (Constants.MAX_WAVELENGTH - wavelength) / 80; g = 0; b = 0; end return { r = r * 255, g = g * 255, b = b * 255 } end function Utils.calculateSpectrumColors() local colors = {} for wv = Constants.MIN_WAVELENGTH, Constants.MAX_WAVELENGTH do colors[wv] = Utils.wavelengthToRGB(wv) end return colors end return Utils
apache-2.0
fqrouter/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk/dialplan_out.lua
80
3231
--[[ LuCI - Lua Configuration Interface Copyright 2008 Jo-Philipp Wich <xm@subsignal.org> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- local ast = require("luci.asterisk") local function find_outgoing_contexts(uci) local c = { } local h = { } -- uci:foreach("asterisk", "dialplan", -- function(s) -- if not h[s['.name']] then -- c[#c+1] = { s['.name'], "Dialplan: %s" % s['.name'] } -- h[s['.name']] = true -- end -- end) uci:foreach("asterisk", "dialzone", function(s) if not h[s['.name']] then c[#c+1] = { s['.name'], "Dialzone: %s" % s['.name'] } h[s['.name']] = true end end) return c end local function find_incoming_contexts(uci) local c = { } local h = { } uci:foreach("asterisk", "sip", function(s) if s.context and not h[s.context] and uci:get_bool("asterisk", s['.name'], "provider") then c[#c+1] = { s.context, "Incoming: %s" % s['.name'] or s.context } h[s.context] = true end end) return c end local function find_trunks(uci) local t = { } uci:foreach("asterisk", "sip", function(s) if uci:get_bool("asterisk", s['.name'], "provider") then t[#t+1] = { "SIP/%s" % s['.name'], "SIP: %s" % s['.name'] } end end) uci:foreach("asterisk", "iax", function(s) t[#t+1] = { "IAX/%s" % s['.name'], "IAX: %s" % s.extension or s['.name'] } end) return t end --[[ dialzone {name} - Outgoing zone. uses - Outgoing line to use: TYPE/Name match (list) - Number to match countrycode - The effective country code of this dialzone international (list) - International prefix to match localzone - dialzone for local numbers addprefix - Prexix required to dial out. localprefix - Prefix for a local call ]] -- -- SIP dialzone configuration -- if arg[1] then cbimap = Map("asterisk", "Edit Dialplan Entry") entry = cbimap:section(NamedSection, arg[1]) back = entry:option(DummyValue, "_overview", "Back to dialplan overview") back.value = "" back.titleref = luci.dispatcher.build_url("admin", "asterisk", "dialplans") desc = entry:option(Value, "description", "Description") function desc.cfgvalue(self, s, ...) return Value.cfgvalue(self, s, ...) or s end match = entry:option(DynamicList, "match", "Number matches") intl = entry:option(DynamicList, "international", "Intl. prefix matches (optional)") trunk = entry:option(MultiValue, "uses", "Used trunk") for _, v in ipairs(find_trunks(cbimap.uci)) do trunk:value(unpack(v)) end aprefix = entry:option(Value, "addprefix", "Add prefix to dial out (optional)") --ast.idd.cbifill(aprefix) ccode = entry:option(Value, "countrycode", "Effective countrycode (optional)") ast.cc.cbifill(ccode) lzone = entry:option(ListValue, "localzone", "Dialzone for local numbers") lzone:value("", "no special treatment of local numbers") for _, v in ipairs(find_outgoing_contexts(cbimap.uci)) do lzone:value(unpack(v)) end lprefix = entry:option(Value, "localprefix", "Prefix for local calls (optional)") return cbimap end
apache-2.0
wright8191/dotfiles
Linux/config.symlink/awesome/rc.lua
2
26176
-- Standard awesome library local gears = require("gears") local awful = require("awful") require("awful.autofocus") -- Widget and layout library local wibox = require("wibox") -- Theme handling library; global for awesome-client beautiful = require("beautiful") -- Notification library; global for awesome-client naughty = require("naughty") -- https://github.com/awesomeWM/awesome/issues/1862 -- migrate to beautiful.notification_icon_size = 10 one day naughty.config.defaults['icon_size'] = 50 local menubar = require("menubar") local hotkeys_popup = require("awful.hotkeys_popup").widget -- Vicious widgets local vicious = require("vicious") -- my utils local whw = require("whw-utils") if whw.has_battery() then require("battery-notification") end -- globals for downstream programs newline = '\n' -- {{{ Error handling -- Check if awesome encountered an error during startup and fell back to -- another config (This code will only ever execute for the fallback config) if awesome.startup_errors then naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, there were errors during startup!", text = awesome.startup_errors }) end -- Handle runtime errors after startup do local in_error = false awesome.connect_signal("debug::error", function (err) -- Make sure we don't go into an endless error loop if in_error then return end in_error = true naughty.notify({ preset = naughty.config.presets.critical, title = "Oops, an error happened!", text = tostring(err) }) in_error = false end) end -- }}} -- {{{ Variable definitions -- Themes define colours, icons, font and wallpapers. beautiful.init(awful.util.get_configuration_dir() .. "themes/default/theme.lua") -- This is used later as the default terminal and editor to run. terminal = "terminator" editor = os.getenv("EDITOR") or "nano" editor_cmd = terminal .. " -e " .. editor -- Default modkey. -- Usually, Mod4 is the key with a logo between Control and Alt. -- If you do not like this or do not have such a key, -- I suggest you to remap Mod4 to another key using xmodmap or other tools. -- However, you can use another modifier like Mod1, but it may interact with others. modkey = "Mod4" -- Table of layouts to cover with awful.layout.inc, order matters. awful.layout.layouts = { -- awful.layout.suit.floating, awful.layout.suit.tile, -- awful.layout.suit.tile.left, -- awful.layout.suit.tile.bottom, -- awful.layout.suit.tile.top, awful.layout.suit.fair, -- awful.layout.suit.fair.horizontal, -- awful.layout.suit.spiral, -- awful.layout.suit.spiral.dwindle, -- awful.layout.suit.max, -- awful.layout.suit.max.fullscreen, -- awful.layout.suit.magnifier, -- awful.layout.suit.corner.nw, -- awful.layout.suit.corner.ne, -- awful.layout.suit.corner.sw, -- awful.layout.suit.corner.se, } -- }}} -- {{{ Helper functions local function client_menu_toggle_fn() local instance = nil return function () if instance and instance.wibox.visible then instance:hide() instance = nil else instance = awful.menu.clients({ theme = { width = 250 } }) end end end -- }}} -- {{{ Menu -- Create a launcher widget and a main menu myawesomemenu = { { "hotkeys", function() return false, hotkeys_popup.show_help end}, { "manual", terminal .. " -e man awesome" }, { "edit config", editor_cmd .. " " .. awesome.conffile }, { "restart", awesome.restart }, { "quit", function() awesome.quit() end} } mymainmenu = awful.menu({ items = { { "awesome", myawesomemenu, beautiful.awesome_icon }, { "open terminal", terminal } } }) mylauncher = awful.widget.launcher({ image = beautiful.awesome_icon, menu = mymainmenu }) -- Menubar configuration menubar.utils.terminal = terminal -- Set the terminal for applications that require it -- }}} -- Keyboard map indicator and switcher mykeyboardlayout = awful.widget.keyboardlayout() -- {{{ Wibar -- Create a textclock widget mytextclock = awful.widget.textclock("%a %b %d %H:%M %z", 15) -- separators local separator = wibox.widget.textbox() separator:set_text(' | ') local space_separator = wibox.widget.textbox() space_separator:set_text(' ') -- vicious widgets -- cpu graph cpu_graph_widget = wibox.widget.graph() cpu_graph_widget:set_width(50) cpu_graph_widget.background_color = beautiful.bg_normal cpu_graph_widget:set_color({ type = "linear", from = { 0, 0 }, to = { 50, 0 }, stops = { { 0, "#FF5656" }, { 0.5, "#88A175" }, { 1, "#AECF96" } }}) vicious.register(cpu_graph_widget, vicious.widgets.cpu, "$1", 3) -- volume volume_widget = wibox.widget.textbox() vicious.register(volume_widget, vicious.widgets.volume, function (widget, args) return whw.fg(args[2] .. args[1], {color = "white"}) end, 1, "Master") -- stock widget local stock_widget = require("stock-widget") stock = stock_widget({symbol = "HD", loss_color = whw.colors.red, gain_color = whw.colors.green}) -- 3rd party widgets -- https://github.com/coldfix/awesome.battery-widget if whw.has_battery() then local battery_widget = require("battery-widget") battery = battery_widget({ adapter = "BAT0", battery_prefix = "Battery: ", limits = { {25, whw.colors.red}, {50, "orange"}, {100, whw.colors.green} }}) else battery = { widget = nil } end -- Create a wibox for each screen and add it local taglist_buttons = awful.util.table.join( awful.button({ }, 1, function(t) t:view_only() end), awful.button({ modkey }, 1, function(t) if client.focus then client.focus:move_to_tag(t) end end), awful.button({ }, 3, awful.tag.viewtoggle), awful.button({ modkey }, 3, function(t) if client.focus then client.focus:toggle_tag(t) end end), awful.button({ }, 4, function(t) awful.tag.viewnext(t.screen) end), awful.button({ }, 5, function(t) awful.tag.viewprev(t.screen) end) ) local tasklist_buttons = awful.util.table.join( awful.button({ }, 1, function (c) if c == client.focus then c.minimized = true else -- Without this, the following -- :isvisible() makes no sense c.minimized = false if not c:isvisible() and c.first_tag then c.first_tag:view_only() end -- This will also un-minimize -- the client, if needed client.focus = c c:raise() end end), awful.button({ }, 3, client_menu_toggle_fn()), awful.button({ }, 4, function () awful.client.focus.byidx(1) end), awful.button({ }, 5, function () awful.client.focus.byidx(-1) end)) local function set_wallpaper(s) -- Wallpaper if beautiful.wallpaper then local wallpaper = beautiful.wallpaper -- If wallpaper is a function, call it with the screen if type(wallpaper) == "function" then wallpaper = wallpaper(s) end gears.wallpaper.maximized(wallpaper, s, true) end end -- Re-set wallpaper when a screen's geometry changes (e.g. different resolution) screen.connect_signal("property::geometry", set_wallpaper) -- restart awesome when moving displays screen.connect_signal("removed", awesome.restart) screen.connect_signal("added", awesome.restart) awful.screen.connect_for_each_screen(function(s) -- Wallpaper set_wallpaper(s) -- Each screen has its own tag table. awful.tag({ "1", "2", "3", "4", "5", "6", "7", "8", "9" }, s, awful.layout.layouts[1]) -- Create a promptbox for each screen s.mypromptbox = awful.widget.prompt() -- Create an imagebox widget which will contains an icon indicating which layout we're using. -- We need one layoutbox per screen. s.mylayoutbox = awful.widget.layoutbox(s) s.mylayoutbox:buttons(awful.util.table.join( awful.button({ }, 1, function () awful.layout.inc( 1) end), awful.button({ }, 3, function () awful.layout.inc(-1) end), awful.button({ }, 4, function () awful.layout.inc( 1) end), awful.button({ }, 5, function () awful.layout.inc(-1) end))) -- Create a taglist widget s.mytaglist = awful.widget.taglist(s, awful.widget.taglist.filter.all, taglist_buttons) -- Create a tasklist widget s.mytasklist = awful.widget.tasklist(s, awful.widget.tasklist.filter.currenttags, tasklist_buttons) -- Create the wibox s.mywibox = awful.wibar({ position = "top", screen = s }) -- Add widgets to the wibox s.mywibox:setup { layout = wibox.layout.align.horizontal, { -- Left widgets layout = wibox.layout.fixed.horizontal, mylauncher, s.mytaglist, s.mypromptbox, }, s.mytasklist, -- Middle widget { -- Right widgets layout = wibox.layout.fixed.horizontal, -- mykeyboardlayout, -- what is this? -- space_separator, wibox.widget.systray(), separator, cpu_graph_widget, separator, stock.widget, -- hacky solution to not show battery on desktop -- TODO: revisit this with make_widget battery.widget and separator or nil, battery.widget and battery.widget or nil, separator, volume_widget, separator, mytextclock, space_separator, s.mylayoutbox, }, } end) -- }}} -- {{{ Mouse bindings root.buttons(awful.util.table.join( awful.button({ }, 3, function () mymainmenu:toggle() end), awful.button({ }, 4, awful.tag.viewnext), awful.button({ }, 5, awful.tag.viewprev) )) -- }}} -- {{{ Key bindings globalkeys = awful.util.table.join( awful.key({ modkey, }, "s", hotkeys_popup.show_help, {description="show help", group="awesome"}), awful.key({ modkey, }, "Left", awful.tag.viewprev, {description = "view previous", group = "tag"}), awful.key({ modkey, }, "Right", awful.tag.viewnext, {description = "view next", group = "tag"}), awful.key({ modkey, }, "Escape", awful.tag.history.restore, {description = "go back", group = "tag"}), awful.key({ modkey, }, "j", function () awful.client.focus.byidx( 1) end, {description = "focus next by index", group = "client"} ), awful.key({ modkey, }, "k", function () awful.client.focus.byidx(-1) end, {description = "focus previous by index", group = "client"} ), awful.key({ modkey, }, "w", function () mymainmenu:show() end, {description = "show main menu", group = "awesome"}), -- Layout manipulation awful.key({ modkey, "Shift" }, "j", function () awful.client.swap.byidx( 1) end, {description = "swap with next client by index", group = "client"}), awful.key({ modkey, "Shift" }, "k", function () awful.client.swap.byidx( -1) end, {description = "swap with previous client by index", group = "client"}), awful.key({ modkey, "Control" }, "j", function () awful.screen.focus_relative( 1) end, {description = "focus the next screen", group = "screen"}), awful.key({ modkey, "Control" }, "k", function () awful.screen.focus_relative(-1) end, {description = "focus the previous screen", group = "screen"}), awful.key({ modkey, }, "u", awful.client.urgent.jumpto, {description = "jump to urgent client", group = "client"}), awful.key({ modkey, }, "Tab", function () awful.client.focus.history.previous() if client.focus then client.focus:raise() end end, {description = "go back", group = "client"}), -- Standard program awful.key({ modkey, }, "Return", function () awful.spawn(terminal) end, {description = "open a terminal", group = "launcher"}), awful.key({ modkey, "Control" }, "r", awesome.restart, {description = "reload awesome", group = "awesome"}), awful.key({ modkey, "Shift" }, "q", awesome.quit, {description = "quit awesome", group = "awesome"}), awful.key({ modkey, }, "l", function () awful.tag.incmwfact( 0.05) end, {description = "increase master width factor", group = "layout"}), awful.key({ modkey, }, "h", function () awful.tag.incmwfact(-0.05) end, {description = "decrease master width factor", group = "layout"}), awful.key({ modkey, "Shift" }, "h", function () awful.tag.incnmaster( 1, nil, true) end, {description = "increase the number of master clients", group = "layout"}), awful.key({ modkey, "Shift" }, "l", function () awful.tag.incnmaster(-1, nil, true) end, {description = "decrease the number of master clients", group = "layout"}), awful.key({ modkey, "Control" }, "h", function () awful.tag.incncol( 1, nil, true) end, {description = "increase the number of columns", group = "layout"}), awful.key({ modkey, "Control" }, "l", function () awful.tag.incncol(-1, nil, true) end, {description = "decrease the number of columns", group = "layout"}), awful.key({ modkey, }, "space", function () awful.layout.inc( 1) end, {description = "select next", group = "layout"}), awful.key({ modkey, "Shift" }, "space", function () awful.layout.inc(-1) end, {description = "select previous", group = "layout"}), awful.key({ modkey, "Control" }, "n", function () local c = awful.client.restore() -- Focus restored client if c then client.focus = c c:raise() end end, {description = "restore minimized", group = "client"}), -- Prompt awful.key({ modkey }, "r", function () awful.screen.focused().mypromptbox:run() end, {description = "run prompt", group = "launcher"}), awful.key({ modkey }, "x", function () awful.prompt.run { prompt = "Run Lua code: ", textbox = awful.screen.focused().mypromptbox.widget, exe_callback = awful.util.eval, history_path = awful.util.get_cache_dir() .. "/history_eval" } end, {description = "lua execute prompt", group = "awesome"}), -- Menubar awful.key({ modkey }, "p", function() menubar.show() end, {description = "show the menubar", group = "launcher"}), -- Volume awful.key({ }, "XF86AudioRaiseVolume", function () awful.util.spawn("amixer -D pulse sset Master 5%+") end), awful.key({ }, "XF86AudioLowerVolume", function () awful.util.spawn("amixer -D pulse sset Master 5%-") end), awful.key({ }, "XF86AudioMute", function () awful.util.spawn("amixer -D pulse set Master 1+ toggle") end), -- Brightness awful.key({ }, "XF86MonBrightnessDown", function() awful.util.spawn("xbacklight -dec 5") end), awful.key({ }, "XF86MonBrightnessUp", function() awful.util.spawn("xbacklight -inc 5") end), -- Lock awful.key({ "Control", "Mod1" }, "l", function () awful.util.spawn("sync") awful.util.spawn("xautolock -locknow") end), -- application switcher awful.key({ "Mod1" }, "Escape", function () -- If you want to always position the menu on the same place set coordinates awful.menu.menu_keys.down = { "Down", "Alt_L" } awful.menu.clients({theme = { width = 250 }}, { keygrabber=true }) end) ) clientkeys = awful.util.table.join( awful.key({ modkey, }, "f", function (c) c.fullscreen = not c.fullscreen c:raise() end, {description = "toggle fullscreen", group = "client"}), awful.key({ modkey, "Shift" }, "c", function (c) c:kill() end, {description = "close", group = "client"}), awful.key({ modkey, "Control" }, "space", awful.client.floating.toggle , {description = "toggle floating", group = "client"}), awful.key({ modkey, "Control" }, "Return", function (c) c:swap(awful.client.getmaster()) end, {description = "move to master", group = "client"}), awful.key({ modkey, }, "o", function (c) c:move_to_screen() end, {description = "move to screen", group = "client"}), awful.key({ modkey, }, "t", function (c) c.ontop = not c.ontop end, {description = "toggle keep on top", group = "client"}), awful.key({ modkey, }, "n", function (c) -- The client currently has the input focus, so it cannot be -- minimized, since minimized clients can't have the focus. c.minimized = true end , {description = "minimize", group = "client"}), awful.key({ modkey, }, "m", function (c) c.maximized = not c.maximized -- sometimes windows get stuck with these settings c.maximized_horizontal = false c.maximized_vertical = false c.floating = false c:raise() end , {description = "maximize", group = "client"}) ) -- Bind all key numbers to tags. -- Be careful: we use keycodes to make it works on any keyboard layout. -- This should map on the top row of your keyboard, usually 1 to 9. for i = 1, 9 do globalkeys = awful.util.table.join(globalkeys, -- View tag only. awful.key({ modkey }, "#" .. i + 9, function () local screen = awful.screen.focused() local tag = screen.tags[i] if tag then tag:view_only() end end, {description = "view tag #"..i, group = "tag"}), -- Toggle tag display. awful.key({ modkey, "Control" }, "#" .. i + 9, function () local screen = awful.screen.focused() local tag = screen.tags[i] if tag then awful.tag.viewtoggle(tag) end end, {description = "toggle tag #" .. i, group = "tag"}), -- Move client to tag. awful.key({ modkey, "Shift" }, "#" .. i + 9, function () if client.focus then local tag = client.focus.screen.tags[i] if tag then client.focus:move_to_tag(tag) end end end, {description = "move focused client to tag #"..i, group = "tag"}), -- Toggle tag on focused client. awful.key({ modkey, "Control", "Shift" }, "#" .. i + 9, function () if client.focus then local tag = client.focus.screen.tags[i] if tag then client.focus:toggle_tag(tag) end end end, {description = "toggle focused client on tag #" .. i, group = "tag"}) ) end clientbuttons = awful.util.table.join( awful.button({ }, 1, function (c) client.focus = c; c:raise() end), awful.button({ modkey }, 1, awful.mouse.client.move), awful.button({ modkey }, 3, awful.mouse.client.resize)) -- Set keys root.keys(globalkeys) -- }}} -- {{{ Rules -- Rules to apply to new clients (through the "manage" signal). awful.rules.rules = { -- All clients will match this rule. { rule = { }, properties = { border_width = beautiful.border_width, border_color = beautiful.border_normal, focus = awful.client.focus.filter, raise = true, keys = clientkeys, buttons = clientbuttons, screen = awful.screen.preferred, placement = awful.placement.no_overlap+awful.placement.no_offscreen } }, -- Floating clients. { rule_any = { instance = { "DTA", -- Firefox addon DownThemAll. "copyq", -- Includes session name in class. }, class = { "Arandr", "Gpick", "Kruler", "MessageWin", -- kalarm. "Sxiv", "Wpa_gui", "pinentry", "veromix", "xtightvncviewer"}, name = { "Event Tester", -- xev. }, role = { "AlarmWindow", -- Thunderbird's calendar. "pop-up", -- e.g. Google Chrome's (detached) Developer Tools. } }, properties = { floating = true }}, -- Add titlebars to normal clients and dialogs { rule_any = {type = { "normal", "dialog" } }, properties = { titlebars_enabled = false } }, -- Set Firefox to always map on the tag named "2" on screen 1. -- { rule = { class = "Firefox" }, -- properties = { screen = 1, tag = "2" } }, -- tag 5 { rule = { class = "datagrip" }, properties = { screen = 1, tag = "5" } }, -- tag 9 { rule = { class = "KeeWeb" }, properties = { screen = 1, tag = "9" } }, } -- }}} -- {{{ Signals -- Signal function to execute when a new client appears. client.connect_signal("manage", function (c) -- Set the windows at the slave, -- i.e. put it at the end of others instead of setting it master. -- if not awesome.startup then awful.client.setslave(c) end if awesome.startup and not c.size_hints.user_position and not c.size_hints.program_position then -- Prevent clients from being unreachable after screen count changes. awful.placement.no_offscreen(c) end end) -- Add a titlebar if titlebars_enabled is set to true in the rules. client.connect_signal("request::titlebars", function(c) -- buttons for the titlebar local buttons = awful.util.table.join( awful.button({ }, 1, function() client.focus = c c:raise() awful.mouse.client.move(c) end), awful.button({ }, 3, function() client.focus = c c:raise() awful.mouse.client.resize(c) end) ) awful.titlebar(c) : setup { { -- Left awful.titlebar.widget.iconwidget(c), buttons = buttons, layout = wibox.layout.fixed.horizontal }, { -- Middle { -- Title align = "center", widget = awful.titlebar.widget.titlewidget(c) }, buttons = buttons, layout = wibox.layout.flex.horizontal }, { -- Right awful.titlebar.widget.floatingbutton (c), awful.titlebar.widget.maximizedbutton(c), awful.titlebar.widget.stickybutton (c), awful.titlebar.widget.ontopbutton (c), awful.titlebar.widget.closebutton (c), layout = wibox.layout.fixed.horizontal() }, layout = wibox.layout.align.horizontal } end) -- Enable sloppy focus, so that focus follows mouse. client.connect_signal("mouse::enter", function(c) if awful.layout.get(c.screen) ~= awful.layout.suit.magnifier and awful.client.focus.filter(c) then client.focus = c end end) client.connect_signal("focus", function(c) c.border_color = beautiful.border_focus end) client.connect_signal("unfocus", function(c) c.border_color = beautiful.border_normal end) -- }}}
mit
kitala1/darkstar
scripts/globals/mobskills/Gate_of_Tartarus.lua
7
1068
--------------------------------------------- -- Gate of Tartarus -- -- Description: Lowers target's attack. Additional effect: Refresh -- Type: Physical -- Shadow per hit -- Range: Melee --------------------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/globals/monstertpmoves"); --------------------------------------------- function onMobSkillCheck(target,mob,skill) return 0; end; function onMobWeaponSkill(target, mob, skill) local numhits = 1; local accmod = 1; local dmgmod = 2.5; local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_DMG_VARIES,3,3,3); local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_SLASH,info.hitslanded); local duration = 20; if(mob:getTP() == 300) then duration = 60; elseif(mob:getTP() >= 200) then duration = 40; end MobBuffMove(mob, EFFECT_REFRESH, 8, 3, duration); MobStatusEffectMove(mob, target, EFFECT_ATTACK_DOWN, 20, 0, duration); target:delHP(dmg); return dmg; end;
gpl-3.0
Pulse-Eight/drivers
Control4/neo4_professional_pulse-eight/lib/c4_log.lua
9
17977
--[[============================================================================= c4_log Class Copyright 2015 Control4 Corporation. All Rights Reserved. ===============================================================================]] require "common.p8declares" require "lib.c4_object" c4_log = inheritsFrom(nil) function c4_log:construct(logName) self._logLevel = tonumber(string.sub(Properties['Log Level'] or "", 1, 1)) or 5 self._outputPrint = Properties['Log Mode']:find("Print") ~= nil self._outputC4Log = Properties['Log Mode']:find("Log") ~= nil self._logName = logName or "" -- make sure Property is up to date (no harm if absent) C4:UpdateProperty("Log Level", Properties['Log Level']) end function c4_log:SetLogLevel(level) self._logLevel = tonumber(string.sub(level or "", 1, 1)) or self._logLevel end function c4_log:LogLevel() return self._logLevel end function c4_log:OutputPrint(value) self._outputPrint = value end function c4_log:OutputC4Log(value) self._outputC4Log = value end function c4_log:SetLogName(logName) if (logName == nil or logName == "") then logName = "" else logName = logName .. ": " end self._logName = logName end function c4_log:LogName() return self._logName end function c4_log:Enabled() return (self._outputPrint or self._outputC4Log) end function c4_log:PrintEnabled() return self._outputPrint end function c4_log:C4LogEnabled() return self._outputC4Log end function c4_log:CreateTableText(tValue, tableText) tableText = tableText or "" if (type(tValue) == "table") then tableText = tableText .. "{" for k, v in pairs(tValue) do -- add key if (type(k) == "number") then tableText = tableText .. "[" .. tostring(k) .. "]=" elseif (type(k) == "string") then tableText = tableText .. k .. "=" else print (tostring(k) .. ": " .. tostring (v)) end -- add value if (type(v) == "number") then tableText = tableText .. tostring(v) .. "," elseif (type(v) == "string") then tableText = tableText .. "'" .. v .. "'," elseif (type(v) == "table") then tableText = c4_log:CreateTableText(v, tableText) tableText = tableText .. "," elseif (type(v) == "boolean") then tableText = tableText .. tostring(v) .. "," end end tableText = tableText .. "}" end return tableText end function InsertIndent(indentLevel) local indentStr = "" for i=1, indentLevel do indentStr = indentStr .. "\t" end return indentStr end function c4_log:CreateTableTextFormatted(tValue, tableText, indentLevel) tableText = tableText or "" indentLevel = indentLevel or 0 if (type(tValue) == "table") then indentLevel = indentLevel + 1 tableText = tableText .. "{\n" for k, v in pairs(tValue) do -- add key if (type(k) == "number") then tableText = tableText .. InsertIndent(indentLevel) .. "[" .. tostring(k) .. "]=" elseif (type(k) == "string") then tableText = tableText .. InsertIndent(indentLevel) .. k .. "=" else print (tostring(k) .. ": " .. tostring (v)) end -- add value if (type(v) == "number") then tableText = tableText .. tostring(v) .. ",\n" elseif (type(v) == "string") then tableText = tableText .. "'" .. v .. "',\n" elseif (type(v) == "table") then tableText = c4_log:CreateTableTextFormatted(v, tableText, indentLevel) tableText = tableText .. ",\n" elseif (type(v) == "boolean") then tableText = tableText .. tostring(v) .. ",\n" end end indentLevel = indentLevel - 1 tableText = tableText .. InsertIndent(indentLevel) .. "}" end return tableText end MAX_TABLE_LEVELS = 10 function c4_log:PrintTable(tValue, tableText, sIndent, level) tableText = tableText or "" level = level + 1 if (level <= MAX_TABLE_LEVELS) then if (type(tValue) == "table") then for k,v in pairs(tValue) do if (tableText == "") then tableText = sIndent .. tostring(k) .. ": " .. tostring(v) if (sIndent == ". ") then sIndent = " " end else tableText = tableText .. "\n" .. sIndent .. tostring(k) .. ": " .. tostring(v) end if (type(v) == "table") then tableText = self:PrintTable(v, tableText, sIndent .. " ", level) end end else tableText = tableText .. "\n" .. sIndent .. tostring(tValue) end end return tableText end function c4_log:LogTable(tValue, sIndent, level) level = level + 1 if (level <= MAX_TABLE_LEVELS) then if (type(tValue) == "table") then for k,v in pairs(tValue) do C4:ErrorLog(self._logName .. ": " .. sIndent .. tostring(k) .. ": " .. tostring(v)) if (type(v) == "table") then self:LogTable(v, sIndent .. " ", level) end end else C4:ErrorLog(self._logName .. ": " .. sIndent .. tValue) end end end function c4_log:Print(logLevel, sLogText) if (self._logLevel >= logLevel) then if (type(sLogText) == "table") then if (self._outputPrint) then print (self:PrintTable(sLogText, tableText, ". ", 0)) end if (self._outputC4Log) then self:LogTable(sLogText, " ", 0) end return end if (self._outputPrint) then print (sLogText) end if (self._outputC4Log) then C4:ErrorLog(self._logName .. ": " .. tostring(sLogText)) end end end function c4_log:Fatal(sLogText, ...) self:LogOutput(0, sLogText, ...) end function c4_log:Error(sLogText, ...) self:LogOutput(1, sLogText, ...) end function c4_log:Warn(sLogText, ...) self:LogOutput(2, sLogText, ...) end function c4_log:Info(sLogText, ...) self:LogOutput(3, sLogText, ...) end function c4_log:Debug(sLogText, ...) self:LogOutput(4, sLogText, ...) end function c4_log:Trace(sLogText, ...) self:LogOutput(5, sLogText, ...) end function c4_log:LogOutput(level, sLogText, ...) if (LogEnabled()) then if (type(sLogText) == "string") then sLogText = string.format(sLogText, ...) end self:Print(level, sLogText) end end --[[============================================================================= c4_log wrapper functions ===============================================================================]] function TryLog(level, sLogText, ...) LOG:LogOutput(level, sLogText, ...) end --[[============================================================================= SetLogLevel(level) Description: Sets the desired log level to view Parameters: level(int) - The logging level to set the message to 0 = Fatal 1 = Error 2 = Warn 3 = Info 4 = Debug 5 = Trace Returns: None ===============================================================================]] function SetLogLevel(level) LOG:SetLogLevel(level) end --[[============================================================================= LogLevel() Description: Returns the currently set log level Parameters: None Returns: The current log level 0 = Fatal 1 = Error 2 = Warn 3 = Info 4 = Debug 5 = Trace ===============================================================================]] function LogLevel() return LOG:LogLevel() end --[[============================================================================= OutputPrint(value) Description: Specifies whether to output log messages or not Parameters: value(bool) - true to enable logging output, false otherwise Returns: None ===============================================================================]] function OutputPrint(value) LOG:OutputPrint(value) end --[[============================================================================= OutputPrint(value) Description: Specifies whether to output log messages to file or not Parameters: value(bool) - true to enable logging output, false otherwise Returns: None ===============================================================================]] function OutputC4Log(value) LOG:OutputC4Log(value) end --[[============================================================================= SetLogName(logName) Description: Sets the name of the log file where the messages will be written to Parameters: logName(string) - Sets the name of the log to write messages to Returns: None ===============================================================================]] function SetLogName(logName) LOG:SetLogName(logName) end --[[============================================================================= LogName(logName) Description: Gets the name of the log file where the messages will be written to Parameters: None Returns: The value of the log file that has been set ===============================================================================]] function LogName() return LOG:LogName() end --[[============================================================================= LogEnabled() Description: Identifies if logging or print has been enabled Parameters: None Returns: true if either logging or print has been enabled, false otherwise ===============================================================================]] function LogEnabled() return LOG:Enabled() end --[[============================================================================= PrintEnabled() Description: Gets the state of print output Parameters: None Returns: true if print has been enabled, false otherwise ===============================================================================]] function PrintEnabled() return LOG:PrintEnabled() end --[[============================================================================= C4LogEnabled() Description: Gets the state of logging Parameters: None Returns: true if logging has been enabled, false otherwise ===============================================================================]] function C4LogEnabled() return LOG:C4LogEnabled() end --[[============================================================================= LogFatal(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Fatal(0) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogFatal(sLogText, ...) local status, err = pcall(TryLog, 0, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogFatal failed: " .. err) end end --[[============================================================================= LogError(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Error(1) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogError(sLogText, ...) local status, err = pcall(TryLog, 1, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogError failed: " .. err) end end --[[============================================================================= LogWarn(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Warn(2) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogWarn(sLogText, ...) local status, err = pcall(TryLog, 2, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogWarn failed: " .. err) end end --[[============================================================================= LogInfo(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Info(3) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogInfo(sLogText, ...) local status, err = pcall(TryLog, 3, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogInfo failed: " .. err) end end --[[============================================================================= LogDebug(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Debug(5) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogDebug(sLogText, ...) local status, err = pcall(TryLog, 4, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogDebug failed: " .. err) end end --[[============================================================================= LogTrace(sLogText, ...) Description: Formats and prints a series of characters and values to the enabled outputs when the set logging level is Trace(4) or higher Parameters: sLogText(string) - Format control string ... - Optional arguments which will replace all the format specifiers contained in the format string Returns: None ===============================================================================]] function LogTrace(sLogText, ...) local status, err = pcall(TryLog, 5, sLogText, ...) if (not status) then LOG:Print(1, "LUA_ERROR - LogTrace failed: " .. err) end end function dbgPrint(buf) if (LOG:PrintEnabled()) then print (buf) end end function dbgHexdump(buf) hexdump(buf, dbgPrint) end --[[============================================================================= c4_log unit tests ===============================================================================]] function __test_c4_log() require "test.C4Virtual" local LOG = c4_log:new("test_c4_log") assert(LOG:LogName() == "test_c4_log", "_logName is not equal to 'test_c4_log' it is: " .. LOG:LogName()) -- Test setting log level LOG:SetLogLevel("2 - Warning") assert(LOG:LogLevel() == 2, "_logLevel is not equal to '2' it is: " .. LOG:LogLevel()) LOG:SetLogLevel(3) assert(LOG:LogLevel() == 3, "_logLevel is not equal to '3' it is: " .. LOG:LogLevel()) -- Test enabling logs LOG:OutputPrint(false) assert(LOG:PrintEnabled() == false, "_outputPrint is not equal to 'false' it is: " .. tostring(LOG:PrintEnabled())) LOG:OutputC4Log(true) assert(LOG:C4LogEnabled() == true, "_outputC4Log is not equal to 'true' it is: " .. tostring(LOG:C4LogEnabled())) LOG:SetLogLevel(4) LogTrace("***** This is a test *****") end function __test_CreatTableText() local tTest = {} tTest[1] = {} tTest[2] = {} tTest[3] = 30 tTest[4] = "Forty" LogTrace("----- tText -----") LogTrace(tTest) local tTest2 = { One = {}, Two = {}, Three = 30, Four = "Forty" } LogTrace("----- tText2 -----") LogTrace(tTest2) local tTest3 = { [1] = {}, [2] = {}, [3] = 30, [4] = "Forty" } LogTrace("----- tText3 -----") LogTrace(tTest3) local tTest4 = { [1] = {}, Two = {}, [3] = 30, [4] = "Forty", Five = "Fifty" } LogTrace("----- tText4 -----") LogTrace(tTest4) local tableText = LOG:CreateTableText(tTest4) LogTrace("----- tableText -----") LogTrace(tableText) --local tNew = {[1] = {},[3] = 30,[4] = 'Forty',Five = 'Fifty',Two = {},} --LogTrace(tNew) end function __TestCreateTableTextFormatted() require "test.C4Virtual" local LOG = c4_log:new("test_c4_log") local tButtons = { Name = 'heat', Attributes = {}, ChildNodes = { [1] = { Name = 'button', Attributes = {}, ChildNodes = { [1] = { Value = '51', Attributes = {}, Name = 'id', ChildNodes = {}, }, [2] = { Value = 'Pool Heater', Attributes = {}, Name = 'button_text', ChildNodes = {}, }, [3] = { Value = 'POOLHT', Attributes = {}, Name = 'button_name', ChildNodes = {}, }, }, }, [2] = { Name = 'button', Attributes = {}, ChildNodes = { [1] = { Value = '53', Attributes = {}, Name = 'id', ChildNodes = {}, }, [2] = { Value = 'Spa Heater', Attributes = {}, Name = 'button_text', ChildNodes = {}, }, [3] = { Value = 'SPAHT', Attributes = {}, Name = 'button_name', ChildNodes = {}, }, }, }, [3] = { Name = 'button', Attributes = {}, ChildNodes = { [1] = { Value = '54', Attributes = {}, Name = 'id', ChildNodes = {}, }, [2] = {Value = 'Pool Solar Heater', Attributes = {}, Name = 'button_text', ChildNodes = {} }, [3] = { Value = 'SOLHT', Attributes = {}, Name = 'button_name', ChildNodes = {}, }, } } } } print(LOG:CreateTableTextFormatted(tButtons)) end
apache-2.0
kitala1/darkstar
scripts/zones/Windurst_Waters/npcs/Baren-Moren.lua
36
7540
----------------------------------- -- Area: Windurst Waters -- NPC: Baren-Moren -- Starts and Finishes Quest: Hat in Hand -- Working 100% -- @zone = 238 -- @pos = -66 -3 -148 ----------------------------------- package.loaded["scripts/zones/Windurst_Waters/TextIDs"] = nil; ----------------------------------- require("scripts/globals/quests"); require("scripts/globals/settings"); require("scripts/globals/titles"); require("scripts/globals/keyitems"); require("scripts/zones/Windurst_Waters/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) featherstatus = player:getQuestStatus(WINDURST,A_FEATHER_IN_ONE_S_CAP); if (featherstatus >= 1 and trade:hasItemQty(842,3) == true and trade:getGil() == 0 and trade:getItemCount() == 3) then player:startEvent(0x004f,1500); -- Quest Turn In end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) -- player:delQuest(WINDURST,A_FEATHER_IN_ONE_S_CAP); -- ================== FOR TESTING ONLY ===================== -- player:addFame(WINDURST,WIN_FAME*200); -- ================== FOR TESTING ONLY ===================== function testflag(set,flag) return (set % (2*flag) >= flag) end hatstatus = player:getQuestStatus(WINDURST,HAT_IN_HAND); featherstatus = player:getQuestStatus(WINDURST,A_FEATHER_IN_ONE_S_CAP); pfame = player:getFameLevel(WINDURST); if (hatstatus == 0) then player:startEvent(0x0030); -- Quest Offered -- elseif ((hatstatus == 1 or player:getVar("QuestHatInHand_var2") == 1) and player:getVar("QuestHatInHand_count") == 0) then -- player:startEvent(0x0033,80); -- Hat in Hand: During Quest - Objective Reminder elseif (hatstatus == 1 or player:getVar("QuestHatInHand_var2") == 1) then -- Variable to track quest progress -- 1 = Machitata @pos 163 0 -22 -- 2 = Honoi-Gomoi @pos -195 -11 -120 -- 4 = Kenapa-Keppa @pos 27 -6 -199 -- 8 = Clais @pos -31 -3 11 -- 16 = Kyume-Romeh @pos -58 -4 23 -- 32 = Tosuka-Porika @pos -26 -6 103 -- 64 = Pechiru-Mashiru @pos = 162 -2 159 -- 128 = Bondada @pos = -66 -3 -148 count = player:getVar("QuestHatInHand_count"); if (count == 8) then -- 80 = HAT + FULL REWARD = 8 NPCS - Option 5 player:startEvent(0x0034,80); elseif (count >= 6) then -- 50 = HAT + GOOD REWARD >= 6-7 NPCS - Option 4 player:startEvent(0x0034,50); elseif (count >= 4) then -- 30 = PARTIAL REWARD - >= 4-5 NPCS - Option 3 player:startEvent(0x0034,30); elseif (count >= 2) then -- 20 = POOR REWARD >= 2-3 NPCS - Option 2 player:startEvent(0x0034,20); else -- 0/nill = NO REWARD >= 0-1 NPCS - Option 1 player:startEvent(0x0034); end elseif (featherstatus == 1 or player:getVar("QuestFeatherInOnesCap_var") == 1) then player:startEvent(0x004e,0,842); -- Quest Objective Reminder elseif (hatstatus == 2 and featherstatus == 0 and pfame >= 3 and player:needToZone() == false and player:getVar("QuestHatInHand_var2") == 0) then rand = math.random(1,2); if (rand == 1) then player:startEvent(0x004b,0,842); -- Quest "Feather In One's Cap" offered else player:startEvent(0x0031); -- Repeatable Quest "Hat In Hand" offered end elseif (featherstatus == 2 and player:needToZone() == false) then rand = math.random(1,2); if (rand == 1) then player:startEvent(0x0031); -- Repeatable Quest "Hat In Hand" offered else player:startEvent(0x004b,0,842); -- Repeatable Quest "A Feather In One's Cap" offered end elseif (player:needToZone() == false) then player:startEvent(0x0031); -- Repeatable Quest "Hat In Hand" offered else -- Will run through these if fame is not high enough for other quests rand = math.random(1,6); if (rand == 1) then player:startEvent(0x002a); -- Standard Conversation 1 elseif (rand == 2) then player:startEvent(0x002c); -- Standard Conversation 2 elseif (rand == 3) then player:startEvent(0x002d); -- Standard Conversation 3 elseif (rand == 4) then player:startEvent(0x002e); -- Standard Conversation 4 elseif (rand == 5) then player:startEvent(0x002f); -- Standard Conversation 5 elseif (rand == 6) then player:startEvent(0x03fe); -- Standard Conversation 6 end end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); printf("RESULT: %u",option); if (csid == 0x0030 and option == 1) then player:addQuest(WINDURST,HAT_IN_HAND); player:addKeyItem(NEW_MODEL_HAT); player:messageSpecial(KEYITEM_OBTAINED,NEW_MODEL_HAT); elseif (csid == 0x0031 and option == 1) then player:setVar("QuestHatInHand_var2",1); player:addKeyItem(NEW_MODEL_HAT); player:messageSpecial(KEYITEM_OBTAINED,NEW_MODEL_HAT); elseif (csid == 0x0034 and option >= 4 and player:getFreeSlotsCount(0) == 0) then player:messageSpecial(ITEM_CANNOT_BE_OBTAINED,12543); elseif (csid == 0x0034 and option >= 1) then if (option == 5) then -- 80 = HAT + FULL REWARD = 8 NPCS - Option 5 player:addGil(GIL_RATE*500); player:messageSpecial(GIL_OBTAINED,GIL_RATE*500); if (player:hasItem(12543) == false) then player:addItem(12543,1); player:messageSpecial(ITEM_OBTAINED,12543); end elseif (option == 4) then -- 50 = HAT + GOOD REWARD >= 6 NPCS - Option 4 player:addGil(GIL_RATE*400); player:messageSpecial(GIL_OBTAINED,GIL_RATE*400); if (player:hasItem(12543) == false) then player:addItem(12543,1); player:messageSpecial(ITEM_OBTAINED,12543); end elseif (option == 3) then -- 30 = PARTIAL REWARD - >= 4 NPCS - Option 3 player:addGil(GIL_RATE*300); player:messageSpecial(GIL_OBTAINED,GIL_RATE*300); elseif (option == 2) then -- 20 = POOR REWARD >= 2 NPCS - Option 2 player:addGil(GIL_RATE*150); player:messageSpecial(GIL_OBTAINED,GIL_RATE*150); -- else (option == 1) then -- 0/nill = NO REWARD >= 0 NPCS - Option 1 end if (hatstatus == 1) then player:addFame(WINDURST,WIN_FAME*75); else player:addFame(WINDURST,WIN_FAME*8); end player:completeQuest(WINDURST,HAT_IN_HAND); player:setVar("QuestHatInHand_count",0); player:setVar("QuestHatInHand_var",0); player:needToZone(true); player:delKeyItem(NEW_MODEL_HAT); player:setVar("QuestHatInHand_var2",0); elseif (csid == 0x004b and option == 1) then if (player:getQuestStatus(WINDURST,A_FEATHER_IN_ONE_S_CAP) == QUEST_AVAILABLE) then player:addQuest(WINDURST,A_FEATHER_IN_ONE_S_CAP); elseif (player:getQuestStatus(WINDURST,A_FEATHER_IN_ONE_S_CAP) == QUEST_COMPLETED) then player:setVar("QuestFeatherInOnesCap_var",1); end elseif (csid == 0x004f) then if (player:getQuestStatus(WINDURST,A_FEATHER_IN_ONE_S_CAP) == QUEST_ACCEPTED) then player:completeQuest(WINDURST,A_FEATHER_IN_ONE_S_CAP); player:addFame(WINDURST,WIN_FAME*75); else player:addFame(WINDURST,WIN_FAME*8); player:setVar("QuestFeatherInOnesCap_var",0); end player:addGil(GIL_RATE*1500); player:tradeComplete(trade); player:needToZone(true); end end;
gpl-3.0
paulosalvatore/maruim_server
config.lua
1
2530
-- Combat settings -- NOTE: valid values for worldType are: "pvp", "no-pvp" and "pvp-enforced" worldType = "no-pvp" hotkeyAimbotEnabled = true protectionLevel = 1 killsToRedSkull = 3 killsToBlackSkull = 6 pzLocked = 30000 removeChargesFromRunes = true timeToDecreaseFrags = 24 * 60 * 60 * 1000 whiteSkullTime = 15 * 60 * 1000 stairJumpExhaustion = 2000 experienceByKillingPlayers = false expFromPlayersLevelRange = 75 allowWalkthrough = true -- Connection Config -- NOTE: maxPlayers set to 0 means no limit ip = "127.0.0.1" bindOnlyGlobalAddress = false loginProtocolPort = 7171 gameProtocolPort = 7172 statusProtocolPort = 7171 maxPlayers = 0 motd = "Seja bem-vindo ao MaruimOT!" onePlayerOnlinePerAccount = false allowClones = false serverName = "MaruimOT" statusTimeout = 5000 replaceKickOnLogin = true maxPacketsPerSecond = 40 -- Cast enableLiveCasting = true liveCastPort = 7173 -- Store Config storeImagesUrl = "http://link/to/store" storeCoinPacket = 5 -- Deaths -- NOTE: Leave deathLosePercent as -1 if you want to use the default -- death penalty formula. For the old formula, set it to 10. For -- no skill/experience loss, set it to 0. deathLosePercent = -1 -- Houses -- NOTE: set housePriceEachSQM to -1 to disable the ingame buy house functionality housePriceEachSQM = 1000 houseRentPeriod = "never" -- Item Usage timeBetweenActions = 200 timeBetweenExActions = 1000 -- Map -- NOTE: set mapName WITHOUT .otbm at the end mapName = "map" mapAuthor = "Aman" -- Market marketOfferDuration = 30 * 24 * 60 * 60 premiumToCreateMarketOffer = false checkExpiredMarketOffersEachMinutes = 60 maxMarketOffersAtATimePerPlayer = 100 -- MySQL mysqlHost = "127.0.0.1" mysqlUser = "" mysqlPass = "" mysqlDatabase = "tibia" mysqlPort = 3306 mysqlSock = "" -- Misc. allowChangeOutfit = true freePremium = true kickIdlePlayerAfterMinutes = 15 maxMessageBuffer = 4 emoteSpells = false classicEquipmentSlots = false -- Rates -- NOTE: rateExp is not used if you have enabled stages in data/XML/stages.xml rateExp = 1 rateSkill = 15 rateLoot = 1 rateMagic = 5 rateSpawn = 1 -- Monsters deSpawnRange = 2 deSpawnRadius = 50 -- Stamina staminaSystem = true -- Scripts warnUnsafeScripts = true convertUnsafeScripts = true -- Startup -- NOTE: defaultPriority only works on Windows and sets process priority. defaultPriority = "high" startupDatabaseOptimization = false -- Status server information ownerName = "Paulo Salvatore" ownerEmail = "paulo.salvatore@hotmail.com.br" url = "maruim.paulosalvatore.com.br" location = "Brasil"
gpl-2.0
kitala1/darkstar
scripts/globals/items/loaf_of_goblin_bread.lua
35
1287
----------------------------------------- -- ID: 4458 -- Item: loaf_of_goblin_bread -- Food Effect: 30Min, All Races ----------------------------------------- -- Health 7 -- Vitality 1 -- Charisma -5 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,1800,4458); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_HP, 7); target:addMod(MOD_VIT, 1); target:addMod(MOD_CHR, -5); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_HP, 7); target:delMod(MOD_VIT, 1); target:delMod(MOD_CHR, -5); end;
gpl-3.0
kitala1/darkstar
scripts/globals/spells/raptor_mazurka.lua
31
1188
----------------------------------------- -- Spell: Raptor Mazurka -- Gives party members enhanced movement ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local power = 12; local iBoost = caster:getMod(MOD_MAZURKA_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); local duration = 120; duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if (caster:hasStatusEffect(EFFECT_SOUL_VOICE)) then duration = duration * 2; elseif (caster:hasStatusEffect(EFFECT_MARCATO)) then duration = duration * 1.5; end caster:delStatusEffect(EFFECT_MARCATO); if (caster:hasStatusEffect(EFFECT_TROUBADOUR)) then duration = duration * 2; end if not (target:addBardSong(caster,EFFECT_MAZURKA,power,0,duration,caster:getID(), 0, 1)) then spell:setMsg(75); end return EFFECT_MAZURKA; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Southern_San_dOria/npcs/Estiliphire.lua
29
1068
----------------------------------- -- Area: Southern Sandoria -- NPC: Estiliphire -- Type: Event Sideshow NPC -- @zone: 230 -- @pos -41.550 1.999 -2.845 -- ----------------------------------- package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil; ----------------------------------- ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) local FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE); if (FlyerForRegine == 1) then count = trade:getItemCount(); MagicFlyer = trade:hasItemQty(532,1); if (MagicFlyer == true and count == 1) then player:messageSpecial(FLYER_REFUSED); end end end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) player:startEvent(0x381); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end;
gpl-3.0
kitala1/darkstar
scripts/zones/Sauromugue_Champaign/npcs/Cavernous_Maw.lua
13
2388
----------------------------------- -- Area: Sauromugue Champaign -- NPC: Cavernous Maw -- Teleports Players to Sauromugue_Champaign_S -- @pos 369 8 -227 120 ----------------------------------- package.loaded["scripts/zones/Sauromugue_Champaign/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/keyitems"); require("scripts/globals/teleports"); require("scripts/globals/missions"); require("scripts/globals/campaign"); require("scripts/zones/Sauromugue_Champaign/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) if (ENABLE_WOTG == 1 and player:hasKeyItem(PURE_WHITE_FEATHER) == false) then player:startEvent(0x01f4,2); elseif (ENABLE_WOTG == 1 and hasMawActivated(player,2)) then player:startEvent(0x0388); else player:messageSpecial(NOTHING_HAPPENS); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish Action ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID:",csid); -- printf("RESULT:",option); if (csid == 0x01f4) then local r = math.random(1,3); player:addKeyItem(PURE_WHITE_FEATHER); player:messageSpecial(KEYITEM_OBTAINED,PURE_WHITE_FEATHER); player:completeMission(WOTG,CAVERNOUS_MAWS); player:addMission(WOTG,BACK_TO_THE_BEGINNING); if (r == 1) then player:addNationTeleport(MAW,1); toMaw(player,1); -- go to Batallia_Downs[S] elseif (r == 2) then player:addNationTeleport(MAW,2); toMaw(player,3); -- go to Rolanberry_Fields_[S] elseif (r == 3) then player:addNationTeleport(MAW,4); toMaw(player,5); -- go to Sauromugue_Champaign_[S] end; elseif (csid == 0x0388 and option == 1) then toMaw(player,5); -- go to Sauromugue_Champaign_[S] end; end;
gpl-3.0
Roblox/Core-Scripts
CoreScriptsRoot/Modules/DevConsole/Components/Scripts/ServerScriptsEntry.lua
1
4428
local CorePackages = game:GetService("CorePackages") local Roact = require(CorePackages.Roact) local Components = script.Parent.Parent.Parent.Components local CellLabel = require(Components.CellLabel) local BannerButton = require(Components.BannerButton) local LineGraph = require(Components.LineGraph) local Constants = require(script.Parent.Parent.Parent.Constants) local LINE_WIDTH = Constants.GeneralFormatting.LineWidth local LINE_COLOR = Constants.GeneralFormatting.LineColor local HEADER_NAMES = Constants.ServerScriptsFormatting.ChartHeaderNames local ENTRY_HEIGHT = Constants.ServerScriptsFormatting.EntryFrameHeight local ACTIVITYBOX_WIDTH = Constants.ServerScriptsFormatting.ActivityBoxWidth local ACTIVITYBOX_PADDING = Constants.ServerScriptsFormatting.ActivityBoxPadding local ACTIVITYBOX_PADDING_UDIM = UDim2.new(0, ACTIVITYBOX_PADDING, 0, 0) local GRAPH_HEIGHT = Constants.GeneralFormatting.LineGraphHeight local convertTimeStamp = require(script.Parent.Parent.Parent.Util.convertTimeStamp) return function(props) local scriptData = props.scriptData local frameHeight = props.frameHeight local showGraph = props.showGraph local layoutOrder = props.layoutOrder local activityBoxColor = props.activityBoxColor local entryCellSize = props.entryCellSize local cellOffset = props.cellOffset local verticalOffsets = props.verticalOffsets local onButtonPress = props.onButtonPress local getX = props.getX local getActivity = props.getActivity local getRate = props.getRate local formatScriptsData = props.formatScriptsData local scriptDataStats = scriptData.dataStats local currEntry = scriptDataStats.dataSet:back() return Roact.createElement("Frame", { Size = UDim2.new(1, 0, 0, frameHeight), BackgroundTransparency = 1, LayoutOrder = layoutOrder, }, { button = Roact.createElement(BannerButton, { size = UDim2.new(1, 0, 0, ENTRY_HEIGHT), pos = UDim2.new(), isExpanded = showGraph, onButtonPress = onButtonPress, }, { ActivityBox = Roact.createElement("Frame", { Size = UDim2.new(0, ACTIVITYBOX_WIDTH, 0, ACTIVITYBOX_WIDTH), Position = UDim2.new(0, ACTIVITYBOX_PADDING, 0, (ENTRY_HEIGHT - ACTIVITYBOX_WIDTH) / 2), BackgroundColor3 = activityBoxColor, }), ScriptName = Roact.createElement(CellLabel, { text = scriptData.name, size = entryCellSize[1] - ACTIVITYBOX_PADDING_UDIM, pos = cellOffset[1] + ACTIVITYBOX_PADDING_UDIM, }), ScriptAcitivity = Roact.createElement(CellLabel, { text = formatScriptsData(currEntry.data[1]), size = entryCellSize[2], pos = cellOffset[2], }), scriptFreqStr = Roact.createElement(CellLabel, { text = formatScriptsData(currEntry.data[2]), size = entryCellSize[3], pos = cellOffset[3], }), upperHorizontalLine = Roact.createElement("Frame", { Size = UDim2.new(1, 0, 0, LINE_WIDTH), BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }), verticalLine1 = Roact.createElement("Frame", { Size = UDim2.new(0, LINE_WIDTH, 1, 0), Position = verticalOffsets[2], BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }), verticalLine2 = Roact.createElement("Frame", { Size = UDim2.new(0, LINE_WIDTH, 1, 0), Position = verticalOffsets[3], BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }), lowerHorizontalLine = Roact.createElement("Frame", { Size = UDim2.new(1, 0, 0, LINE_WIDTH), Position = UDim2.new(0, 0, 1, 0), BackgroundColor3 = LINE_COLOR, BorderSizePixel = 0, }), }), ActivityGraph = showGraph and Roact.createElement(LineGraph, { pos = UDim2.new(0, 0, 0, ENTRY_HEIGHT), size = UDim2.new(1, 0, 0, GRAPH_HEIGHT), graphData = scriptDataStats.dataSet, maxY = scriptDataStats.max[1], minY = scriptDataStats.min[1], getX = getX, getY = getActivity, stringFormatX = convertTimeStamp, stringFormatY = formatScriptsData, axisLabelX = "Timestamp", axisLabelY = HEADER_NAMES[2], }), RateGraph = showGraph and Roact.createElement(LineGraph, { pos = UDim2.new(0, 0, 0, ENTRY_HEIGHT + GRAPH_HEIGHT), size = UDim2.new(1, 0, 0, GRAPH_HEIGHT), graphData = scriptDataStats.dataSet, maxY = scriptDataStats.max[2], minY = scriptDataStats.min[2], getX = getX, getY = getRate, stringFormatX = convertTimeStamp, stringFormatY = formatScriptsData, axisLabelX = "Timestamp", axisLabelY = HEADER_NAMES[3], }), }) end
apache-2.0
apletnev/koreader
frontend/ui/data/keyboardlayouts/ja_keyboard.lua
5
10232
return { shiftmode_keys = {["Shift"] = true}, symbolmode_keys = {["記号"] = true, ["かな"] = true}, utf8mode_keys = {["゛"] = true}, umlautmode_keys = {["゜"] = true}, keys = { -- first row { -- 1 2 3 4 5 6 7 8 9 10 11 12 { "ア", "あ", "~", "`", "ア", "あ", "~", "`", "ア", "あ", "~", "`", }, { "カ", "か", "!", "1", "ガ", "が", "!", "1", "カ", "か", "!", "1", }, { "サ", "さ", "@", "2", "ザ", "ざ", "@", "2", "サ", "さ", "@", "2", }, { "タ", "た", "#", "3", "ダ", "だ", "#", "3", "タ", "た", "#", "3", }, { "ナ", "な", "$", "4", "ナ", "な", "$", "4", "ナ", "な", "$", "4", }, { "ハ", "は", "%", "5", "バ", "ば", "%", "5", "パ", "ぱ", "%", "5", }, { "マ", "ま", "^", "6", "マ", "ま", "^", "6", "マ", "ま", "^", "6", }, { "ヤ", "や", "&", "7", "ヤ", "や", "&", "7", "ヤ", "や", "&", "7", }, { "ラ", "ら", "*", "8", "ラ", "ら", "*", "8", "ラ", "ら", "*", "8", }, { "ワ", "わ", "(", "9", "ワ", "わ", "(", "9", "ワ", "わ", "(", "9", }, { "ァ", "ぁ", ")", "0", "ァ", "ぁ", ")", "0", "ァ", "ぁ", ")", "0", }, { "ャ", "ゃ", "_", "-", "ャ", "ゃ", "_", "-", "ャ", "ゃ", "_", "-", }, { "゛", "゛", "+", "=", "゛", "゛", "+", "=", "゛", "゛", "+", "=", }, }, -- second row { -- 1 2 3 4 5 6 7 8 9 10 11 12 { "イ", "い", "Q", "q", "イ", "い", "Q", "q", "イ", "い", "Q", "q", }, { "キ", "き", "W", "w", "ギ", "ぎ", "W", "w", "キ", "き", "W", "w", }, { "シ", "し", "E", "e", "ジ", "じ", "E", "e", "シ", "し", "E", "e", }, { "チ", "ち", "R", "r", "ヂ", "ぢ", "R", "r", "チ", "ち", "R", "r", }, { "ニ", "に", "T", "t", "ニ", "に", "T", "t", "ニ", "に", "T", "t", }, { "ヒ", "ひ", "Y", "y", "ビ", "び", "Y", "y", "ピ", "ぴ", "Y", "y", }, { "ミ", "み", "U", "u", "ミ", "み", "U", "u", "ミ", "み", "U", "u", }, { " ", " ", "I", "i", " ", " ", "I", "i", " ", " ", "I", "i", }, { "リ", "り", "O", "o", "リ", "り", "O", "o", "リ", "り", "O", "o", }, { " ", " ", "P", "p", " ", " ", "P", "p", " ", " ", "P", "p", }, { "ィ", "ぃ", "{", "[", "ィ", "ぃ", "{", "[", "ィ", "ぃ", "{", "[", }, { "ュ", "ゅ", "}", "]", "ュ", "ゅ", "}", "]", "ュ", "ゅ", "}", "]", }, { "゜", "゜", "|", "\\", "゜", "゜", "|", "\\", "゜", "゜", "|", "\\", }, }, -- third row { -- 1 2 3 4 5 6 7 8 9 10 11 12 { "ウ", "う", "A", "a", "ヴ", "ゔ", "A", "a", "ウ", "う", "A", "a", }, { "ク", "く", "S", "s", "グ", "ぐ", "S", "s", "ク", "く", "S", "s", }, { "ス", "す", "D", "d", "ズ", "ず", "D", "d", "ス", "す", "D", "d", }, { "ツ", "つ", "F", "f", "ヅ", "づ", "F", "f", "ツ", "つ", "F", "f", }, { "ヌ", "ぬ", "G", "g", "ヌ", "ぬ", "G", "g", "ヌ", "ぬ", "G", "g", }, { "フ", "ふ", "H", "h", "ブ", "ぶ", "H", "h", "プ", "ぷ", "H", "h", }, { "ム", "む", "J", "j", "ム", "む", "J", "j", "ム", "む", "J", "j", }, { "ユ", "ゆ", "K", "k", "ユ", "ゆ", "K", "k", "ユ", "ゆ", "K", "k", }, { "ル", "る", "L", "l", "ル", "る", "L", "l", "ル", "る", "L", "l", }, { "ヲ", "を", ":", ";", "ヲ", "を", ":", ";", "ヲ", "を", ":", ";", }, { "ゥ", "ぅ", "\"", "'", "ゥ", "ぅ", "\"", "'", "ゥ", "ぅ", "\"", "'", }, { "ョ", "ょ", "『", "「", "ョ", "ょ", "『", "「", "ョ", "ょ", "『", "「", }, { "ー", "ー", "』", "」", "ー", "ー", "』", "」", "ー", "ー", "』", "」", }, }, -- fourth row { -- 1 2 3 4 5 6 7 8 9 10 11 12 { "エ", "え", "Z", "z", "エ", "え", "Z", "z", "エ", "え", "Z", "z", }, { "ケ", "け", "X", "x", "ゲ", "げ", "X", "x", "ケ", "け", "X", "x", }, { "セ", "せ", "C", "c", "ゼ", "ぜ", "C", "c", "セ", "せ", "C", "c", }, { "テ", "て", "V", "v", "デ", "で", "V", "v", "テ", "て", "V", "v", }, { "ネ", "ね", "B", "b", "ネ", "ね", "B", "b", "ネ", "ね", "B", "b", }, { "ヘ", "へ", "N", "n", "ベ", "べ", "N", "n", "ペ", "ぺ", "N", "n", }, { "メ", "め", "M", "m", "メ", "め", "M", "m", "メ", "め", "M", "m", }, { " ", " ", "<", ",", " ", " ", "<", ",", " ", " ", "<", ",", }, { "レ", "れ", ">", ".", "レ", "れ", ">", ".", "レ", "れ", ">", ".", }, { " ", " ", "?", "/", " ", " ", "?", "/", " ", " ", "?", "/", }, { "ェ", "ぇ", "~", "・", "ェ", "ぇ", "~", "・", "ェ", "ぇ", "~", "・", }, { "ッ", "っ", "…", "、", "ッ", "っ", "…", "、", "ッ", "っ", "…", "、", }, { "、", "、", "¥", "。", "、", "、", "¥", "。", "、", "、", "¥", "。", }, }, -- fifth row { -- 1 2 3 4 5 6 7 8 9 10 11 12 { "オ", "お", "Á", "á", "オ", "お", "Á", "á", "オ", "お", "Á", "á", }, { "コ", "こ", "É", "é", "ゴ", "ご", "É", "é", "コ", "こ", "É", "é", }, { "ソ", "そ", "Í", "í", "ゾ", "ぞ", "Í", "í", "ソ", "そ", "Í", "í", }, { "ト", "と", "Ó", "ó", "ド", "ど", "Ó", "ó", "ト", "と", "Ó", "ó", }, { "ノ", "の", "Ú", "ú", "ノ", "の", "Ú", "ú", "ノ", "の", "Ú", "ú", }, { "ホ", "ほ", "Ñ", "ñ", "ボ", "ぼ", "Ñ", "ñ", "ホ", "ほ", "Ñ", "ñ", }, { "モ", "も", "Ü", "ü", "モ", "も", "Ü", "ü", "モ", "も", "Ü", "ü", }, { "ヨ", "よ", "¿", "ç", "ヨ", "よ", "¿", "ç", "ヨ", "よ", "¿", "ç", }, { "ロ", "ろ", "¡", "ß", "ロ", "ろ", "¡", "ß", "ロ", "ろ", "¡", "ß", }, { "ン", "ん", "Æ", "æ", "ン", "ん", "Æ", "æ", "ン", "ん", "Æ", "æ", }, { "ォ", "ぉ", "€", "£", "ォ", "ぉ", "€", "£", "ォ", "ぉ", "€", "£", }, { " ", " ", "«", "【", " ", " ", "«", "”", " ", " ", "«", "【", }, { "。", "。", "»", "】", "。", "。", "’", "”", "。", "。", "»", "】", }, }, -- sixth row { { label = "Shift", icon = "resources/icons/appbar.arrow.shift.png", width = 1.5 }, { "記号", "記号", "かな", "かな", "記号", "記号", "かな", "かな", "記号", "記号", "かな", "かな", width = 1.5}, { label = "空白", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", " ", width = 7.0}, { label = "Enter", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", "\n", icon = "resources/icons/appbar.arrow.enter.png", width = 1.5, }, { label = "Backspace", icon = "resources/icons/appbar.clear.reflect.horizontal.png", width = 1.5 }, }, }, }
agpl-3.0
kitala1/darkstar
scripts/zones/Riverne-Site_A01/npcs/Spatial_Displacement.lua
11
2971
----------------------------------- -- Area: Riverne Site #A01 -- NPC: Spacial Displacement ----------------------------------- ----------------------------------- -- onTrade ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger ----------------------------------- function onTrigger(player,npc) local id = npc:getID(); local base = 16900334; -- (First Spacial Displacement in NPC_LIST) if(id == base) then player:startEvent(0x2); elseif(id == base+1) then player:startEvent(0x3); elseif(id == base+2) then player:startEvent(0x4); elseif(id == base+7) then player:startEvent(0x7); elseif(id == base+8) then player:startEvent(0x8); elseif(id == base+9) then player:startEvent(0x9); elseif(id == base+10) then player:startEvent(0x0A); elseif(id == base+11) then player:startEvent(0xB); elseif(id == base+12) then player:startEvent(0xC); elseif(id == base+13) then player:startEvent(0xD); elseif(id == base+14) then player:startEvent(0xE); elseif(id == base+15) then player:startEvent(0xF); elseif(id == base+16) then player:startEvent(0x10); elseif(id == base+18) then player:startEvent(0x12); elseif(id == base+20) then player:startEvent(0x14); elseif(id == base+21) then player:startEvent(0x15); elseif(id == base+22) then player:startEvent(0x16); elseif(id == base+23) then player:startEvent(0x17); elseif(id == base+24) then player:startEvent(0x18); elseif(id == base+25) then player:startEvent(0x19); elseif(id == base+26) then player:startEvent(0x1A); elseif(id == base+27) then player:startEvent(0x1b); elseif(id == base+28) then player:startEvent(0x1C); elseif(id == base+29) then player:startEvent(0x1d); elseif(id == base+30) then player:startEvent(0x1E); elseif(id == base+31) then player:startEvent(0x1F); elseif(id == base+33) then player:startEvent(0x21); elseif(id == base+34) then player:startEvent(0x22); elseif(id == base+35) then player:startEvent(0x23); elseif(id == base+36) then player:startEvent(0x24); elseif(id == base+37) then player:startEvent(0x25); elseif(id == base+38) then player:startEvent(0x26); elseif(id == base+39) then player:startEvent(0x27); end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x23 and option == 1) then player:setPos(12.527,0.345,-539.602,127,31); -- to Monarch Linn (Retail confirmed) elseif(csid == 0x0A and option == 1) then player:setPos(-538.526,-29.5,359.219,255,25); -- back to Misareaux Coast (Retail confirmed) end; end;
gpl-3.0
kitala1/darkstar
scripts/zones/Mhaura/TextIDs.lua
5
1944
-- Variable TextID Description text -- General Texts ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item>. Come back after sorting your inventory. ITEM_OBTAINED = 6382; -- Obtained: <item>. GIL_OBTAINED = 6383; -- Obtained <number> gil. KEYITEM_OBTAINED = 6385; -- Obtained key item: <keyitem>. NOT_HAVE_ENOUGH_GIL = 6387; -- You do not have enough gil. HOMEPOINT_SET = 6466; -- Home point set! FISHING_MESSAGE_OFFSET = 6692; -- You can't fish here. DO_NOT_POSSESS = 7726; -- You do not possess . You were not permitted to board the ship... -- Other Texts MAURIRI_DELIVERY_DIALOG = 7723; -- Mauriri is my name, and sending parcels from Mhaura is my game. PANORU_DELIVERY_DIALOG = 7724; -- Looking for a delivery company that isn't lamey-wame? The quality of my service puts Mauriri to shame! -- Quest Dialog NOMAD_MOOGLE_DIALOG = 6787; -- I'm a traveling moogle, kupo. I help adventurers in the Outlands access items they have stored in a Mog House elsewhere, kupo. SUBJOB_UNLOCKED = 7028; -- You can now use support jobs! GOLDSMITHING_GUILD = 7131; -- Everything you need for your goldsmithing needs! SMITHING_GUILD = 7132; -- Welcome to the Blacksmiths' Guild salesroom! RAMUH_UNLOCKED = 7345; -- You are now able to summon -- Shop Texts GRAINE_SHOP_DIALOG = 7127; -- Hello there, I'm Graine the armorer. I've got just what you need! PIKINIMIKINI_SHOP_DIALOG = 7129; -- Hi, I'm Pikini-Mikini, Mhaura's item seller. I've got the wares, so size doesn't matter! RUNITOMONITO_SHOP_DIALOG = 7128; -- Hi! Welcome! I'm Runito-Monito, and weapons is my middle name! TYAPADOLIH_SHOP_DIALOG = 7130; -- Welcome, strrranger! Tya Padolih's the name, and dealin' in magic is my game! -- conquest Base CONQUEST_BASE = 6516; -- Tallying conquest results... -- Porter Moogle RETRIEVE_DIALOG_ID = 7761; -- You retrieve a <item> from the porter moogle's care.
gpl-3.0
kitala1/darkstar
scripts/globals/items/head_of_napa.lua
35
1195
----------------------------------------- -- ID: 5235 -- Item: head_of_napa -- Food Effect: 5Min, All Races ----------------------------------------- -- Agility 1 -- Vitality -3 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,300,5235); end; ----------------------------------- -- onEffectGain Action ----------------------------------- function onEffectGain(target,effect) target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -3); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -3); end;
gpl-3.0
fqrouter/luci
applications/luci-asterisk/luasrc/model/cbi/asterisk-mod-chan.lua
80
1726
--[[ LuCI - Lua Configuration Interface Copyright 2008 Steven Barth <steven@midlink.org> Copyright 2008 Jo-Philipp Wich <xm@leipzig.freifunk.net> Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 $Id$ ]]-- cbimap = Map("asterisk", "asterisk", "") module = cbimap:section(TypedSection, "module", "Modules", "") module.anonymous = true chan_agent = module:option(ListValue, "chan_agent", "Agent Proxy Channel", "") chan_agent:value("yes", "Load") chan_agent:value("no", "Do Not Load") chan_agent:value("auto", "Load as Required") chan_agent.rmempty = true chan_alsa = module:option(ListValue, "chan_alsa", "Channel driver for GTalk", "") chan_alsa:value("yes", "Load") chan_alsa:value("no", "Do Not Load") chan_alsa:value("auto", "Load as Required") chan_alsa.rmempty = true chan_gtalk = module:option(ListValue, "chan_gtalk", "Channel driver for GTalk", "") chan_gtalk:value("yes", "Load") chan_gtalk:value("no", "Do Not Load") chan_gtalk:value("auto", "Load as Required") chan_gtalk.rmempty = true chan_iax2 = module:option(Flag, "chan_iax2", "Option chan_iax2", "") chan_iax2.rmempty = true chan_local = module:option(ListValue, "chan_local", "Local Proxy Channel", "") chan_local:value("yes", "Load") chan_local:value("no", "Do Not Load") chan_local:value("auto", "Load as Required") chan_local.rmempty = true chan_sip = module:option(ListValue, "chan_sip", "Session Initiation Protocol (SIP)", "") chan_sip:value("yes", "Load") chan_sip:value("no", "Do Not Load") chan_sip:value("auto", "Load as Required") chan_sip.rmempty = true return cbimap
apache-2.0
kitala1/darkstar
scripts/zones/RuLude_Gardens/npcs/Neraf-Najiruf.lua
19
2005
----------------------------------- -- Area: Ru'Lud Gardens -- NPC: Neraf-Najiruf -- Involved in Quests: Save my Sister -- @zone 243 -- @pos -36 2 60 ----------------------------------- package.loaded["scripts/zones/RuLude_Gardens/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/quests"); require("scripts/zones/RuLude_Gardens/TextIDs"); ----------------------------------- -- onTrade Action ----------------------------------- function onTrade(player,npc,trade) end; ----------------------------------- -- onTrigger Action ----------------------------------- function onTrigger(player,npc) saveMySister = player:getQuestStatus(JEUNO,SAVE_MY_SISTER); if(saveMySister == QUEST_AVAILABLE and player:getVar("saveMySisterVar") == 3) then player:startEvent(0x0062); -- Real start of this quest (with addquest) elseif(saveMySister == QUEST_ACCEPTED) then player:startEvent(0x0063); -- During quest elseif(saveMySister == QUEST_COMPLETED and player:hasKeyItem(DUCAL_GUARDS_LANTERN) == true) then player:startEvent(0x0061); -- last CS (after talk with baudin) else player:startEvent(0x009C); -- Standard dialog end end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); if(csid == 0x0062) then player:addQuest(JEUNO,SAVE_MY_SISTER); player:setVar("saveMySisterVar", 0); player:addKeyItem(DUCAL_GUARDS_LANTERN); player:messageSpecial(KEYITEM_OBTAINED,DUCAL_GUARDS_LANTERN); elseif(csid == 0x0061) then player:delKeyItem(DUCAL_GUARDS_LANTERN); player:setVar("saveMySisterFireLantern", 0); end end;
gpl-3.0
kitala1/darkstar
scripts/globals/spells/foe_lullaby.lua
11
1176
----------------------------------------- -- Spell: Foe Lullaby ----------------------------------------- require("scripts/globals/status"); require("scripts/globals/magic"); ----------------------------------------- -- OnSpellCast ----------------------------------------- function onMagicCastingCheck(caster,target,spell) return 0; end; function onSpellCast(caster,target,spell) local duration = 30; local pCHR = caster:getStat(MOD_CHR); local mCHR = target:getStat(MOD_CHR); local dCHR = (pCHR - mCHR); local resm = applyResistance(caster,spell,target,dCHR,40,0); if(resm < 0.5) then spell:setMsg(85);--resist message return EFFECT_LULLABY; end if(target:hasImmunity(1) or 100 * math.random() < target:getMod(MOD_SLEEPRES)) then --No effect spell:setMsg(75); else local iBoost = caster:getMod(MOD_LULLABY_EFFECT) + caster:getMod(MOD_ALL_SONGS_EFFECT); duration = duration * ((iBoost * 0.1) + (caster:getMod(MOD_SONG_DURATION_BONUS)/100) + 1); if(target:addStatusEffect(EFFECT_LULLABY,1,0,duration)) then spell:setMsg(237); else spell:setMsg(75); end end return EFFECT_LULLABY; end;
gpl-3.0
kitala1/darkstar
scripts/globals/items/bataquiche_+1.lua
35
1474
----------------------------------------- -- ID: 5169 -- Item: Bataquiche +1 -- Food Effect: 60Min, All Races ----------------------------------------- -- Magic 10 -- Agility 1 -- Vitality -1 -- Ranged ATT % 7 -- Ranged ATT Cap 20 ----------------------------------------- require("scripts/globals/status"); ----------------------------------------- -- OnItemCheck ----------------------------------------- function onItemCheck(target) local result = 0; if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then result = 246; end return result; end; ----------------------------------------- -- OnItemUse ----------------------------------------- function onItemUse(target) target:addStatusEffect(EFFECT_FOOD,0,0,3600,5169); end; ----------------------------------------- -- onEffectGain Action ----------------------------------------- function onEffectGain(target,effect) target:addMod(MOD_MP, 10); target:addMod(MOD_AGI, 1); target:addMod(MOD_VIT, -1); target:addMod(MOD_FOOD_RATTP, 7); target:addMod(MOD_FOOD_RATT_CAP, 20); end; ----------------------------------------- -- onEffectLose Action ----------------------------------------- function onEffectLose(target,effect) target:delMod(MOD_MP, 10); target:delMod(MOD_AGI, 1); target:delMod(MOD_VIT, -1); target:delMod(MOD_FOOD_RATTP, 7); target:delMod(MOD_FOOD_RATT_CAP, 20); end;
gpl-3.0
hanxi/cocos2d-x-v3.1
frameworks/cocos2d-x/cocos/scripting/lua-bindings/auto/api/ComController.lua
6
1099
-------------------------------- -- @module ComController -- @extend Component,InputDelegate -------------------------------- -- @function [parent=#ComController] create -- @param self -- @return ComController#ComController ret (return value: ccs.ComController) -------------------------------- -- @function [parent=#ComController] createInstance -- @param self -- @return Ref#Ref ret (return value: cc.Ref) -------------------------------- -- @function [parent=#ComController] setEnabled -- @param self -- @param #bool bool -------------------------------- -- @function [parent=#ComController] isEnabled -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ComController] update -- @param self -- @param #float float -------------------------------- -- @function [parent=#ComController] init -- @param self -- @return bool#bool ret (return value: bool) -------------------------------- -- @function [parent=#ComController] ComController -- @param self return nil
mit
kitala1/darkstar
scripts/zones/PsoXja/Zone.lua
13
4106
----------------------------------- -- -- Zone: PsoXja (9) -- ----------------------------------- package.loaded["scripts/zones/PsoXja/TextIDs"] = nil; ----------------------------------- require("scripts/globals/settings"); require("scripts/globals/status"); require("scripts/zones/PsoXja/TextIDs"); require("scripts/globals/missions"); ----------------------------------- -- onInitialize ----------------------------------- function onInitialize(zone) zone:registerRegion(1,-21.469,27.000,-24.255, -18.723,32.000,-19.877); -- 40 cap (H-8 Tower) zone:registerRegion(2, 337.376,27,-19.836, 342.340,32,-16.055); -- 50 cap area (J-8 Tower) zone:registerRegion(3, 95.659,42,-302.390, 99.973,48,-297.744); -- 60 cap area (H-10 Tower) zone:registerRegion(4, -384.452,26,257.961, -379.945,32,262.558); -- Uncapped area 1 (F-7 Tower) zone:registerRegion(5, -302.493,42,-179.995, -297.386,48,-176.078); -- Uncapped area 2 (G-9 Tower) zone:registerRegion(6, 299.847,42, 257.716, 303.824,48,262.391); -- Uncapped area 3 (I-7 Tower) UpdateTreasureSpawnPoint(16814557); end; ----------------------------------- -- onConquestUpdate ----------------------------------- function onConquestUpdate(zone, updatetype) local players = zone:getPlayers(); for name, player in pairs(players) do conquestUpdate(zone, player, updatetype, CONQUEST_BASE); end end; ----------------------------------- -- onZoneIn ----------------------------------- function onZoneIn(player,prevZone) local cs = -1; local playerX = player:getXPos(); if ((playerX == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then player:setPos(-29.956,-1.903,212.521,188); end if(ENABLE_COP_ZONE_CAP == 1)then local LVLcap = player:getVar("PSOXJA_RESTRICTION_LVL"); if (LVLcap > 0)then player:addStatusEffect(EFFECT_LEVEL_RESTRICTION,LVLcap,0,0);-- ZONE LEVEL RESTRICTION end end if(playerX == -300 and player:getCurrentMission(COP) == THE_ENDURING_TUMULT_OF_WAR and player:getVar("PromathiaStatus")==2)then cs = 0x0001; -- COP event elseif(playerX == 220 and player:getCurrentMission(COP) == THREE_PATHS and player:getVar("COP_Tenzen_s_Path") == 8)then cs = 0x0004; end return cs; end; ----------------------------------- -- onRegionEnter ----------------------------------- function onRegionEnter(player,region) if(region:GetRegionID() == 1) then player:startEvent(0x0014); elseif(region:GetRegionID() == 2) then player:startEvent(0x0015); elseif(region:GetRegionID() == 3) then player:startEvent(0x0016); elseif(region:GetRegionID() == 4) then player:startEvent(0x0017); elseif(region:GetRegionID() == 5) then player:startEvent(0x0018); elseif(region:GetRegionID() == 6) then player:startEvent(0x0019); end end; ----------------------------------- -- onRegionLeave ----------------------------------- function onRegionLeave(player,region) end; ----------------------------------- -- onEventUpdate ----------------------------------- function onEventUpdate(player,csid,option) --printf("CSID: %u",csid); --printf("RESULT: %u",option); end; ----------------------------------- -- onEventFinish ----------------------------------- function onEventFinish(player,csid,option) -- printf("CSID: %u",csid); -- printf("RESULT: %u",option); if(csid == 0x0001)then player:setVar("PromathiaStatus",3); elseif(csid == 0x0004)then player:setVar("COP_Tenzen_s_Path",9); elseif(csid == 0x0014 and option == 1) then player:setPos(-20,-60.250,-60,63,111); elseif(csid == 0x0015 and option == 1) then player:setPos(260,-0.25,-20,254,111); elseif(csid == 0x0016 and option == 1) then player:setPos(60,-0.250,-340.000,190,111); elseif(csid == 0x0017 and option == 1) then player:setPos(-340,-100.250,140,63,111); elseif(csid == 0x0018 and option == 1) then player:setPos(-180,-40.25 ,-220,0,111); elseif(csid == 0x0019 and option == 1) then player:setPos(100,-20.25,140,64,111); end end;
gpl-3.0