repo_name stringlengths 6 69 | path stringlengths 6 178 | copies stringclasses 278
values | size stringlengths 4 7 | content stringlengths 671 917k | license stringclasses 15
values |
|---|---|---|---|---|---|
nasomi/darkstar | scripts/globals/weaponskills/rock_crusher.lua | 30 | 1240 | -----------------------------------
-- Rock Crusher
-- Staff weapon skill
-- Skill Level: 40
-- Delivers an earth elemental attack. Damage varies with TP.
-- Aligned with the Thunder Gorget.
-- Aligned with the Thunder Belt.
-- Element: Earth
-- Modifiers: STR:40% ; INT:40%
-- 100%TP 200%TP 300%TP
-- 1.00 2.00 2.50
-----------------------------------
require("scripts/globals/magic");
require("scripts/globals/status");
require("scripts/globals/settings");
require("scripts/globals/weaponskills");
-----------------------------------
function onUseWeaponSkill(player, target, wsID)
local params = {};
params.ftp100 = 1; params.ftp200 = 2; params.ftp300 = 2.5;
params.str_wsc = 0.2; params.dex_wsc = 0.0; params.vit_wsc = 0.0; params.agi_wsc = 0.0; params.int_wsc = 0.2; params.mnd_wsc = 0.0; params.chr_wsc = 0.0;
params.ele = ELE_EARTH;
params.skill = SKILL_STF;
params.includemab = true;
if (USE_ADOULIN_WEAPON_SKILL_CHANGES == true) then
params.str_wsc = 0.4; params.int_wsc = 0.4;
end
local damage, criticalHit, tpHits, extraHits = doMagicWeaponskill(player, target, params);
damage = damage * WEAPON_SKILL_POWER
return tpHits, extraHits, criticalHit, damage;
end
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Ordelles_Caves/npcs/qm3.lua | 19 | 1571 | -----------------------------------
-- Area: Ordelle's Caves
-- NPC: ??? (qm3)
-- Involved in Quest: A Squire's Test II
-- @pos -139 0.1 264 193
-------------------------------------
package.loaded["scripts/zones/Ordelles_Caves/TextIDs"] = nil;
-------------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Ordelles_Caves/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (os.time() - player:getVar("SquiresTestII") <= 60 and player:hasKeyItem(STALACTITE_DEW) == false) then
player:messageSpecial(A_SQUIRE_S_TEST_II_DIALOG_II);
player:addKeyItem(STALACTITE_DEW);
player:messageSpecial(KEYITEM_OBTAINED, STALACTITE_DEW);
player:setVar("SquiresTestII",0);
elseif (player:hasKeyItem(STALACTITE_DEW)) then
player:messageSpecial(A_SQUIRE_S_TEST_II_DIALOG_III);
else
player:messageSpecial(NOTHING_OUT_OF_ORDINARY);
player:setVar("SquiresTestII",0);
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 |
nasomi/darkstar | scripts/globals/mobskills/Pelagic_Tempest.lua | 25 | 1133 | ---------------------------------------------
-- Pelagic Tempest
--
-- Description: Delivers an area attack that inflicts Shock and Terror.
-- Type: Physical?
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: 10' cone
-- Notes: Used by Murex affiliated with lightning element. Shock effect is fairly strong (28/tick).
---------------------------------------------
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 = 2;
local dmgmod = 3;
local info = MobPhysicalMove(mob,target,skill,numhits,accmod,dmgmod,TP_NO_EFFECT);
local dmg = MobFinalAdjustments(info.dmg,mob,skill,target,MOBSKILL_PHYSICAL,MOBPARAM_BLUNT,info.hitslanded);
MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_SHOCK, 28, 3, 180);
MobPhysicalStatusEffectMove(mob, target, skill, EFFECT_TERROR, 1, 0, 180);
target:delHP(dmg);
return dmg;
end;
| gpl-3.0 |
nasomi/darkstar | scripts/globals/items/bowl_of_pumpkin_soup.lua | 35 | 1656 | -----------------------------------------
-- ID: 4430
-- Item: bowl_of_pumpkin_soup
-- Food Effect: 3Hrs, All Races
-----------------------------------------
-- HP % 1
-- Vitality -1
-- Agility 3
-- HP Recovered While Healing 5
-- Ranged Accuracy % 8 (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,10800,4430);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_FOOD_HPP, 1);
target:addMod(MOD_FOOD_HP_CAP, 999);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_AGI, 3);
target:addMod(MOD_HPHEAL, 5);
target:addMod(MOD_FOOD_RACCP, 8);
target:addMod(MOD_FOOD_RACC_CAP, 20);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_FOOD_HPP, 1);
target:delMod(MOD_FOOD_HP_CAP, 999);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_AGI, 3);
target:delMod(MOD_HPHEAL, 5);
target:delMod(MOD_FOOD_RACCP, 8);
target:delMod(MOD_FOOD_RACC_CAP, 20);
end;
| gpl-3.0 |
shangjiyu/luci-with-extra | applications/luci-app-minidlna/luasrc/model/cbi/minidlna.lua | 60 | 5493 | -- Copyright 2012 Gabor Juhos <juhosg@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
local m, s, o
m = Map("minidlna", translate("miniDLNA"),
translate("MiniDLNA is server software with the aim of being fully compliant with DLNA/UPnP-AV clients."))
m:section(SimpleSection).template = "minidlna_status"
s = m:section(TypedSection, "minidlna", "miniDLNA Settings")
s.addremove = false
s.anonymous = true
s:tab("general", translate("General Settings"))
s:tab("advanced", translate("Advanced Settings"))
o = s:taboption("general", Flag, "enabled", translate("Enable:"))
o.rmempty = false
function o.cfgvalue(self, section)
return luci.sys.init.enabled("minidlna") and self.enabled or self.disabled
end
function o.write(self, section, value)
if value == "1" then
luci.sys.init.enable("minidlna")
luci.sys.call("/etc/init.d/minidlna start >/dev/null")
else
luci.sys.call("/etc/init.d/minidlna stop >/dev/null")
luci.sys.init.disable("minidlna")
end
return Flag.write(self, section, value)
end
o = s:taboption("general", Value, "port", translate("Port:"),
translate("Port for HTTP (descriptions, SOAP, media transfer) traffic."))
o.datatype = "port"
o.default = 8200
o = s:taboption("general", Value, "interface", translate("Interfaces:"),
translate("Network interfaces to serve."))
o.template = "cbi/network_ifacelist"
o.widget = "checkbox"
o.nocreate = true
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if val then
local ifc
for ifc in val:gmatch("[^,%s]+") do
rv[#rv+1] = ifc
end
end
return rv
end
function o.write(self, section, value)
local rv = { }
local ifc
for ifc in luci.util.imatch(value) do
rv[#rv+1] = ifc
end
Value.write(self, section, table.concat(rv, ","))
end
o = s:taboption("general", Value, "friendly_name", translate("Friendly name:"),
translate("Set this if you want to customize the name that shows up on your clients."))
o.rmempty = true
o.placeholder = "OpenWrt DLNA Server"
o = s:taboption("advanced", Value, "db_dir", translate("Database directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its database and album art cache."))
o.rmempty = true
o.placeholder = "/var/cache/minidlna"
o = s:taboption("advanced", Value, "log_dir", translate("Log directory:"),
translate("Set this if you would like to specify the directory where you want MiniDLNA to store its log file."))
o.rmempty = true
o.placeholder = "/var/log"
s:taboption("advanced", Flag, "inotify", translate("Enable inotify:"),
translate("Set this to enable inotify monitoring to automatically discover new files."))
s:taboption("advanced", Flag, "enable_tivo", translate("Enable TIVO:"),
translate("Set this to enable support for streaming .jpg and .mp3 files to a TiVo supporting HMO."))
o.rmempty = true
o = s:taboption("advanced", Flag, "strict_dlna", translate("Strict to DLNA standard:"),
translate("Set this to strictly adhere to DLNA standards. This will allow server-side downscaling of very large JPEG images, which may hurt JPEG serving performance on (at least) Sony DLNA products."))
o.rmempty = true
o = s:taboption("advanced", Value, "presentation_url", translate("Presentation URL:"))
o.rmempty = true
o.placeholder = "http://192.168.1.1/"
o = s:taboption("advanced", Value, "notify_interval", translate("Notify interval:"),
translate("Notify interval in seconds."))
o.datatype = "uinteger"
o.placeholder = 900
o = s:taboption("advanced", Value, "serial", translate("Announced serial number:"),
translate("Serial number the miniDLNA daemon will report to clients in its XML description."))
o.placeholder = "12345678"
s:taboption("advanced", Value, "model_number", translate("Announced model number:"),
translate("Model number the miniDLNA daemon will report to clients in its XML description."))
o.placholder = "1"
o = s:taboption("advanced", Value, "minissdpsocket", translate("miniSSDP socket:"),
translate("Specify the path to the MiniSSDPd socket."))
o.rmempty = true
o.placeholder = "/var/run/minissdpd.sock"
o = s:taboption("general", ListValue, "root_container", translate("Root container:"))
o:value(".", translate("Standard container"))
o:value("B", translate("Browse directory"))
o:value("M", translate("Music"))
o:value("V", translate("Video"))
o:value("P", translate("Pictures"))
s:taboption("general", DynamicList, "media_dir", translate("Media directories:"),
translate("Set this to the directory you want scanned. If you want to restrict the directory to a specific content type, you can prepend the type ('A' for audio, 'V' for video, 'P' for images), followed by a comma, to the directory (eg. media_dir=A,/mnt/media/Music). Multiple directories can be specified."))
o = s:taboption("general", DynamicList, "album_art_names", translate("Album art names:"),
translate("This is a list of file names to check for when searching for album art."))
o.rmempty = true
o.placeholder = "Cover.jpg"
function o.cfgvalue(self, section)
local rv = { }
local val = Value.cfgvalue(self, section)
if type(val) == "table" then
val = table.concat(val, "/")
elseif not val then
val = ""
end
local file
for file in val:gmatch("[^/%s]+") do
rv[#rv+1] = file
end
return rv
end
function o.write(self, section, value)
local rv = { }
local file
for file in luci.util.imatch(value) do
rv[#rv+1] = file
end
Value.write(self, section, table.concat(rv, "/"))
end
return m
| apache-2.0 |
renyaoxiang/QSanguosha-For-Hegemony | lua/ai/formation-ai.lua | 2 | 24121 | --[[********************************************************************
Copyright (c) 2013-2015 Mogara
This file is part of QSanguosha-Hegemony.
This game 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.0
of the License, or (at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
General Public License for more details.
See the LICENSE file for more details.
Mogara
*********************************************************************]]
sgs.ai_skill_invoke.tuntian = function(self, data)
if not (self:willShowForAttack() or self:willShowForDefence()) then
return false
end
return true
end
sgs.ai_skill_invoke._tuntian = function(self, data)
if not (self:willShowForAttack() or self:willShowForDefence()) then
return false
end
return true
end
local jixi_skill = {}
jixi_skill.name = "jixi"
table.insert(sgs.ai_skills, jixi_skill)
jixi_skill.getTurnUseCard = function(self)
if self.player:getPile("field"):isEmpty()
or (self.player:getHandcardNum() >= self.player:getHp() + 2
and self.player:getPile("field"):length() <= self.room:getAlivePlayers():length() / 2 - 1) then
return
end
local can_use = false
for i = 0, self.player:getPile("field"):length() - 1, 1 do
local snatch = sgs.Sanguosha:getCard(self.player:getPile("field"):at(i))
local snatch_str = ("snatch:jixi[%s:%s]=%d&jixi"):format(snatch:getSuitString(), snatch:getNumberString(), self.player:getPile("field"):at(i))
local jixisnatch = sgs.Card_Parse(snatch_str)
assert(jixisnatch)
for _, player in sgs.qlist(self.room:getOtherPlayers(self.player)) do
if (self.player:distanceTo(player, 1) <= 1 + sgs.Sanguosha:correctCardTarget(sgs.TargetModSkill_DistanceLimit, self.player, jixisnatch))
and self:hasTrickEffective(jixisnatch, player) then
local suit = snatch:getSuitString()
local number = snatch:getNumberString()
local card_id = snatch:getEffectiveId()
local card_str = ("snatch:jixi[%s:%s]=%d%s"):format(suit, number, card_id, "&jixi")
local snatch = sgs.Card_Parse(card_str)
assert(snatch)
return snatch
end
end
end
end
sgs.ai_view_as.jixi = function(card, player, card_place)
local suit = card:getSuitString()
local number = card:getNumberString()
local card_id = card:getEffectiveId()
if card_place == sgs.Player_PlaceSpecial and player:getPileName(card_id) == "field" then
return ("snatch:jixi[%s:%s]=%d%s"):format(suit, number, card_id, "&jixi")
end
end
local getZiliangCard = function(self, damage)
if not (damage.to:getPhase() == sgs.Player_NotActive and self:needKongcheng(damage.to, true)) then
local ids = sgs.QList2Table(self.player:getPile("field"))
local cards = {}
for _, id in ipairs(ids) do table.insert(cards, sgs.Sanguosha:getCard(id)) end
for _, card in ipairs(cards) do
if card:isKindOf("Peach") or card:isKindOf("Analeptic") then return card:getEffectiveId() end
end
for _, card in ipairs(cards) do
if card:isKindOf("Jink") then return card:getEffectiveId() end
end
self:sortByKeepValue(cards, true)
return cards[1]:getEffectiveId()
else
return nil
end
end
sgs.ai_skill_use["@@ziliang"] = function(self)
local damage = self.player:getTag("ziliang_aidata"):toDamage()
local id = getZiliangCard(self, damage)
if id then
return "@ZiliangCard=" .. tostring(id) .. "&ziliang"
end
return "."
end
local function huyuan_validate(self, equip_type, is_handcard)
local targets = {}
if is_handcard then targets = self.friends else targets = self.friends_noself end
if equip_type == "SilverLion" then
for _, enemy in ipairs(self.enemies) do
if enemy:hasShownSkill("bazhen") and not enemy:getArmor() then table.insert(targets, enemy) end
end
end
for _, friend in ipairs(targets) do
local has_equip = false
for _, equip in sgs.qlist(friend:getEquips()) do
if equip:isKindOf(equip_type == "SilverLion" and "Armor" or equip_type) then
has_equip = true
break
end
end
if not has_equip and not ((equip_type == "Armor" or equip_type == "SilverLion") and friend:hasShownSkill("bazhen")) then
self:sort(self.enemies, "defense")
for _, enemy in ipairs(self.enemies) do
if friend:distanceTo(enemy) == 1 and self.player:canDiscard(enemy, "he") then
enemy:setFlags("AI_HuyuanToChoose")
return friend
end
end
end
end
return nil
end
sgs.ai_skill_use["@@huyuan"] = function(self, prompt)
local cards = self.player:getHandcards()
cards = sgs.QList2Table(cards)
self:sortByKeepValue(cards)
if self.player:hasArmorEffect("SilverLion") then
local player = huyuan_validate(self, "SilverLion", false)
if player then return "@HuyuanCard=" .. self.player:getArmor():getEffectiveId() .. "->" .. player:objectName() end
end
if self.player:getOffensiveHorse() then
local player = huyuan_validate(self, "OffensiveHorse", false)
if player then return "@HuyuanCard=" .. self.player:getOffensiveHorse():getEffectiveId() .. "->" .. player:objectName() end
end
if self.player:getWeapon() then
local player = huyuan_validate(self, "Weapon", false)
if player then return "@HuyuanCard=" .. self.player:getWeapon():getEffectiveId() .. "->" .. player:objectName() end
end
if self.player:getArmor() and self.player:getLostHp() <= 1 and self.player:getHandcardNum() >= 3 then
local player = huyuan_validate(self, "Armor", false)
if player then return "@HuyuanCard=" .. self.player:getArmor():getEffectiveId() .. "->" .. player:objectName() end
end
for _, card in ipairs(cards) do
if card:isKindOf("DefensiveHorse") then
local player = huyuan_validate(self, "DefensiveHorse", true)
if player then return "@HuyuanCard=" .. card:getEffectiveId() .. "->" .. player:objectName() end
end
end
for _, card in ipairs(cards) do
if card:isKindOf("OffensiveHorse") then
local player = huyuan_validate(self, "OffensiveHorse", true)
if player then return "@HuyuanCard=" .. card:getEffectiveId() .. "->" .. player:objectName() end
end
end
for _, card in ipairs(cards) do
if card:isKindOf("Weapon") then
local player = huyuan_validate(self, "Weapon", true)
if player then return "@HuyuanCard=" .. card:getEffectiveId() .. "->" .. player:objectName() end
end
end
for _, card in ipairs(cards) do
if card:isKindOf("SilverLion") then
local player = huyuan_validate(self, "SilverLion", true)
if player then return "@HuyuanCard=" .. card:getEffectiveId() .. "->" .. player:objectName() end
end
if card:isKindOf("Armor") and huyuan_validate(self, "Armor", true) then
local player = huyuan_validate(self, "Armor", true)
if player then return "@HuyuanCard=" .. card:getEffectiveId() .. "->" .. player:objectName() end
end
end
end
sgs.ai_skill_playerchosen.huyuan = function(self, targets)
targets = sgs.QList2Table(targets)
for _, p in ipairs(targets) do
if p:hasFlag("AI_HuyuanToChoose") then
p:setFlags("-AI_HuyuanToChoose")
return p
end
end
return targets[1]
end
sgs.ai_card_intention.HuyuanCard = function(self, card, from, to)
if to[1]:hasShownSkill("bazhen") then
if sgs.Sanguosha:getCard(card:getEffectiveId()):isKindOf("SilverLion") then
sgs.updateIntention(from, to[1], 10)
return
end
end
sgs.updateIntention(from, to[1], -50)
end
sgs.ai_cardneed.huyuan = sgs.ai_cardneed.equip
sgs.huyuan_keep_value = {
Peach = 6,
Jink = 5.1,
EquipCard = 4.8
}
function SmartAI:isTiaoxinTarget(enemy)
if not enemy then self.room:writeToConsole(debug.traceback()) return end
if getCardsNum("Slash", enemy, self.player) < 1 and self.player:getHp() > 1 and not self:canHit(self.player, enemy)
and not (enemy:hasWeapon("DoubleSword") and self.player:getGender() ~= enemy:getGender())
then return true end
if sgs.card_lack[enemy:objectName()]["Slash"] == 1
or self:needLeiji(self.player, enemy)
or self:getDamagedEffects(self.player, enemy, true)
or self:needToLoseHp(self.player, enemy, true, true)
then return true end
if self.player:hasSkill("xiangle") and (enemy:getHandcardNum() < 2 or getKnownCard(enemy, self.player, "BasicCard") < 2
and enemy:getHandcardNum() - getKnownNum(enemy, self.player) < 2) then return true end
return false
end
local tiaoxin_skill = {}
tiaoxin_skill.name = "tiaoxin"
table.insert(sgs.ai_skills, tiaoxin_skill)
tiaoxin_skill.getTurnUseCard = function(self)
if not self:willShowForAttack() then
return
end
if self.player:hasUsed("TiaoxinCard") then return end
return sgs.Card_Parse("@TiaoxinCard=.&tiaoxin")
end
sgs.ai_skill_use_func.TiaoxinCard = function(TXCard, use, self)
local distance = use.defHorse and 1 or 0
local targets = {}
for _, enemy in ipairs(self.enemies) do
if enemy:distanceTo(self.player, distance) <= enemy:getAttackRange() and not self:doNotDiscard(enemy) and self:isTiaoxinTarget(enemy) then
table.insert(targets, enemy)
end
end
if #targets == 0 then return end
sgs.ai_use_priority.TiaoxinCard = 8
if not self.player:getArmor() and not self.player:isKongcheng() then
for _, card in sgs.qlist(self.player:getCards("h")) do
if card:isKindOf("Armor") and self:evaluateArmor(card) > 3 then
sgs.ai_use_priority.TiaoxinCard = 5.9
break
end
end
end
if use.to then
self:sort(targets, "defenseSlash")
use.to:append(targets[1])
end
use.card = TXCard
end
sgs.ai_skill_cardask["@tiaoxin-slash"] = function(self, data, pattern, target)
if target then
local cards = self:getCards("Slash")
self:sortByUseValue(cards)
for _, slash in ipairs(cards) do
if self:isFriend(target) and self:slashIsEffective(slash, target) then
if self:needLeiji(target, self.player) then return slash:toString() end
if self:getDamagedEffects(target, self.player) then return slash:toString() end
if self:needToLoseHp(target, self.player, nil, true) then return slash:toString() end
end
if not self:isFriend(target) and self:slashIsEffective(slash, target)
and not self:getDamagedEffects(target, self.player, true) and not self:needLeiji(target, self.player) then
return slash:toString()
end
end
for _, slash in ipairs(cards) do
if not self:isFriend(target) then
if not self:needLeiji(target, self.player) and not self:getDamagedEffects(target, self.player, true) then return slash:toString() end
if not self:slashIsEffective(slash, target) then return slash:toString() end
end
end
end
return "."
end
sgs.ai_card_intention.TiaoxinCard = 80
sgs.ai_use_priority.TiaoxinCard = 4
sgs.ai_skill_invoke.shoucheng = function(self, data)
local move = data:toMoveOneTime()
if move and move.from then
local from = findPlayerByObjectName(move.from:objectName())
if from and self:isFriend(from) and not self:needKongcheng(move.from, true) then
return true
end
end
return false
end
local shangyi_skill = {}
shangyi_skill.name = "shangyi"
table.insert(sgs.ai_skills, shangyi_skill)
shangyi_skill.getTurnUseCard = function(self)
if self.player:hasUsed("ShangyiCard") then return end
if self.player:isKongcheng() then return end
if not self:willShowForAttack() then return end
local card_str = ("@ShangyiCard=.&shangyi")
local shangyi_card = sgs.Card_Parse(card_str)
assert(shangyi_card)
return shangyi_card
end
sgs.ai_skill_use_func.ShangyiCard = function(card, use, self)
self:sort(self.enemies, "handcard")
for index = #self.enemies, 1, -1 do
if not self.enemies[index]:isKongcheng() and self:objectiveLevel(self.enemies[index]) > 0 then
use.card = card
if use.to then
use.to:append(self.enemies[index])
end
return
end
end
end
sgs.ai_skill_choice.shangyi = function(self, choices)
return "handcards"
end
sgs.ai_use_value.ShangyiCard = 4
sgs.ai_use_priority.ShangyiCard = 9
sgs.ai_card_intention.ShangyiCard = 50
sgs.ai_skill_invoke.yicheng = function(self, data)
if not self:willShowForDefence() then
return false
end
return true
end
sgs.ai_skill_discard.yicheng = function(self, discard_num, min_num, optional, include_equip)
if self.player:hasSkill("hongyan") then
return self:askForDiscard("dummyreason", 1, 1, false, true)
end
local unpreferedCards = {}
local cards = sgs.QList2Table(self.player:getHandcards())
if self:getCardsNum("Slash") > 1 then
self:sortByKeepValue(cards)
for _, card in ipairs(cards) do
if card:isKindOf("Slash") then table.insert(unpreferedCards, card:getId()) end
end
table.remove(unpreferedCards, 1)
end
local num = self:getCardsNum("Jink") - 1
if self.player:getArmor() then num = num + 1 end
if num > 0 then
for _, card in ipairs(cards) do
if card:isKindOf("Jink") and num > 0 then
table.insert(unpreferedCards, card:getId())
num = num - 1
end
end
end
for _, card in ipairs(cards) do
if (card:isKindOf("Weapon") and self.player:getHandcardNum() < 3) or card:isKindOf("OffensiveHorse")
or self:getSameEquip(card, self.player) or card:isKindOf("AmazingGrace") or card:isKindOf("Lightning") then
table.insert(unpreferedCards, card:getId())
end
end
if self.player:getWeapon() and self.player:getHandcardNum() < 3 then
table.insert(unpreferedCards, self.player:getWeapon():getId())
end
if self:needToThrowArmor() then
table.insert(unpreferedCards, self.player:getArmor():getId())
end
if self.player:getOffensiveHorse() and self.player:getWeapon() then
table.insert(unpreferedCards, self.player:getOffensiveHorse():getId())
end
for index = #unpreferedCards, 1, -1 do
if not self.player:isJilei(sgs.Sanguosha:getCard(unpreferedCards[index])) then return { unpreferedCards[index] } end
end
return self:askForDiscard("dummyreason", 1, 1, false, true)
end
sgs.ai_skill_invoke.qianhuan = function(self, data)
if not (self:willShowForAttack() or self:willShowForDefence() or self:willShowForMasochism() ) then
return false
end
return true
end
local invoke_qianhuan = function(self, use)
if (use.from and self:isFriend(use.from)) then return false end
if use.to:isEmpty() then return false end
if use.card:isKindOf("Peach") then return false end
if use.card:isKindOf("Lightning") then return end
local to = use.to:first()
if use.card:isKindOf("Slash") and not self:slashIsEffective(use.card, to, use.from) then return end
if use.card:isKindOf("TrickCard") and not self:hasTrickEffective(use.card, to, use.from) then return end
if self.player:getPile("sorcery"):length() == 1 then
if use.card:isKindOf("Slash") or use.card:isKindOf("Duel") or use.card:isKindOf("FireAttack") or use.card:isKindOf("BurningCamps")
or use.card:isKindOf("ArcheryAttack") or use.card:isKindOf("Drowning") or use.card:isKindOf("SavageAssault") then
return true
end
if use.card:isKindOf("KnownBoth") or use.card:isKindOf("Dismantlement") or use.card:isKindOf("Indulgence") or use.card:isKindOf("SupplyShortage") then
--@todo
return false
end
self.room:writeToConsole("invoke_qianhuan ? " .. use.card:getClassName())
return false
end
if to and to:objectName() == self.player:objectName() then
return not (use.from and (use.from:objectName() == to:objectName()
or (use.card:isKindOf("Slash") and self:isPriorFriendOfSlash(self.player, use.card, use.from))))
else
return not (use.from and use.from:objectName() == to:objectName())
end
end
sgs.ai_skill_use["@@qianhuan"] = function(self)
local use = self.player:getTag("qianhuan_data"):toCardUse()
local invoke = invoke_qianhuan(self, use)
if invoke then
return "@QianhuanCard=" .. self.player:getPile("sorcery"):first()
end
return "."
end
local function will_discard_zhendu(self)
local current = self.room:getCurrent()
local need_damage = self:getDamagedEffects(current, self.player) or self:needToLoseHp(current, self.player)
if self:isFriend(current) then
if current:getMark("drank") > 0 and not need_damage then return -1 end
if (getKnownCard(current, self.player, "Slash") > 0 or (getCardsNum("Slash", current, self.player) >= 1 and current:getHandcardNum() >= 2))
and (not self:damageIsEffective(current, nil, self.player) or current:getHp() > 2 or (getCardsNum("Peach", current, self.player) > 1 and not self:isWeak(current))) then
local slash = sgs.cloneCard("slash")
local trend = 3
if current:hasWeapon("Axe") then trend = trend - 1
elseif current:hasShownSkills("liegong|tieqi|wushuang|niaoxiang") then trend = trend - 0.4 end
for _, enemy in ipairs(self.enemies) do
if ((enemy:getHp() < 3 and enemy:getHandcardNum() < 3) or (enemy:getHandcardNum() < 2)) and current:canSlash(enemy) and not self:slashProhibit(slash, enemy, current)
and self:slashIsEffective(slash, enemy, current) and sgs.isGoodTarget(enemy, self.enemies, self, true) then
return trend
end
end
end
if need_damage then return 3 end
elseif self:isEnemy(current) then
if current:getHp() == 1 then return 1 end
if need_damage or current:getHandcardNum() >= 2 then return -1 end
if getKnownCard(current, self.player, "Slash") == 0 and getCardsNum("Slash", current, self.player) < 0.5 then return 3.5 end
end
return -1
end
sgs.ai_skill_discard.zhendu = function(self)
local discard_trend = will_discard_zhendu(self)
if discard_trend <= 0 then return "." end
if self.player:getHandcardNum() + math.random(1, 100) / 100 >= discard_trend then
local cards = sgs.QList2Table(self.player:getHandcards())
self:sortByKeepValue(cards)
for _, card in ipairs(cards) do
if not self:isValuableCard(card, self.player) then return {card:getEffectiveId()} end
end
end
return {}
end
sgs.ai_skill_invoke.jizhao = sgs.ai_skill_invoke.niepan
sgs.ai_skill_invoke.zhangwu = true
sgs.weapon_range.DragonPhoenix = 2
sgs.ai_use_priority.DragonPhoenix = 2.400
function sgs.ai_weapon_value.DragonPhoenix(self, enemy, player)
local lordliubei = nil
for _, p in sgs.qlist(self.room:getAlivePlayers()) do
if p:hasShownSkill("zhangwu") then
lordliubei = p
break
end
end
if lordliubei and player:getWeapon() and not player:hasShownSkill("xiaoji") then
return -10
end
if enemy and enemy:getHp() <= 1 and (sgs.card_lack[enemy:objectName()]["Jink"] == 1 or getCardsNum("Jink", enemy, self.player) == 0) then
return 4.1
end
end
function sgs.ai_slash_weaponfilter.DragonPhoenix(self, to, player)
if player:distanceTo(to) > math.max(sgs.weapon_range.DragonPhoenix, player:getAttackRange()) then return end
return getCardsNum("Peach", to, self.player) + getCardsNum("Jink", to, self.player) < 1
and (sgs.card_lack[to:objectName()]["Jink"] == 1 or getCardsNum("Jink", to, self.player) == 0)
end
sgs.ai_skill_invoke.DragonPhoenix = function(self, data)
if data:toString() == "revive" then return true end
local death = data:toDeath()
if death.who then return true
else
local to = data:toPlayer()
return self:doNotDiscard(to) == self:isFriend(to)
end
end
sgs.ai_skill_choice.DragonPhoenix = function(self, choices, data)
local kingdom = data:toString()
local choices_pri = {}
choices_t = string.split(choices, "+")
if (kingdom == "wei") then
if (string.find(choices, "guojia")) then
table.insert(choices_pri,"guojia") end
if (string.find(choices, "xunyu")) then
table.insert(choices_pri,"xunyu") end
if (string.find(choices, "lidian")) then
table.insert(choices_pri,"lidian") end
if (string.find(choices, "zhanghe")) then
table.insert(choices_pri,"zhanghe") end
if (string.find(choices, "caopi")) then
table.insert(choices_pri,"caopi") end
if (string.find(choices, "zhangliao")) then
table.insert(choices_pri,"zhangliao") end
table.removeOne(choices_t, "caohong")
table.removeOne(choices_t, "zangba")
table.removeOne(choices_t, "xuchu")
table.removeOne(choices_t, "dianwei")
table.removeOne(choices_t, "caoren")
elseif (kingdom == "shu") then
if (string.find(choices, "mifuren")) then
table.insert(choices_pri,"mifuren") end
if (string.find(choices, "pangtong")) then
table.insert(choices_pri,"pangtong") end
if (string.find(choices, "lord_liubei")) then
table.insert(choices_pri,"lord_liubei") end
if (string.find(choices, "liushan")) then
table.insert(choices_pri, "liushan") end
if (string.find(choices, "jiangwanfeiyi")) then
table.insert(choices_pri, "jiangwanfeiyi") end
if (string.find(choices, "wolong")) then
table.insert(choices_pri, "wolong") end
table.removeOne(choices_t, "guanyu")
table.removeOne(choices_t, "zhangfei")
table.removeOne(choices_t, "weiyan")
table.removeOne(choices_t, "zhurong")
table.removeOne(choices_t, "madai")
elseif (kingdom == "wu") then
if (string.find(choices, "zhoutai")) then
table.insert(choices_pri, "zhoutai") end
if (string.find(choices, "lusu")) then
table.insert(choices_pri, "lusu") end
if (string.find(choices, "taishici")) then
table.insert(choices_pri, "taishici") end
if (string.find(choices, "sunjian")) then
table.insert(choices_pri, "sunjian") end
if (string.find(choices, "sunshangxiang")) then
table.insert(choices_pri, "sunshangxiang") end
table.removeOne(choices_t, "sunce")
table.removeOne(choices_t, "chenwudongxi")
table.removeOne(choices_t, "luxun")
table.removeOne(choices_t, "huanggai")
elseif (kingdom == "qun") then
if (string.find(choices, "yuji")) then
table.insert(choices_pri,"yuji") end
if (string.find(choices, "caiwenji")) then
table.insert(choices_pri,"caiwenji") end
if (string.find(choices, "mateng")) then
table.insert(choices_pri,"mateng") end
if (string.find(choices, "kongrong")) then
table.insert(choices_pri,"kongrong") end
if (string.find(choices, "lord_zhangjiao")) then
table.insert(choices_pri,"lord_zhangjiao") end
if (string.find(choices, "huatuo")) then
table.insert(choices_pri,"huatuo") end
table.removeOne(choices_t, "dongzhuo")
table.removeOne(choices_t, "tianfeng")
table.removeOne(choices_t, "zhangjiao")
end
if #choices_pri > 0 then
return choices_pri[math.random(1, #choices_pri)]
end
if #choices_t == 0 then choices_t = string.split(choices, "+") end
return choices_t[math.random(1, #choices_t)]
end
sgs.ai_skill_discard.DragonPhoenix = function(self, discard_num, min_num, optional, include_equip)
local to_discard = sgs.QList2Table(self.player:getCards("he"))
if #to_discard == 1 then
return {to_discard[1]:getEffectiveId()}
end
local aux_func = function(card)
local place = self.room:getCardPlace(card:getEffectiveId())
if place == sgs.Player_PlaceEquip then
if card:isKindOf("SilverLion") and self.player:isWounded() then return -2 end
if card:isKindOf("Weapon") then
if self.player:getHandcardNum() < discard_num + 2 and not self:needKongcheng() then return 0
else return 2 end
elseif card:isKindOf("OffensiveHorse") then
if self.player:getHandcardNum() < discard_num + 2 and not self:needKongcheng() then return 0
else return 1 end
elseif card:isKindOf("DefensiveHorse") then return 3
elseif card:isKindOf("Armor") then
if self.player:hasSkill("bazhen") then return 0
else return 4 end
else return 0 --@to-do: add the corrsponding value of Treasure
end
else
if self.player:getMark("@qianxi_red") > 0 and card:isRed() and not card:isKindOf("Peach") then return 0 end
if self.player:getMark("@qianxi_black") > 0 and card:isBlack() then return 0 end
if self:isWeak() then return 5 else return 0 end
end
end
local compare_func = function(card1, card2)
local card1_aux = aux_func(card1)
local card2_aux = aux_func(card2)
if card1_aux ~= card2_aux then return card1_aux < card2_aux end
return self:getKeepValue(card1) < self:getKeepValue(card2)
end
table.sort(to_discard, compare_func)
for _, card in ipairs(to_discard) do
if not self.player:isJilei(card) then return {card:getEffectiveId()} end
end
end
sgs.ai_skill_invoke.shengxi = function(self, data)
if not self:willShowForDefence() then
return false
end
if self:getOverflow() >= 0 then
local erzhang = sgs.findPlayerByShownSkillName("guzheng")
if erzhang and self:isEnemy(erzhang) then return false end
end
return true
end
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Bastok_Markets/npcs/Marin.lua | 38 | 1121 | -----------------------------------
-- Area: Bastok Markets
-- NPC: Marin
-- Type: Quest Giver
-- @zone: 235
-- @pos -340.060 -11.003 -148.181
--
-- Auto-Script: Requires Verification. Verified standard dialog is also "All By Myself" repeatable quest. - thrydwolf 12/18/2011
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets/TextIDs"] = nil;
require("scripts/zones/Bastok_Markets/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0169);
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 |
RhenaudTheLukark/CreateYourFrisk | Assets/Mods/Examples/Lua/Encounters/#10 - timeScale test.lua | 1 | 1506 | -- A basic encounter script skeleton you can copy and modify for your own creations.
-- music = "shine_on_you_crazy_diamond" --Either OGG or WAV. Extension is added automatically. Uncomment for custom music.
encountertext = "Poseur checks out the ACT menu!" --Modify as necessary. It will only be read out in the action select screen.
nextwaves = {"bullettest_chaserorb_time"}
wavetimer = 4.0
arenasize = {155, 130}
enemies = {
"timeScalePoseur"
}
enemypositions = {
{0, 0}
}
-- A custom list with attacks to choose from. Actual selection happens in EnemyDialogueEnding(). Put here in case you want to use it.
possible_attacks = {"bullettest_bouncy_time", "bullettest_chaserorb_time", "bullettest_touhou_time"}
function EncounterStarting()
-- If you want to change the game state immediately, this is the place.
end
function EnemyDialogueStarting()
-- Good location for setting monster dialogue depending on how the battle is going.
end
function EnemyDialogueEnding()
-- Good location to fill the 'nextwaves' table with the attacks you want to have simultaneously.
nextwaves = { possible_attacks[math.random(#possible_attacks)] }
end
function DefenseEnding() --This built-in function fires after the defense round ends.
encountertext = RandomEncounterText() --This built-in function gets a random encounter text from a random enemy.
end
function HandleSpare()
State("ENEMYDIALOGUE")
end
function HandleItem(ItemID)
BattleDialog({"Selected item " .. ItemID .. "."})
end | gpl-3.0 |
nasomi/darkstar | scripts/zones/Davoi/npcs/!.lua | 19 | 2445 | -----------------------------------
-- Area: Davoi
-- NPC: !
-- Involved in Mission: The Davoi Report
-- @pos 164 0.1 -21 149
-----------------------------------
package.loaded["scripts/zones/Davoi/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/globals/keyitems");
require("scripts/zones/Davoi/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local CurrentMission = player:getCurrentMission(SANDORIA)
if (CurrentMission == THE_DAVOI_REPORT and player:getVar("MissionStatus") == 1) then
player:setVar("MissionStatus",2);
player:addKeyItem(LOST_DOCUMENT);
player:messageSpecial(KEYITEM_OBTAINED,LOST_DOCUMENT);
elseif (CurrentMission == INFILTRATE_DAVOI and player:getVar("MissionStatus") >= 6 and player:getVar("MissionStatus") <= 9) then
local X = npc:getXPos();
local Z = npc:getZPos();
if (X >= 292 and X <= 296 and Z >= -30 and Z <= -26 and player:hasKeyItem(EAST_BLOCK_CODE) == false) then
player:setVar("MissionStatus",player:getVar("MissionStatus") + 1);
player:addKeyItem(EAST_BLOCK_CODE);
player:messageSpecial(KEYITEM_OBTAINED,EAST_BLOCK_CODE);
elseif (X >= 333 and X <= 337 and Z >= -138 and Z <= -134 and player:hasKeyItem(SOUTH_BLOCK_CODE) == false) then
player:setVar("MissionStatus",player:getVar("MissionStatus") + 1);
player:addKeyItem(SOUTH_BLOCK_CODE);
player:messageSpecial(KEYITEM_OBTAINED,SOUTH_BLOCK_CODE);
elseif (X >= 161 and X <= 165 and Z >= -20 and Z <= -16 and player:hasKeyItem(NORTH_BLOCK_CODE) == false) then
player:setVar("MissionStatus",player:getVar("MissionStatus") + 1);
player:addKeyItem(NORTH_BLOCK_CODE);
player:messageSpecial(KEYITEM_OBTAINED,NORTH_BLOCK_CODE);
else
player:messageSpecial(YOU_SEE_NOTHING);
end
else
player:messageSpecial(YOU_SEE_NOTHING);
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 |
nasomi/darkstar | scripts/zones/Nashmau/npcs/Kyokyoroon.lua | 17 | 1764 | -----------------------------------
-- Area: Nashmau
-- NPC: Kyokyoroon
-- Standard Info NPC
-- @pos 18.020 -6.000 10.467 53
-----------------------------------
package.loaded["scripts/zones/Nashmau/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Nashmau/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(AHT_URHGAN,RAT_RACE) == QUEST_ACCEPTED and player:getVar("ratraceCS") == 5) then
if (trade:hasItemQty(5595,1) and trade:getItemCount() == 1) then
player:startEvent(0x0137);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local ratRaceProg = player:getVar("ratraceCS");
if (ratRaceProg == 5) then
player:startEvent(0x0107);
elseif (ratRaceProg == 6) then
player:startEvent(0x0013c);
elseif (player:getQuestStatus(AHT_URHGAN,RAT_RACE) == QUEST_COMPLETED) then
player:startEvent(0x013d);
else
player:startEvent(0x0107);
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 == 0x0137) then
player:tradeComplete();
player:setVar("ratraceCS",6);
end
end;
| gpl-3.0 |
mlem/wesnoth | data/lua/ilua.lua | 30 | 3556 | -- ilua.lua
-- A more friendly Lua interactive prompt
-- doesn't need '='
-- will try to print out tables recursively, subject to the pretty_print_limit value.
-- Steve Donovan, 2007
-- Adapted by iceiceice for wesnoth, 2014
-- Retrived from: http://lua-users.org/files/wiki_insecure/users/steved/ilua.lua
local pretty_print_limit = 20
local max_depth = 7
local table_clever = true
-- imported global functions
local sub = string.sub
local push = table.insert
local pop = table.remove
local pack = table.pack
local floor = math.floor
local declared = {}
local jstack = {}
local ilua = { strict = true }
function ilua.join(tbl,delim,limit,depth)
if not limit then limit = pretty_print_limit end
if not depth then depth = max_depth end
local n = #tbl
local res = ''
local k = 0
-- very important to avoid disgracing ourselves with circular referencs...
if #jstack > depth then
return "..."
end
for i,t in ipairs(jstack) do
if tbl == t then
return "<self>"
end
end
push(jstack,tbl)
-- this is a hack to work out if a table is 'list-like' or 'map-like'
-- you can switch it off with ilua.table_options {clever = false}
local is_list
if table_clever then
local index1 = n > 0 and tbl[1]
local index2 = n > 1 and tbl[2]
is_list = index1 and index2
end
if is_list then
for i,v in ipairs(tbl) do
res = res..delim..ilua.val2str(v)
k = k + 1
if k > limit then
res = res.." ... "
break
end
end
else
for key,v in pairs(tbl) do
if type(key) == 'number' then
key = '['..tostring(key)..']'
else
key = tostring(key)
end
res = res..delim..key..'='..ilua.val2str(v)
k = k + 1
if k > limit then
res = res.." ... "
break
end
end
end
pop(jstack)
return sub(res,2)
end
function ilua.val2str(val)
local tp = type(val)
if tp == 'function' then
return tostring(val)
elseif tp == 'table' then
if val.__tostring then
return tostring(val)
else
return '{'..ilua.join(val,',')..'}'
end
elseif tp == 'string' then
return "'"..val.."'"
elseif tp == 'number' then
-- removed numeric precision features, but we might actually want these... might put them back
return tostring(val)
else
return tostring(val)
end
end
function ilua._pretty_print(...)
local arg = pack(...)
for i,val in ipairs(arg) do
print(ilua.val2str(val))
end
end
--
-- strict.lua
-- checks uses of undeclared global variables
-- All global variables must be 'declared' through a regular assignment
-- (even assigning nil will do) in a main chunk before being used
-- anywhere.
--
function ilua.set_strict()
local mt = getmetatable(_G)
if mt == nil then
mt = {}
setmetatable(_G, mt)
end
local function what ()
local d = debug.getinfo(3, "S")
return d and d.what or "C"
end
mt.__newindex = function (t, n, v)
declared[n] = true
rawset(t, n, v)
end
mt.__index = function (t, n)
if not declared[n] and ilua.strict and what() ~= "C" then
error("variable '"..n.."' must be assigned before being used", 2)
end
return rawget(t, n)
end
end
return ilua
| gpl-2.0 |
nasomi/darkstar | scripts/globals/items/strip_of_smoked_mackerel.lua | 36 | 1154 | -----------------------------------------
-- ID: 5943
-- Item: Strip of Smoked Mackerel
-- Food Effect: 30Min, All Races
-----------------------------------------
-- Agility 4
-- Vitality -3
-----------------------------------------
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,5943);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_AGI, 4);
target:addMod(MOD_VIT, -3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_AGI, 4);
target:delMod(MOD_VIT, -3);
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Aht_Urhgan_Whitegate/npcs/Mushayra.lua | 38 | 1034 | -----------------------------------
-- Area: Aht Urhgan Whitegate
-- NPC: Mushayra
-- Type: Standard NPC
-- @pos -111.551 -6.999 -61.720 50
-----------------------------------
package.loaded["scripts/zones/Aht_Urhgan_Whitegate/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Aht_Urhgan_Whitegate/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0207);
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 |
ngeiswei/ardour | share/scripts/__plugin_modulation.lua | 4 | 1701 | --- session-script example to modulate plugin parameter(s) globally
--
-- Ardour > Menu > Session > Scripting > Add Lua Script
-- "Add" , select "Modulate Plugin Parameter", click "Add" + OK.
--
-----------------------------------------------------------------------------
-- This script currently assumes you have a track named "Audio"
-- which as a plugin at the top, where the first parameter has a range > 200
-- e.g. "No Delay Line"
--
-- edit below..
-- plugin descriptor
ardour {
["type"] = "session",
name = "Modulate Plugin Parameter",
license = "MIT",
author = "Ardour Team",
description = [[An example session to modulate a plugin parameter.]]
}
function factory () -- generate a new script instance
local count = 0 -- script-instance "global" variable
-- the "run" function called at the beginning of every process cycle
return function (n_samples)
count = (count + 1) % 200; -- count process cycles
local tri = math.abs (100 - count) -- triangle wave 0..100
-- get the track named "Audio"
-- see also http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:Session
-- and http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:Route
local route = Session:route_by_name ("Audio")
assert (not route:isnil ()) -- make sure it exists
-- the 1st plugin (from top) on that track, ardour starts counting at zero
-- see also http://manual.ardour.org/lua-scripting/class_reference/#ARDOUR:Processor
local plugin = route:nth_plugin (0)
assert (not plugin:isnil ()) -- make sure it exists
-- modulate the plugin's first parameter (0) from 200 .. 300
ARDOUR.LuaAPI.set_processor_param (plugin, 0, 200.0 + tri)
end
end
| gpl-2.0 |
nasomi/darkstar | scripts/globals/titles.lua | 31 | 46695 | -----------------------------------
--
-- TITLES IDs
--
-----------------------------------
FODDERCHIEF_FLAYER = 1;
WARCHIEF_WRECKER = 2;
DREAD_DRAGON_SLAYER = 3;
OVERLORD_EXECUTIONER = 4;
DARK_DRAGON_SLAYER = 5;
ADAMANTKING_KILLER = 6;
BLACK_DRAGON_SLAYER = 7;
MANIFEST_MAULER = 8;
BEHEMOTHS_BANE = 9;
ARCHMAGE_ASSASSIN = 10;
HELLSBANE = 11;
GIANT_KILLER = 12;
LICH_BANISHER = 13;
JELLYBANE = 14;
BOGEYDOWNER = 15;
BEAKBENDER = 16;
SKULLCRUSHER = 17;
MORBOLBANE = 18;
GOLIATH_KILLER = 19;
MARYS_GUIDE = 20;
SIMURGH_POACHER = 21;
ROC_STAR = 22;
SERKET_BREAKER = 23;
CASSIENOVA = 24;
THE_HORNSPLITTER = 25;
TORTOISE_TORTURER = 26;
MON_CHERRY = 27;
BEHEMOTH_DETHRONER = 28;
THE_VIVISECTOR = 29;
DRAGON_ASHER = 30;
EXPEDITIONARY_TROOPER = 31;
BEARER_OF_THE_WISEWOMANS_HOPE = 32;
BEARER_OF_THE_EIGHT_PRAYERS = 33;
LIGHTWEAVER = 34;
DESTROYER_OF_ANTIQUITY = 35;
SEALER_OF_THE_PORTAL_OF_THE_GODS = 36;
BURIER_OF_THE_ILLUSION = 37;
-- Unused = 38;
FAMILY_COUNSELOR = 39;
-- Unused = 40;
GREAT_GRAPPLER_SCORPIO = 41;
BOND_FIXER = 42;
VAMPIRE_HUNTER_DMINUS = 43;
SHEEPS_MILK_DELIVERER = 44;
BEAN_CUISINE_SALTER = 45;
TOTAL_LOSER = 46;
DOCTOR_SHANTOTTOS_FLAVOR_OF_THE_MONTH = 47;
PILGRIM_TO_HOLLA = 48;
PILGRIM_TO_DEM = 49;
PILGRIM_TO_MEA = 50;
DAYBREAK_GAMBLER = 51;
THE_PIOUS_ONE = 52;
A_MOSS_KIND_PERSON = 53;
ENTRANCE_DENIED = 54;
APIARIST = 55;
RABBITER = 56;
ROYAL_GRAVE_KEEPER = 57;
COURIER_EXTRAORDINAIRE = 58;
RONFAURIAN_RESCUER = 59;
PICKPOCKET_PINCHER = 60;
FANG_FINDER = 61;
FAITH_LIKE_A_CANDLE = 62;
THE_PURE_ONE = 63;
LOST_CHILD_OFFICER = 64;
SILENCER_OF_THE_LAMBS = 65;
LOST_AMP_FOUND_OFFICER = 66;
GREEN_GROCER = 67;
THE_BENEVOLENT_ONE = 68;
KNIGHT_IN_TRAINING = 69;
LIZARD_SKINNER = 70;
BUG_CATCHER = 71;
SPELUNKER = 72;
ARMS_TRADER = 73;
TRAVELING_MEDICINE_MAN = 74;
CAT_SKINNER = 75;
CARP_DIEM = 76;
ADVERTISING_EXECUTIVE = 77;
THIRDRATE_ORGANIZER = 78;
SECONDRATE_ORGANIZER = 79;
FIRSTRATE_ORGANIZER = 80;
BASTOK_WELCOMING_COMMITTEE = 81;
SHELL_OUTER = 82;
BUCKET_FISHER = 83;
PURSUER_OF_THE_PAST = 84;
PURSUER_OF_THE_TRUTH = 85;
MOMMYS_HELPER = 86;
HOT_DOG = 87;
STAMPEDER = 88;
QIJIS_FRIEND = 89;
QIJIS_RIVAL = 90;
CONTEST_RIGGER = 91;
RINGBEARER = 92;
KULATZ_BRIDGE_COMPANION = 93;
BEADEAUX_SURVEYOR = 94;
AVENGER = 95;
TREASURE_SCAVENGER = 96;
AIRSHIP_DENOUNCER = 97;
ZERUHN_SWEEPER = 98;
TEARJERKER = 99;
CRAB_CRUSHER = 100;
STAR_OF_IFRIT = 101;
SORROW_DROWNER = 102;
BRYGIDAPPROVED = 103;
DRACHENFALL_ASCETIC = 104;
STEAMING_SHEEP_REGULAR = 105;
PURPLE_BELT = 106;
GUSTABERG_TOURIST = 107;
SAND_BLASTER = 108;
BLACK_DEATH = 109;
-- Unused = 110;
FRESH_NORTH_WINDS_RECRUIT = 111;
NEW_BEST_OF_THE_WEST_RECRUIT = 112;
NEW_BUUMAS_BOOMERS_RECRUIT = 113;
HEAVENS_TOWER_GATEHOUSE_RECRUIT = 114;
CAT_BURGLAR_GROUPIE = 115;
CRAWLER_CULLER = 116;
SAVIOR_OF_KNOWLEDGE = 117;
STARORDAINED_WARRIOR = 118;
LOWER_THAN_THE_LOWEST_TUNNEL_WORM = 119;
STAR_ONION_BRIGADE_MEMBER = 120;
STAR_ONION_BRIGADIER = 121;
QUICK_FIXER = 122;
FAKEMOUSTACHED_INVESTIGATOR = 123;
HAKKURURINKURUS_BENEFACTOR = 124;
SOB_SUPER_HERO = 125;
EDITORS_HATCHET_MAN = 126;
DOCTOR_SHANTOTTOS_GUINEA_PIG = 127;
SPOILSPORT = 128;
SUPER_MODEL = 129;
GHOSTIE_BUSTER = 130;
NIGHT_SKY_NAVIGATOR = 131;
FAST_FOOD_DELIVERER = 132;
CUPIDS_FLORIST = 133;
TARUTARU_MURDER_SUSPECT = 134;
HEXER_VEXER = 135;
CARDIAN_TUTOR = 136;
DELIVERER_OF_TEARFUL_NEWS = 137;
FOSSILIZED_SEA_FARER = 138;
DOWN_PIPER_PIPEUPPERER = 139;
KISSER_MAKEUPPER = 140;
TIMEKEEPER = 141;
FORTUNETELLER_IN_TRAINING = 142;
TORCHBEARER = 143;
TENSHODO_MEMBER = 144;
CHOCOBO_TRAINER = 145;
BRINGER_OF_BLISS = 146;
ACTIVIST_FOR_KINDNESS = 147;
ENVOY_TO_THE_NORTH = 148;
EXORCIST_IN_TRAINING = 149;
PROFESSIONAL_LOAFER = 150;
CLOCK_TOWER_PRESERVATIONIST = 151;
LIFE_SAVER = 152;
FOOLS_ERRAND_RUNNER = 153;
CARD_COLLECTOR = 154;
RESEARCHER_OF_CLASSICS = 155;
STREET_SWEEPER = 156;
MERCY_ERRAND_RUNNER = 157;
TWOS_COMPANY = 158;
BELIEVER_OF_ALTANA = 159;
TRADER_OF_MYSTERIES = 160;
TRADER_OF_ANTIQUITIES = 161;
TRADER_OF_RENOWN = 162;
BROWN_BELT = 163;
HORIZON_BREAKER = 164;
GOBLINS_EXCLUSIVE_FASHION_MANNEQUIN = 165;
SUMMIT_BREAKER = 166;
SKY_BREAKER = 167;
CLOUD_BREAKER = 168;
STAR_BREAKER = 169;
GREEDALOX = 170;
CERTIFIED_RHINOSTERY_VENTURER = 171;
CORDON_BLEU_FISHER = 172;
ACE_ANGLER = 173;
LU_SHANGLIKE_FISHER_KING = 174;
MATCHMAKER = 175;
ECOLOGIST = 176;
LIL_CUPID = 177;
THE_LOVE_DOCTOR = 178;
SAVIOR_OF_LOVE = 179;
HONORARY_CITIZEN_OF_SELBINA = 180;
PURVEYOR_IN_TRAINING = 181;
ONESTAR_PURVEYOR = 182;
TWOSTAR_PURVEYOR = 183;
THREESTAR_PURVEYOR = 184;
FOURSTAR_PURVEYOR = 185;
FIVESTAR_PURVEYOR = 186;
DOCTOR_YORANORAN_SUPPORTER = 187;
DOCTOR_SHANTOTTO_SUPPORTER = 188;
PROFESSOR_KORUMORU_SUPPORTER = 189;
RAINBOW_WEAVER = 190;
SHADOW_WALKER = 191;
HEIR_TO_THE_HOLY_CREST = 192;
BUSHIDO_BLADE = 193;
-- Unused = 194;
PARAGON_OF_PALADIN_EXCELLENCE = 195;
PARAGON_OF_BEASTMASTER_EXCELLENCE = 196;
PARAGON_OF_RANGER_EXCELLENCE = 197;
PARAGON_OF_DARK_KNIGHT_EXCELLENCE = 198;
PARAGON_OF_BARD_EXCELLENCE = 199;
PARAGON_OF_SAMURAI_EXCELLENCE = 200;
PARAGON_OF_DRAGOON_EXCELLENCE = 201;
PARAGON_OF_NINJA_EXCELLENCE = 202;
PARAGON_OF_SUMMONER_EXCELLENCE = 203;
-- Unused = 204;
-- Unused = 205;
NEW_ADVENTURER = 206;
CERTIFIED_ADVENTURER = 207;
SHADOW_BANISHER = 208;
TRIED_AND_TESTED_KNIGHT = 209;
DARK_SIDER = 210;
THE_FANGED_ONE = 211;
HAVE_WINGS_WILL_FLY = 212;
ANIMAL_TRAINER = 213;
WANDERING_MINSTREL = 214;
MOGS_MASTER = 215;
MOGS_KIND_MASTER = 216;
MOGS_EXCEPTIONALLY_KIND_MASTER = 217;
PARAGON_OF_WARRIOR_EXCELLENCE = 218;
PARAGON_OF_MONK_EXCELLENCE = 219;
PARAGON_OF_RED_MAGE_EXCELLENCE = 220;
PARAGON_OF_THIEF_EXCELLENCE = 221;
PARAGON_OF_BLACK_MAGE_EXCELLENCE = 222;
PARAGON_OF_WHITE_MAGE_EXCELLENCE = 223;
MOGS_LOVING_MASTER = 224;
-- Unused = 225;
ROYAL_ARCHER = 226;
ROYAL_SPEARMAN = 227;
ROYAL_SQUIRE = 228;
ROYAL_SWORDSMAN = 229;
ROYAL_CAVALIER = 230;
ROYAL_GUARD = 231;
GRAND_KNIGHT_OF_THE_REALM = 232;
GRAND_TEMPLE_KNIGHT = 233;
RESERVE_KNIGHT_CAPTAIN = 234;
ELITE_ROYAL_GUARD = 235;
LEGIONNAIRE = 236;
DECURION = 237;
CENTURION = 238;
JUNIOR_MUSKETEER = 239;
SENIOR_MUSKETEER = 240;
MUSKETEER_COMMANDER = 241;
GOLD_MUSKETEER = 242;
PRAEFECTUS = 243;
SENIOR_GOLD_MUSKETEER = 244;
PRAEFECTUS_CASTRORUM = 245;
FREESWORD = 246;
MERCENARY = 247;
MERCENARY_CAPTAIN = 248;
COMBAT_CASTER = 249;
TACTICIAN_MAGICIAN = 250;
WISE_WIZARD = 251;
PATRIARCH_PROTECTOR = 252;
CASTER_CAPTAIN = 253;
MASTER_CASTER = 254;
MERCENARY_MAJOR = 255;
FUGITIVE_MINISTER_BOUNTY_HUNTER = 256;
KING_OF_THE_OPOOPOS = 257;
EXCOMMUNICATE_OF_KAZHAM = 258;
KAZHAM_CALLER = 259;
DREAM_DWELLER = 260;
APPRENTICE_SOMMELIER = 261;
DESERT_HUNTER = 262;
SEEKER_OF_TRUTH = 263;
KUFTAL_TOURIST = 264;
THE_IMMORTAL_FISHER_LU_SHANG = 265;
LOOKS_SUBLIME_IN_A_SUBLIGAR = 266;
LOOKS_GOOD_IN_LEGGINGS = 267;
HONORARY_DOCTORATE_MAJORING_IN_TONBERRIES = 268;
TREASUREHOUSE_RANSACKER = 269;
CRACKER_OF_THE_SECRET_CODE = 270;
BLACK_MARKETEER = 271;
ACQUIRER_OF_ANCIENT_ARCANUM = 272;
YA_DONE_GOOD = 273;
HEIR_OF_THE_GREAT_FIRE = 274;
HEIR_OF_THE_GREAT_EARTH = 275;
HEIR_OF_THE_GREAT_WATER = 276;
HEIR_OF_THE_GREAT_WIND = 277;
HEIR_OF_THE_GREAT_ICE = 278;
HEIR_OF_THE_GREAT_LIGHTNING = 279;
GUIDER_OF_SOULS_TO_THE_SANCTUARY = 280;
BEARER_OF_BONDS_BEYOND_TIME = 281;
FRIEND_OF_THE_OPOOPOS = 282;
HERO_ON_BEHALF_OF_WINDURST = 283;
VICTOR_OF_THE_BALGA_CONTEST = 284;
GULLIBLES_TRAVELS = 285;
EVEN_MORE_GULLIBLES_TRAVELS = 286;
HEIR_OF_THE_NEW_MOON = 287;
ASSASSIN_REJECT = 288;
BLACK_BELT = 289;
VERMILLION_VENTURER = 290;
CERULEAN_SOLDIER = 291;
EMERALD_EXTERMINATOR = 292;
GUIDING_STAR = 293;
VESTAL_CHAMBERLAIN = 294;
SAN_DORIAN_ROYAL_HEIR = 295;
HERO_AMONG_HEROES = 296;
DYNAMISSAN_DORIA_INTERLOPER = 297;
DYNAMISBASTOK_INTERLOPER = 298;
DYNAMISWINDURST_INTERLOPER = 299;
DYNAMISJEUNO_INTERLOPER = 300;
DYNAMISBEAUCEDINE_INTERLOPER = 301;
DYNAMISXARCABARD_INTERLOPER = 302;
DISCERNING_INDIVIDUAL = 303;
VERY_DISCERNING_INDIVIDUAL = 304;
EXTREMELY_DISCERNING_INDIVIDUAL = 305;
ROYAL_WEDDING_PLANNER = 306;
CONSORT_CANDIDATE = 307;
OBSIDIAN_STORM = 308;
PENTACIDE_PERPETRATOR = 309;
WOOD_WORSHIPER = 310;
LUMBER_LATHER = 311;
ACCOMPLISHED_CARPENTER = 312;
ANVIL_ADVOCATE = 313;
FORGE_FANATIC = 314;
ACCOMPLISHED_BLACKSMITH = 315;
TRINKET_TURNER = 316;
SILVER_SMELTER = 317;
ACCOMPLISHED_GOLDSMITH = 318;
KNITTING_KNOWITALL = 319;
LOOM_LUNATIC = 320;
ACCOMPLISHED_WEAVER = 321;
FORMULA_FIDDLER = 322;
POTION_POTENTATE = 323;
ACCOMPLISHED_ALCHEMIST = 324;
BONE_BEAUTIFIER = 325;
SHELL_SCRIMSHANDER = 326;
ACCOMPLISHED_BONEWORKER = 327;
HIDE_HANDLER = 328;
LEATHER_LAUDER = 329;
ACCOMPLISHED_TANNER = 330;
FASTRIVER_FISHER = 331;
COASTLINE_CASTER = 332;
ACCOMPLISHED_ANGLER = 333;
GOURMAND_GRATIFIER = 334;
BANQUET_BESTOWER = 335;
ACCOMPLISHED_CHEF = 336;
FINE_TUNER = 337;
FRIEND_OF_THE_HELMED = 338;
TAVNAZIAN_SQUIRE = 339;
DUCAL_DUPE = 340;
HYPER_ULTRA_SONIC_ADVENTURER = 341;
ROD_RETRIEVER = 342;
DEED_VERIFIER = 343;
CHOCOBO_LOVE_GURU = 344;
PICKUP_ARTIST = 345;
TRASH_COLLECTOR = 346;
ANCIENT_FLAME_FOLLOWER = 347;
TAVNAZIAN_TRAVELER = 348;
TRANSIENT_DREAMER = 349;
THE_LOST_ONE = 350;
TREADER_OF_AN_ICY_PAST = 351;
BRANDED_BY_LIGHTNING = 352;
SEEKER_OF_THE_LIGHT = 353;
DEAD_BODY = 354;
FROZEN_DEAD_BODY = 355;
DREAMBREAKER = 356;
MIST_MELTER = 357;
DELTA_ENFORCER = 358;
OMEGA_OSTRACIZER = 359;
ULTIMA_UNDERTAKER = 360;
ULMIAS_SOULMATE = 361;
TENZENS_ALLY = 362;
COMPANION_OF_LOUVERANCE = 363;
TRUE_COMPANION_OF_LOUVERANCE = 364;
PRISHES_BUDDY = 365;
NAGMOLADAS_UNDERLING = 366;
ESHANTARLS_COMRADE_IN_ARMS = 367;
THE_CHEBUKKIS_WORST_NIGHTMARE = 368;
BROWN_MAGE_GUINEA_PIG = 369;
BROWN_MAGIC_BYPRODUCT = 370;
BASTOKS_SECOND_BEST_DRESSED = 371;
ROOKIE_HERO_INSTRUCTOR = 372;
GOBLIN_IN_DISGUISE = 373;
APOSTATE_FOR_HIRE = 374;
TALKS_WITH_TONBERRIES = 375;
ROOK_BUSTER = 376;
BANNERET = 377;
GOLD_BALLI_STAR = 378;
MYTHRIL_BALLI_STAR = 379;
SILVER_BALLI_STAR = 380;
BRONZE_BALLI_STAR = 381;
SEARING_STAR = 382;
STRIKING_STAR = 383;
SOOTHING_STAR = 384;
SABLE_STAR = 385;
SCARLET_STAR = 386;
SONIC_STAR = 387;
SAINTLY_STAR = 388;
SHADOWY_STAR = 389;
SAVAGE_STAR = 390;
SINGING_STAR = 391;
SNIPING_STAR = 392;
SLICING_STAR = 393;
SNEAKING_STAR = 394;
SPEARING_STAR = 395;
SUMMONING_STAR = 396;
PUTRID_PURVEYOR_OF_PUNGENT_PETALS = 397;
UNQUENCHABLE_LIGHT = 398;
BALLISTAGER = 399;
ULTIMATE_CHAMPION_OF_THE_WORLD = 400;
WARRIOR_OF_THE_CRYSTAL = 401;
INDOMITABLE_FISHER = 402;
AVERTER_OF_THE_APOCALYPSE = 403;
BANISHER_OF_EMPTINESS = 404;
RANDOM_ADVENTURER = 405;
IRRESPONSIBLE_ADVENTURER = 406;
ODOROUS_ADVENTURER = 407;
INSIGNIFICANT_ADVENTURER = 408;
FINAL_BALLI_STAR = 409;
BALLI_STAR_ROYALE = 410;
DESTINED_FELLOW = 411;
ORCISH_SERJEANT = 412;
BRONZE_QUADAV = 413;
YAGUDO_INITIATE = 414;
MOBLIN_KINSMAN = 415;
SIN_HUNTER_HUNTER = 416;
DISCIPLE_OF_JUSTICE = 417;
MONARCH_LINN_PATROL_GUARD = 418;
TEAM_PLAYER = 419;
WORTHY_OF_TRUST = 420;
CONQUEROR_OF_FATE = 421;
BREAKER_OF_THE_CHAINS = 422;
A_FRIEND_INDEED = 423;
HEIR_TO_THE_REALM_OF_DREAMS = 424;
GOLD_HOOK = 425;
MYTHRIL_HOOK = 426;
SILVER_HOOK = 427;
COPPER_HOOK = 428;
-- Unused = 429;
DYNAMISVALKURM_INTERLOPER = 430;
DYNAMISBUBURIMU_INTERLOPER = 431;
DYNAMISQUFIM_INTERLOPER = 432;
DYNAMISTAVNAZIA_INTERLOPER = 433;
CONFRONTER_OF_NIGHTMARES = 434;
DISTURBER_OF_SLUMBER = 435;
INTERRUPTER_OF_DREAMS = 436;
SAPPHIRE_STAR = 437;
SURGING_STAR = 438;
SWAYING_STAR = 439;
DARK_RESISTANT = 440;
BEARER_OF_THE_MARK_OF_ZAHAK = 441;
SEAGULL_PHRATRIE_CREW_MEMBER = 442;
PROUD_AUTOMATON_OWNER = 443;
PRIVATE_SECOND_CLASS = 444;
PRIVATE_FIRST_CLASS = 445;
SUPERIOR_PRIVATE = 446;
WILDCAT_PUBLICIST = 447;
ADAMANTKING_USURPER = 448;
OVERLORD_OVERTHROWER = 449;
DEITY_DEBUNKER = 450;
FAFNIR_SLAYER = 451;
ASPIDOCHELONE_SINKER = 452;
NIDHOGG_SLAYER = 453;
MAAT_MASHER = 454;
KIRIN_CAPTIVATOR = 455;
CACTROT_DESACELERADOR = 456;
LIFTER_OF_SHADOWS = 457;
TIAMAT_TROUNCER = 458;
VRTRA_VANQUISHER = 459;
WORLD_SERPENT_SLAYER = 460;
XOLOTL_XTRAPOLATOR = 461;
BOROKA_BELEAGUERER = 462;
OURYU_OVERWHELMER = 463;
VINEGAR_EVAPORATOR = 464;
VIRTUOUS_SAINT = 465;
BYEBYE_TAISAI = 466;
TEMENOS_LIBERATOR = 467;
APOLLYON_RAVAGER = 468;
WYRM_ASTONISHER = 469;
NIGHTMARE_AWAKENER = 470;
CERBERUS_MUZZLER = 471;
HYDRA_HEADHUNTER = 472;
SHINING_SCALE_RIFLER = 473;
TROLL_SUBJUGATOR = 474;
GORGONSTONE_SUNDERER = 475;
KHIMAIRA_CARVER = 476;
ELITE_EINHERJAR = 477;
STAR_CHARIOTEER = 478;
SUN_CHARIOTEER = 479;
SUBDUER_OF_THE_MAMOOL_JA = 480;
SUBDUER_OF_THE_TROLLS = 481;
SUBDUER_OF_THE_UNDEAD_SWARM = 482;
AGENT_OF_THE_ALLIED_FORCES = 483;
SCENIC_SNAPSHOTTER = 484;
BRANDED_BY_THE_FIVE_SERPENTS = 485;
IMMORTAL_LION = 486;
PARAGON_OF_BLUE_MAGE_EXCELLENCE = 487;
PARAGON_OF_CORSAIR_EXCELLENCE = 488;
PARAGON_OF_PUPPETMASTER_EXCELLENCE = 489;
LANCE_CORPORAL = 490;
CORPORAL = 491;
MASTER_OF_AMBITION = 492;
MASTER_OF_CHANCE = 493;
MASTER_OF_MANIPULATION = 494;
OVJANGS_ERRAND_RUNNER = 495;
SERGEANT = 496;
SERGEANT_MAJOR = 497;
KARABABAS_TOUR_GUIDE = 498;
KARABABAS_BODYGUARD = 499;
KARABABAS_SECRET_AGENT = 500;
SKYSERPENT_AGGRANDIZER = 501;
CHIEF_SERGEANT = 502;
APHMAUS_MERCENARY = 503;
NASHMEIRAS_MERCENARY = 504;
CHOCOROOKIE = 505;
SECOND_LIEUTENANT = 506;
GALESERPENT_GUARDIAN = 507;
STONESERPENT_SHOCKTROOPER = 508;
PHOTOPTICATOR_OPERATOR = 509;
SALAHEEMS_RISK_ASSESSOR = 510;
TREASURE_TROVE_TENDER = 511;
GESSHOS_MERCY = 512;
EMISSARY_OF_THE_EMPRESS = 513;
ENDYMION_PARATROOPER = 514;
NAJAS_COMRADEINARMS = 515;
NASHMEIRAS_LOYALIST = 516;
PREVENTER_OF_RAGNAROK = 517;
CHAMPION_OF_AHT_URHGAN = 518;
FIRST_LIEUTENANT = 519;
CAPTAIN = 520;
CRYSTAL_STAKES_CUPHOLDER = 521;
WINNING_OWNER = 522;
VICTORIOUS_OWNER = 523;
TRIUMPHANT_OWNER = 524;
HIGH_ROLLER = 525;
FORTUNES_FAVORITE = 526;
SUPERHERO = 527;
SUPERHEROINE = 528;
BLOODY_BERSERKER = 529;
THE_SIXTH_SERPENT = 530;
ETERNAL_MERCENARY = 531;
SPRINGSERPENT_SENTRY = 532;
SPRIGHTLY_STAR = 533;
SAGACIOUS_STAR = 534;
SCHULTZ_SCHOLAR = 535;
KNIGHT_OF_THE_IRON_RAM = 536;
FOURTH_DIVISION_SOLDIER = 537;
COBRA_UNIT_MERCENARY = 538;
WINDTALKER = 539;
LADY_KILLER = 540;
TROUPE_BRILIOTH_DANCER = 541;
CAIT_SITHS_ASSISTANT = 542;
AJIDOMARUJIDOS_MINDER = 543;
COMET_CHARIOTEER = 544;
MOON_CHARIOTEER = 545;
SANDWORM_WRANGLER = 546;
IXION_HORNBREAKER = 547;
LAMBTON_WORM_DESEGMENTER = 548;
PANDEMONIUM_QUELLER = 549;
DEBASER_OF_DYNASTIES = 550;
DISPERSER_OF_DARKNESS = 551;
ENDER_OF_IDOLATRY = 552;
LUGH_EXORCIST = 553;
ELATHA_EXORCIST = 554;
ETHNIU_EXORCIST = 555;
TETHRA_EXORCIST = 556;
BUARAINECH_EXORCIST = 557;
OUPIRE_IMPALER = 558;
SCYLLA_SKINNER = 559;
ZIRNITRA_WINGCLIPPER = 560;
DAWON_TRAPPER = 561;
KRABKATOA_STEAMER = 562;
ORCUS_TROPHY_HUNTER = 563;
BLOBDINGNAG_BURSTER = 564;
VERTHANDI_ENSNARER = 565;
RUTHVEN_ENTOMBER = 566;
YILBEGAN_HIDEFLAYER = 567;
TORCHBEARER_OF_THE_1ST_WALK = 568;
TORCHBEARER_OF_THE_2ND_WALK = 569;
TORCHBEARER_OF_THE_3RD_WALK = 570;
TORCHBEARER_OF_THE_4TH_WALK = 571;
TORCHBEARER_OF_THE_5TH_WALK = 572;
TORCHBEARER_OF_THE_6TH_WALK = 573;
TORCHBEARER_OF_THE_7TH_WALK = 574;
TORCHBEARER_OF_THE_8TH_WALK = 575;
FURNITURE_STORE_OWNER = 576;
ARMORY_OWNER = 577;
JEWELRY_STORE_OWNER = 578;
BOUTIQUE_OWNER = 579;
APOTHECARY_OWNER = 580;
CURIOSITY_SHOP_OWNER = 581;
SHOESHOP_OWNER = 582;
FISHMONGER_OWNER = 583;
RESTAURANT_OWNER = 584;
ASSISTANT_DETECTIVE = 585;
PROMISING_DANCER = 586;
STARDUST_DANCER = 587;
ELEGANT_DANCER = 588;
DAZZLING_DANCE_DIVA = 589;
FRIEND_OF_LEHKO_HABHOKA = 590;
SUMMA_CUM_LAUDE = 591;
GRIMOIRE_BEARER = 592;
SEASONING_CONNOISSEUR = 593;
FINE_YOUNG_GRIFFON = 594;
BABBANS_TRAVELING_COMPANION = 595;
FELLOW_FORTIFIER = 596;
CHOCOCHAMPION = 597;
TRAVERSER_OF_TIME = 598;
MYTHRIL_MUSKETEER_NO_6 = 599;
JEWEL_OF_THE_COBRA_UNIT = 600;
KNIGHT_OF_THE_SWIFTWING_GRIFFIN = 601;
WYRMSWORN_PROTECTOR = 602;
FLAMESERPENT_FACILITATOR = 603;
MAZE_WANDERER = 604;
MAZE_NAVIGATOR = 605;
MAZE_SCHOLAR = 606;
MAZE_ARTISAN = 607;
MAZE_OVERLORD = 608;
SWARMINATOR = 609;
BATTLE_OF_JEUNO_VETERAN = 610;
GRAND_GREEDALOX = 611;
KARAHABARUHAS_RESEARCH_ASSISTANT = 612;
HONORARY_KNIGHT_OF_THE_CARDINAL_STAG = 613;
DETECTOR_OF_DECEPTION = 614;
SILENCER_OF_THE_ECHO = 615;
BESTRIDER_OF_FUTURES = 616;
MOG_HOUSE_HANDYPERSON = 617;
PRESIDENTIAL_PROTECTOR = 618;
THE_MOONS_COMPANION = 619;
ARRESTER_OF_THE_ASCENSION = 620;
HOUSE_AURCHIAT_RETAINER = 621;
WANDERER_OF_TIME = 622;
SMITER_OF_THE_SHADOW = 623;
HEIR_OF_THE_BLESSED_RADIANCE = 624;
HEIR_OF_THE_BLIGHTED_GLOOM = 625;
SWORN_TO_THE_DARK_DIVINITY = 626;
TEMPERER_OF_MYTHRIL = 627;
STAR_IN_THE_AZURE_SKY = 628;
FANGMONGER_FORESTALLER = 629;
VISITOR_TO_ABYSSEA = 630;
FRIEND_OF_ABYSSEA = 631;
WARRIOR_OF_ABYSSEA = 632;
STORMER_OF_ABYSSEA = 633;
DEVASTATOR_OF_ABYSSEA = 634;
HERO_OF_ABYSSEA = 635;
CHAMPION_OF_ABYSSEA = 636;
CONQUEROR_OF_ABYSSEA = 637;
SAVIOR_OF_ABYSSEA = 638;
VANQUISHER_OF_SPITE = 639;
HADHAYOSH_HALTERER = 640;
BRIAREUS_FELLER = 641;
KARKINOS_CLAWCRUSHER = 642;
CARABOSSE_QUASHER = 643;
OVNI_OBLITERATOR = 644;
RUMINATOR_CONFOUNDER = 645;
ECCENTRICITY_EXPUNGER = 646;
FISTULE_DRAINER = 647;
KUKULKAN_DEFANGER = 648;
TURUL_GROUNDER = 649;
BLOODEYE_BANISHER = 650;
SATIATOR_DEPRIVER = 651;
IRATHAM_CAPTURER = 652;
LACOVIE_CAPSIZER = 653;
CHLORIS_UPROOTER = 654;
MYRMECOLEON_TAMER = 655;
GLAVOID_STAMPEDER = 656;
USURPER_DEPOSER = 657;
YAANEI_CRASHER = 658;
KUTHAREI_UNHORSER = 659;
SIPPOY_CAPTURER = 660;
TITLACAUAN_DISMEMBERER = 661;
SMOK_DEFOGGER = 662;
AMHULUK_INUNDATER = 663;
PULVERIZER_DISMANTLER = 664;
DURINN_DECEIVER = 665;
KARKADANN_EXOCULATOR = 666;
ULHUADSHI_DESICCATOR = 667;
ITZPAPALOTL_DECLAWER = 668;
SOBEK_MUMMIFIER = 669;
CIREINCROIN_HARPOONER = 670;
BUKHIS_TETHERER = 671;
SEDNA_TUSKBREAKER = 672;
CLEAVER_DISMANTLER = 673;
EXECUTIONER_DISMANTLER = 674;
SEVERER_DISMANTLER = 675;
LUSCA_DEBUNKER = 676;
TRISTITIA_DELIVERER = 677;
KETEA_BEACHER = 678;
RANI_DECROWNER = 679;
ORTHRUS_DECAPITATOR = 680;
DRAGUA_SLAYER = 681;
BENNU_DEPLUMER = 682;
HEDJEDJET_DESTINGER = 683;
CUIJATENDER_DESICCATOR = 684;
BRULO_EXTINGUISHER = 685;
PANTOKRATOR_DISPROVER = 686;
APADEMAK_ANNIHILATOR = 687;
ISGEBIND_DEFROSTER = 688;
RESHEPH_ERADICATOR = 689;
EMPOUSA_EXPURGATOR = 690;
INDRIK_IMMOLATOR = 691;
OGOPOGO_OVERTURNER = 692;
RAJA_REGICIDE = 693;
ALFARD_DETOXIFIER = 694;
AZDAJA_ABOLISHER = 695;
AMPHITRITE_SHUCKER = 696;
FUATH_PURIFIER = 697;
KILLAKRIQ_EXCORIATOR = 698;
MAERE_BESTIRRER = 699;
WYRM_GOD_DEFIER = 700;
HAHAVA_CONDEMNER = 701;
CELAENO_SILENCER = 702;
VOIDWROUGHT_DECONSTRUCTOR = 703;
DEVOURER_OF_SHADOWS = 704;
KAGGEN_CLOBBERER = 705;
AKVAN_ABSTERGER = 706;
PIL_UNFROCKER = 707;
QILIN_CONTRAVENER = 708;
UPTALA_REPROBATOR = 709;
AELLO_ABATOR = 710;
TORCHBEARER_OF_THE_9TH_WALK = 711;
TORCHBEARER_OF_THE_10TH_WALK = 712;
TORCHBEARER_OF_THE_11TH_WALK = 713;
NIGHTMARE_ILLUMINATOR = 714;
GAUNAB_GUTTER = 715;
KALASUTRAX_CREMATOR = 716;
OCYTHOE_OVERRIDER = 717;
IG_ALIMA_INHUMER = 718;
BOTULUS_REX_ENGORGER = 719;
TORCHBEARER_OF_THE_12TH_WALK = 720;
TORCHBEARER_OF_THE_13TH_WALK = 721;
TORCHBEARER_OF_THE_14TH_WALK = 722;
TORCHBEARER_OF_THE_15TH_WALK = 723;
DELVER_OF_THE_DEPTHS = 724;
SUBJUGATOR_OF_THE_LOFTY = 725;
SUBJUGATOR_OF_THE_MIRED = 726;
SUBJUGATOR_OF_THE_SOARING = 727;
SUBJUGATOR_OF_THE_VEILED = 728;
LEGENDARY_LEGIONNAIRE = 729;
WITNESS_TO_PROVENANCE = 730;
BISMARCK_FLENSER = 731;
MORTA_EXTIRPATOR = 732;
UNSUNG_HEROINE = 733;
EPIC_HEROINE = 734;
EPIC_EINHERJAR = 735;
MENDER_OF_WINGS = 736;
CHAMPION_OF_THE_DAWN = 737;
BUSHIN_ASPIRANT = 738;
BUSHIN_RYU_INHERITOR = 739;
TEMENOS_EMANCIPATOR = 740;
APOLLYON_RAZER = 741;
GOLDWING_SQUASHER = 742;
SILAGILITH_DETONATOR = 743;
SURTR_SMOTHERER = 744;
DREYRUK_PREDOMINATOR = 745;
SAMURSK_VITIATOR = 746;
UMAGRHK_MANEMANGLER = 747;
SUPERNAL_SAVANT = 748;
SOLAR_SAGE = 749;
BOLIDE_BARON = 750;
MOON_MAVEN = 751;
IZYX_VEXER = 752;
GRANNUS_GARROTER = 753;
SVAHA_STRIKER = 754;
MELISSEUS_DOMESTICATOR = 755;
WATERWAY_EXEMPLAR = 756;
CAVERN_EXEMPLAR = 757;
MUYINGWA_WINGCRUSHER = 758;
DAKUWAQA_TRAWLER = 759;
TOJIL_DOUSER = 760;
COLKHAB_DETHRONER = 761;
ACHUKA_GLACIATOR = 762;
TCHAKKA_DESICCATOR = 763;
WEALD_EXEMPLAR = 764;
HURKAN_BIRDLIMEIST = 765;
YUMCAX_LOGGER = 766;
COLKHAB_HIVECRUSHER = 767;
ACHUKA_COAGULATOR = 768;
TCHAKKA_FILLETER = 769;
RABBIT_TUSSLER = 770;
HELMINTH_MINCER = 771;
MANDRAGARDENER = 772;
MOPPET_MASSACRER = 773;
RIP_ROARING_LIMBRENDER = 774;
SHELL_SHOCKER = 775;
YAGUDO_COOPKEEPER = 776;
GIGASPLOSION_EXPERT = 777;
BROTHER_IN_ARMS = 778;
ANTICA_HUNTER = 779;
AMPHIBIAN_ADULTERATOR = 780;
TONBERRY_TOPPLER = 781;
BLOODLINE_CORRUPTER = 782;
KUMHAU_ROASTER = 783;
BRILLIANCE_MANIFEST = 784;
QUIETER_OF_ANCIENT_THOUGHTS = 785;
ARK_HUME_HUMILIATOR = 786;
ARK_ELVAAN_EVISCERATOR = 787;
ARK_MITHRA_MALIGNER = 788;
ARK_TARUTARU_TROUNCER = 789;
ARK_GALKA_GOUGER = 790;
PENTARCH_PACIFIER = 791;
DREAM_DISTILLER = 792;
RAKAZNAR_EXEMPLAR = 793;
UTKUX_PELTBURNER = 794;
CAILIMH_PLUMAGEPLUCKER = 795;
WOPKET_TRUNKSPLITTER = 796;
OURYU_OBFUSCATOR = 797;
UNWAVERING_BLAZE = 798;
LANCELORD_DIVESTER = 799;
GESSHO_PINIONER = 800;
SIN_PURGER = 801;
ADUMBRATION_DISPERSER = 802;
QUELLER_OF_OTHERWORLDLY_GALES = 803;
BLAZE_MARSHALLER = 804;
PENITENTES_BLASTER = 805;
SIROCCO_TAMER = 806;
SUCHIAN_FELLER = 807;
OMBIFID_SLAYER = 808;
NILOTICAN_DECIMATOR = 809;
ILLUMINATOR_OF_THE_1ST_WALK = 810;
ILLUMINATOR_OF_THE_2ND_WALK = 811;
ILLUMINATOR_OF_THE_3RD_WALK = 812;
ILLUMINATOR_OF_THE_4TH_WALK = 813;
ILLUMINATOR_OF_THE_5TH_WALK = 814;
ILLUMINATOR_OF_THE_6TH_WALK = 815;
ILLUMINATOR_OF_THE_7TH_WALK = 816;
ILLUMINATOR_OF_THE_8TH_WALK = 817;
ILLUMINATOR_OF_THE_9TH_WALK = 818;
ILLUMINATOR_OF_THE_10TH_WALK = 819;
ILLUMINATOR_OF_THE_11TH_WALK = 820;
ILLUMINATOR_OF_THE_12TH_WALK = 821;
ILLUMINATOR_OF_THE_13TH_WALK = 822;
ILLUMINATOR_OF_THE_14TH_WALK = 823;
ILLUMINATOR_OF_THE_15TH_WALK = 824;
LITHOSPHERE_ANNIHILATOR = 825;
FULMINATION_DISRUPTOR = 826;
BORE_REPULSOR = 827;
-- Unused = 828;
-- Unused = 829;
-- Unused = 830;
-- Unused = 831;
-- Unused = 832;
-- Unused = 833;
-- Unused = 834;
-- Unused = 835;
GEODANCER = 836;
RUNIC_ENGRAVER = 837;
APPRENTICE_TARUTARU_SAUCE_MANAGER = 838;
VEGETABLE_REVOLUTIONARY = 839;
FRIEND_TO_GLUTTONS = 840;
WAYPOINT_WARRIOR = 841;
ULBUKAN_STALWART = 842;
TOXIN_TUSSLER = 843;
SPIRITUAL_STAR = 844;
STIPPLING_STAR = 845;
GEOMANCIPATOR = 846;
TRIALED_AND_TRUE_RUNEIST = 847;
QUEENS_CONFIDANTE = 848;
PRINCESSS_PARTISAN = 849;
POTATION_PATHFINDER = 850;
STORIED_GEOMANCER = 851;
ULTIMATE_RUNEIST = 852;
MOG_GARDEN_SEEDLING = 853;
KIT_EMPATHIZER = 854;
JINGLY_DANGLER = 855;
MOLE_MANIPULATOR = 856;
AGRARIAN_NOVICE = 857;
AGRARIAN_INITIATE = 858;
AGRARIAN_PROFESSIONAL = 859;
AGRARIAN_VIRTUOSO = 860;
AGRARIAN_TUTELAR = 861;
WEED_PRAETOR = 862;
TREE_PRAETOR = 863;
THICKET_PRAETOR = 864;
FOREST_PRAETOR = 865;
JUNGLE_PRAETOR = 866;
COPPER_MATTOCK = 867;
SILVER_MATTOCK = 868;
MYTHRIL_MATTOCK = 869;
GOLD_MATTOCK = 870;
ADAMANTTOCK = 871;
PUDDLE_PATRON = 872;
SWAMP_SAVANT = 873;
POND_PRECEPTOR = 874;
RIVER_REGENT = 875;
MONKE_ONKE_MASTER = 876;
SARDINEOPHYTE = 877;
CALAMAREELER = 878;
OCTOPOTENTATE = 879;
GIANT_SQUIMPERATOR = 880;
LEVIAUTHORITY = 881;
NOVICE_NURSERYMAN = 882;
LESSER_LANDSCAPER = 883;
GREATER_GARDENER = 884;
HONORED_HORTICULTURIST = 885;
MOG_GARDENER = 886;
BRYGIDESQUE_MANAGER = 887;
VEGETABLE_EVOLUTIONARY = 888;
BLADE_ENTHUSIAST = 889;
RUNIC_EMISSARY = 890;
MAESTER_OF_MADDENING = 891;
SUNSHINE_CADET = 892;
QUARTET_CAPTIVATOR = 893;
THE_TRUSTWORTHY = 894;
THE_LOVELORN = 895;
INVENTOR_EXTRAORDINAIRE = 896;
BOOMY_AND_BUSTY = 897;
WEATHERER_OF_BRUMAL_CLIMES = 898;
WHITE_KNIGHT = 899;
LIGHT_OF_DAWN = 900;
OBSERVER_OF_FATEFUL_CUBES = 901;
KNOWER_OF_UNTRUTHS = 902;
ULBUKAN_UNDERSTUDY = 903;
KEEPER_OF_ULBUKA = 904;
RADIANCE_OF_DAYBREAK = 905;
WIBBLY_WOBBLY_WOOZY_WARRIOR = 906;
HEIR_OF_ETERNITY = 907;
PROSPECTIVE_PAMPERER = 908;
NOVICE_NUZZLER = 909;
SERIOUS_SNUGGLER = 910;
CULTIVATED_CODDLER = 911;
RESPECTED_RUFFLER = 912;
DUNG_DISSEMINATOR = 913;
FAUNA_FEEDER = 914;
CONFIDENT_CARETAKER = 915;
GLORIOUS_GROOMER = 916;
TRANSCENDENTAL_TAMER = 917;
BOND_BUILDING_BREEDER = 918;
CLUMSY_CLEAVER = 919;
DISCIPLINED_DISSECTOR = 920;
ESTABLISHED_EXAMINER = 921;
SUBLIME_SLICER = 922;
LIFTER_OF_SPIRITS = 923;
SHEDDER_OF_HARLEQUIN_TEARS = 924;
HOPE_FOR_THE_FUTURE = 925;
THOUSAND_YEAR_TRAVELER = 926;
VANQUISHER_OF_ASHRAKK = 927;
VANQUISHER_OF_DHOKMAK = 928;
PROTECTED_BY_ULBUKAN_SPIRITS = 929;
RECEIVER_OF_SIGILS = 930;
DESTROYER_OF_HADES = 931;
BRINGER_OF_THE_DAWN = 932;
THE_ONE_TRUE_PIONEER = 933;
BRINGER_OF_HOPE = 934;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Castle_Oztroja/npcs/_m74.lua | 16 | 2227 | -----------------------------------
-- Area: Castle Oztroja
-- NPC: _m74 (Torch Stand)
-- Notes: Opens door _477 when _m72 to _m75 are lit
-- @pos -59.525 -72.320 -62.379 151
-----------------------------------
package.loaded["scripts/zones/Castle_Oztroja/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Castle_Oztroja/TextIDs");
require("scripts/globals/settings");
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
DoorID = npc:getID() - 4;
Torch1 = npc:getID() - 2;
Torch2 = npc:getID() - 1;
Torch3 = npc:getID();
Torch4 = npc:getID() + 1;
DoorA = GetNPCByID(DoorID):getAnimation();
TorchStand1A = GetNPCByID(Torch1):getAnimation();
TorchStand2A = GetNPCByID(Torch2):getAnimation();
TorchStand3A = npc:getAnimation();
TorchStand4A = GetNPCByID(Torch4):getAnimation();
if (DoorA == 9 and TorchStand3A == 9) then
player:startEvent(0x000a);
else
player:messageSpecial(TORCH_LIT);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (option == 1) then
GetNPCByID(Torch3):openDoor(55);
if ((DoorA == 9) and (TorchStand1A == 8) and (TorchStand2A == 8) and (TorchStand4A == 8)) then
GetNPCByID(DoorID):openDoor(35);
-- The lamps shouldn't go off here, but I couldn't get the torches to update animation times without turning them off first
-- They need to be reset to the door open time(35s) + 4s (39 seconds)
GetNPCByID(Torch1):setAnimation(9);
GetNPCByID(Torch2):setAnimation(9);
GetNPCByID(Torch3):setAnimation(9);
GetNPCByID(Torch4):setAnimation(9);
GetNPCByID(Torch1):openDoor(39);
GetNPCByID(Torch2):openDoor(39);
GetNPCByID(Torch3):openDoor(39);
GetNPCByID(Torch4):openDoor(39);
end
end
end;
| gpl-3.0 |
nasomi/darkstar | scripts/globals/items/cup_of_date_tea.lua | 36 | 1352 | -----------------------------------------
-- ID: 5926
-- Item: Cup of Date Tea
-- Food Effect: 3 Hrs, All Races
-----------------------------------------
-- HP 20
-- MP 30
-- Vitality -1
-- Charisma 5
-- Intelligence 3
-----------------------------------------
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,10800,5926);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_MP, 30);
target:addMod(MOD_VIT, -1);
target:addMod(MOD_CHR, 5);
target:addMod(MOD_INT, 3);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_MP, 30);
target:delMod(MOD_VIT, -1);
target:delMod(MOD_CHR, 5);
target:delMod(MOD_INT, 3);
end;
| gpl-3.0 |
OpenPrograms/payonel-Programs | payo-lib/usr/lib/payo-lib/config.lua | 1 | 1249 | local fs = require("filesystem");
local des = require("serialization").unserialize
local ser = require("serialization").serialize
local config = {};
function config.load(configPath)
if (type(configPath) ~= type("")) then
return nil, "file path must be a string";
end
if (not fs.exists(configPath)) then
return nil, string.format("cannot open [%s]. Path does not exist", configPath);
end
local handle, reason = io.open(configPath, "rb");
if (not handle) then
return nil, reason
end
local all = handle:read("*a");
handle:close();
return des(all);
end
function config.save(config, configPath)
if (type(configPath) ~= type("")) then
return nil, "file path must be a string";
end
if (type(config) ~= type({})) then
return nil, "can only save tables"
end
local s, reason = ser(config);
if (not s) then
return nil, "Will not be able to save: " .. tostring(reason);
end
local pwd = configPath:gsub('[^/]*$','')
if (not fs.exists(pwd)) then
local mkdir = loadfile("/bin/mkdir.lua");
mkdir(pwd);
end
local handle, reason = io.open(configPath, "wb");
if (not handle) then
return nil, reason
end
handle:write(s);
handle:close();
return true
end
return config;
| mit |
kenyh0926/DBProxy | lib/proxy/split.lua | 41 | 14816 | module("proxy.split", package.seeall)
--local table = require("proxy.table")
local crc = require("proxy.crc32")
local log = require("proxy.log")
local filter = require("proxy.filter")
local config_file = string.format("proxy.conf.config_%s", proxy.global.config.instance)
local config = require(config_file)
local level = log.level
local write_log = log.write_log
--[[
-- Find Table Name's Index Number From Tokens
-- @param tokens - ARRAY
-- @param break_token - STRING do break when foreach
-- @param start_token - INT start number when foreach
--
]]
function __findtable_form_tokens(tokens, break_token, start_token)
write_log(level.DEBUG, "ENTER __FINDTABLE_FORM_TOKENS")
local index = {}
index.d = 0
index.t = 0
for j = start_token + 1, #tokens-1 do
if tokens[j].token_name == break_token then break end
if tokens[j].token_name == "TK_LITERAL" then
if tokens[j+1].text ~= "." then --ÊÊÓ¦table
index.t = j
break
else --ÊÊÓ¦db.table
index.d = j
index.t = j+2
end
end
end
write_log(level.DEBUG, "LEAVE __FINDTABLE_FORM_TOKENS")
return index
end
function __findtable_form_insert(tokens)
write_log(level.DEBUG, "ENTER __FINDTABLE_FORM_INSERT")
local index = {}
index.d = 0
index.t = 0
for j = 2, #tokens-1 do
local text = string.upper(tokens[j].text)
if text == "VALUES" or text == "VALUE" then break end
if tokens[j].token_name == "TK_LITERAL" and tokens[j+1].text == "." then -- ÊÊÓ¦ db.table ...
index.d = j
index.t = j+2
break
elseif (tokens[j].token_name == "TK_LITERAL" or tokens[j].token_name == "TK_FUNCTION") then
local next_text = string.upper(tokens[j+1].text)
if next_text == "VALUES" or next_text == "VALUE" or next_text == "(" or next_text == "SET" then -- ÊÊÓ¦ table
index.t = j
break
end
end
end
write_log(level.DEBUG, "LEAVE __FINDTABLE_FORM_INSERT")
return index
end
function get_table_index(tokens, sql_type)
write_log(level.DEBUG, "ENTER GET_TABLE_INDEX")
local dt_index = {}
dt_index.d = 0
dt_index.t = 0
if sql_type == 1 then -- SELECT
-- find 'from' index
for i = 2, #tokens-1 do
if tokens[i].token_name == "TK_SQL_FROM" then
dt_index = __findtable_form_tokens(tokens, 'TK_WHERE', i)
end
end
elseif sql_type == 2 then --UPDATEÓï¾ä
dt_index = __findtable_form_tokens(tokens, 'TK_SQL_SET', 1)
elseif sql_type == 3 then --INSERTÓï¾ä£¬Ã»ÓÐͬʱINSERT¶à¸ö±íµÄÇé¿ö
dt_index = __findtable_form_insert(tokens)
end
if dt_index.d == 0 then
write_log(level.INFO, "db not found")
else
write_log(level.INFO, "db = ", tokens[dt_index.d].text)
end
if dt_index.t == 0 then
write_log(level.INFO, "table not found")
else
write_log(level.INFO, "table = ", tokens[dt_index.t].text)
end
write_log(level.DEBUG, "LEAVE GET_TABLE_INDEX")
return dt_index
end
function get_colum_index(tokens, g_table_arr, sql_type, start) --²éÕÒÃûΪpropertyµÄ×ֶΣ¬ÕÒµ½Ê±·µ»Ø¸ÃtokenµÄindexÖµ£¬·ñÔò·µ»Ø0
write_log(level.DEBUG, "ENTER GET_COLUMN_INDEX")
local index = {}
local m = 1
if sql_type == 1 then --SELECT»òDELETEÓï¾ä
for i = start, #tokens-3 do
if tokens[i].token_name == "TK_SQL_WHERE" then
for j = i+1, #tokens-2 do
if tokens[j].token_name == "TK_LITERAL" and tokens[j].text == g_table_arr.property then
if tokens[j+1].text == "=" then --×Ö¶ÎÃûºóÃæÊǵȺţ¬ËµÃ÷Êǵ¥Öµ
if tokens[j-1].text ~= "." or tokens[j-2].text == g_table_arr.name then
index[m] = j + 2
break
end
elseif tokens[j+1].text:upper() == "IN" and tokens[j+2].text == "(" then --×Ö¶ÎÃûºóÃæÊÇINºÍ×óÀ¨ºÅ£¬ËµÃ÷ÊǶàÖµ
local k = j + 2
while tokens[k].text~= ")" do
index[m] = k + 1
k = k + 2
m = m + 1
end
end
end
end
end
end
elseif sql_type == 2 then --UPDATEÓï¾ä
for i = start, #tokens-3 do
if tokens[i].token_name == "TK_SQL_WHERE" then
for j = i+1, #tokens-2 do
if tokens[j].token_name == "TK_LITERAL" and tokens[j].text == g_table_arr.property and tokens[j+1].text == "=" then
if tokens[j-1].text ~= "." or tokens[j-2].text == g_table_arr.name then
index[m] = j + 2
break
end
end
end
end
end
elseif sql_type == 3 then --INSERT»òREPLACEÓï¾ä
local start_text = string.upper(tokens[start].text)
if start_text == "SET" then --"set ÊôÐÔ = Öµ"µÄÐÎʽ
for i = start+1, #tokens-2 do
if tokens[i].text == g_table_arr.property and tokens[i].token_name == "TK_LITERAL" then
index[m] = i + 2
break
end
end
else
local k = 2
if start_text == "(" then --´øÓÐ×Ö¶ÎÃûµÄÇé¿ö
local found = nil
for j = start+1, #tokens-3 do
if tokens[j].text == ")" then break end --ÕÒµ½ÓÒÀ¨ºÅÔòÌø³öÑ»·
if tokens[j].text == g_table_arr.property and tokens[j].token_name == "TK_LITERAL" then
if tokens[j-1].text ~= "." or tokens[j-2].text == g_table_arr.name then
found = j
break
end
end
end
k = found - start + 1
end
for i = start, #tokens-3 do
local text = string.upper(tokens[i].text)
if (text == "VALUES" or text == "VALUE") and tokens[i+1].text == "(" and string.match(tokens[i+k].text, "^%d+$") then
index[m] = i + k
break
end
end
end
end
if #index == 0 then
write_log(level.INFO, "column not found")
else
for i = 1, #index do
write_log(level.INFO, "column = ", tokens[index[i]].text)
end
end
write_log(level.DEBUG, "LEAVE GET_COLUMN_INDEX")
return index
end
function combine_sql(tokens, table_index, colum_index, g_table_arr)
write_log(level.DEBUG, "ENTER COMBINE_SQL")
local partition = g_table_arr.partition
local sqls = {}
if #colum_index == 1 then
local sql = ""
if tokens[1].token_name ~= "TK_COMMENT" then sql = tokens[1].text end
for i = 2, #tokens do
if tokens[i].text ~= "(" then
sql = sql .. ' '
end
if i == table_index then
sql = sql .. tokens[i].text
local column_value = tokens[colum_index[1]].text --×Ö¶ÎÖµ
if string.match(column_value, "^%d+$") then -- ²»ÄÜʹÓÃTK_INTER,Êý×Ö¿ÉÄܼÓ'', splitid Ö»Ö§³ÖÕûÐÎ
sql = sql .. "_" .. (column_value % partition)
else
local key = crc.hash(column_value)
if key > 2147483647 then
key = key - 4294967296
end
sql = sql .. "_" .. (math.abs(key) % partition)
end
elseif tokens[i].token_name == "TK_STRING" then
sql = sql .. "'" .. tokens[i].text .. "'"
elseif tokens[i].token_name ~= "TK_COMMENT" then
sql = sql .. tokens[i].text
end
end
sqls[1] = sql
write_log(level.INFO, "SQL = ", sql)
else
local mt = {}
for i = 1, partition do --ÉùÃ÷¶þάÊý×é
mt[i] = {}
end
for i = 1, #colum_index do
local column_value = tokens[colum_index[i]].text --×Ö¶ÎÖµ
local mod = nil --Ä£Öµ
if string.match(column_value, "^%d+$") then -- ²»ÄÜʹÓÃTK_INTER,Êý×Ö¿ÉÄܼÓ'', splitid Ö»Ö§³ÖÕûÐÎ
mod = column_value % partition + 1
local n = #mt[mod] + 1
mt[mod][n] = column_value
else --×Ö¶ÎֵΪ×Ö·û´®µÄÇé¿ö
local key = crc.hash(column_value)
if key > 2147483647 then
key = key - 4294967296
end
mod = math.abs(key) % partition + 1
local n = #mt[mod] + 1
mt[mod][n] = "'" .. column_value .. "'"
end
end
local property_index = colum_index[1] - 3 --×Ö¶ÎÃûµÄË÷Òý
local start_skip_index = property_index + 1 --INµÄË÷Òý
local end_skip_index = property_index + (#colum_index + 1) * 2 --ÓÒÀ¨ºÅµÄË÷Òý
local j = 1
for m = 1, partition do --Óм¸ÕÅ×Ó±í¾ÍÉú³É¼¸¸öSQLÓï¾ä
if #mt[m] > 0 then
local tmp = nil
tmp = " IN(" .. mt[m][1]
for k = 2, #mt[m] do
tmp = tmp .. "," .. mt[m][k]
end
tmp = tmp .. ")"
local sql = ""
if tokens[1].token_name ~= "TK_COMMENT" then sql = tokens[1].text end
for i = 2, #tokens do
if i < start_skip_index or i > end_skip_index then --Ìø¹ýÔʼSQLÖÐINµ½ÓÒÀ¨ºÅµÄ²¿·Ö
if tokens[i].text ~= "(" then
sql = sql .. ' '
end
if i == table_index then
sql = sql .. tokens[i].text .. "_" .. m-1
elseif i == property_index then
sql = sql .. tokens[i].text .. tmp
elseif tokens[i].token_name ~= "TK_COMMENT" then
sql = sql .. tokens[i].text
end
end
end
sqls[j] = sql
j = j + 1
write_log(level.INFO, "SQL = ", sql)
end
end
end
write_log(level.DEBUG, "LEAVE COMBINE_SQL")
return sqls
end
--[[
-- SQL·ÖÎöÆ÷
-- ÅжÏÊÇ·ñÃüÖзֱíÅäÖÃ
-- ½øÐÐһЩΣÏÕSQL¹ýÂË
--
--]]
function sql_parse(tokens, query)
write_log(level.DEBUG, "ENTER SQL_PARSE")
local re = {}
-- local config = table.config
local table = config.table
local dt_index = {}
local split_colum_index = {}
-- re[1] = query
split_colum_index[1] = 0
--for k,v in pairs(config) do print(k,v.property) end
--[[
for i = 1, #tokens do
print(string.format("%s\t%s", tokens[i].token_name, tokens[i].text))
end
]]
local sql_type = filter.is_whitelist(tokens)
if sql_type == false then
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "Proxy Warning - Syntax Forbidden(NOT in Whitelist)"
}
write_log(level.WARN, query, ": Syntax Forbidden(NOT in Whitelist)")
write_log(level.DEBUG, "LEAVE SQL_PARSE")
return re, -1
end
if filter.is_blacklist(tokens) then
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "Proxy Warning - Syntax Forbidden(Blacklist)"
}
write_log(level.WARN, query, ": Syntax Forbidden(Blacklist)")
write_log(level.DEBUG, "LEAVE SQL_PARSE")
return re, -1
end
if sql_type == 4 then
return re, 0
end
--[[
-- SQL Parse for Split
--]]
-- global array - table_index's attribute
g_table_arr = {}
-- init g_table_arr and find tablename's index
dt_index = get_table_index(tokens, sql_type)
local d = dt_index.d
local t = dt_index.t
if t == 0 then --ÎÞtable£¬Ôò²»ÐèaddÒ²²»Ðèsplit
write_log(level.DEBUG, "LEAVE SQL_PARSE");
re[1] = query
return re, 1
end
local is_split = false
local dbtable
if d == 0 then --tableÐÎʽ
dbtable = proxy.connection.client.default_db .. "." .. tokens[t].text
else --db.tableÐÎʽ
dbtable = tokens[d].text..'.'.. tokens[t].text
end
if table[dbtable] then
g_table_arr = table[dbtable]
is_split = true
end
--print("TABLENAME_INDEX = " .. tablename_index);
--print("-------------debug---------")
-- ÃüÖзֱíÅäÖÃ
if is_split then
--print("Found table for split")
split_colum_index = get_colum_index(tokens, g_table_arr, sql_type, t + 1)
if #split_colum_index > 0 then
--[[
print("Found colum for split")
print("property: " .. g_table_arr.property)
print("partition: " .. g_table_arr.partition)
print("table index: " .. t)
print("colum index: " .. split_colum_index)
]]
else
proxy.response = {
type = proxy.MYSQLD_PACKET_ERR,
errmsg = "Proxy Warning - Syntax Error(SQL Parse)"
}
write_log(level.WARN, query, ": Syntax Error(SQL Parse)")
write_log(level.DEBUG, "LEAVE SQL_PARSE")
return re, -1
end
end
if is_split then
re = combine_sql(tokens, t, split_colum_index, g_table_arr)
else
re[1] = query
end
--print("-------------debug---------")
g_table_arr = {} -- delete
write_log(level.DEBUG, "LEAVE SQL_PARSE")
return re, 1
end
function merge_rows(rows_left, rows_right_fun, sorttype, sortindex, limit)
-- init
local rows_right = {}
local rows_merge = {}
limit = tonumber(limit)
local i = 1
for row in rows_right_fun do
rows_right[i] = row
i = i + 1
end
-- return when one of array is nil
if (rows_left == nil or #rows_left < 1) and rows_right ~= nil then
--print('return rows_right')
return rows_right
end
if (rows_right == nil or #rows_right < 1) and rows_left ~= nil then
--print('return rows_left')
return rows_left
end
local left_num = #rows_left
local right_num = #rows_right
local i = 1
local j = 1
local k = 1
-- merge sort
if sorttype == false then
rows_merge = table_merge(rows_left, rows_right, limit)
else
if sorttype == "TK_SQL_ASC" then
while i < left_num+1 and j < right_num+1 do
if limit > -1 and k > limit then
break
end
if rows_left[i][sortindex] and rows_right[j][sortindex] and
tonumber(rows_left[i][sortindex]) < tonumber(rows_right[j][sortindex]) then
rows_merge[k] = rows_left[i]
--print(rows_merge[k][sortindex]..' '..rows_left[i][sortindex]..' '..rows_right[j][sortindex])
i = i + 1
else
rows_merge[k] = rows_right[j]
--print(rows_merge[k][sortindex]..' '..rows_left[i][sortindex]..' '..rows_right[j][sortindex])
j = j + 1
end
k = k + 1
end
elseif sorttype == "TK_SQL_DESC" then
while i < left_num+1 and j < right_num+1 do
if limit > -1 and k > limit then
break
end
if tonumber(rows_left[i][sortindex]) > tonumber(rows_right[j][sortindex]) then
rows_merge[k] = rows_left[i]
i = i + 1
else
rows_merge[k] = rows_right[j]
j = j + 1
end
k = k + 1
end
end
while i < left_num+1 do
if limit > -1 and k > limit then
break
end
rows_merge[k] = rows_left[i]
k = k + 1
i = i + 1
end
while j < right_num+1 do
if limit > -1 and k > limit then
break
end
rows_merge[k] = rows_right[j]
k = k + 1
j = j + 1
end
end
return rows_merge
end
function table_merge(t1, t2, limit)
limit = tonumber(limit)
if not t1 and not t2 then
return false
end
if #t1 >= limit then
return t1
end
local i = #t1
for j = 1, #t2 do
if i >= limit then
break
end
t1[#t1+1] = t2[j]
i = i + 1
end
return t1
end
| gpl-2.0 |
Hello23-Ygopro/ygopro-ds | expansions/script/c27003031.lua | 1 | 1282 | --BT3-030 Planet M-2
local ds=require "expansions.utility_dbscg"
local scard,sid=ds.GetID()
function scard.initial_effect(c)
--field
ds.EnableField(c,ds.PayEnergyCost(COLOR_RED,1,0))
--draw
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(sid,0))
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_TRIGGER_F)
e1:SetCode(EVENT_CUSTOM+DS_EVENT_EXTRA_TOBATTLE_SUCCESS)
e1:SetRange(DS_LOCATION_BATTLE_FIELD)
e1:SetCondition(ds.ldscon(aux.FilterBoolFunction(Card.IsCharacter,CHARACTER_DR_MYUU)))
e1:SetTarget(ds.hinttg)
e1:SetOperation(ds.DrawOperation(PLAYER_PLAYER,1))
c:RegisterEffect(e1)
--power down
ds.AddActivateBattleSkill(c,1,DS_LOCATION_BATTLE_FIELD,scard.powop,scard.powcost,scard.powtg,DS_EFFECT_FLAG_CARD_CHOOSE,scard.powcon)
end
scard.dragon_ball_super_card=true
scard.powcon=ds.turnpcon(PLAYER_PLAYER)
scard.powcost=ds.SelfSwitchtoRestCost
function scard.powfilter(c)
return c:IsFaceup() and (c:IsLeader() or c:IsBattle())
end
scard.powtg=ds.ChooseCardFunction(PLAYER_PLAYER,scard.powfilter,0,DS_LOCATION_IN_PLAY,0,1,DS_HINTMSG_POWERDOWN)
function scard.powop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not tc or not tc:IsRelateToSkill(e) then return end
ds.GainSkillUpdatePower(e:GetHandler(),tc,2,-5000,RESET_PHASE+PHASE_DAMAGE)
end
| gpl-3.0 |
MatthewDwyer/botman | mudlet/profiles/newbot/scripts/chat/gmsg_tracker.lua | 1 | 33948 | --[[
Botman - A collection of scripts for managing 7 Days to Die servers
Copyright (C) 2020 Matthew Dwyer
This copyright applies to the Lua source code in this Mudlet profile.
Email smegzor@gmail.com
URL http://botman.nz
Source https://bitbucket.org/mhdwyer/botman
--]]
local debug, result, tmp, r, cursor ,errorString, help
local shortHelp = false
local skipHelp = false
local filter = ""
debug = false -- should be false unless testing
function gmsg_tracker()
calledFunction = "gmsg_tracker"
result = false
tmp = {}
if botman.debugAll then
debug = true -- this should be true
end
-- ################## tracker command functions ##################
local function cmd_CheckBases()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}check bases"
help[2] = "Load base coordinates into the tracker so you can tp directly to each base in sequence. Used for visiting every single base ingame."
tmp.command = help[1]
tmp.keywords = "track,base,visit,check"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or string.find(chatvars.command, "base") or string.find(chatvars.command, "visit") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if ((chatvars.words[1] == "check") and (chatvars.words[2] == "bases")) then
if (chatvars.accessLevel > 2) then
message(string.format("pm %s [%s]" .. restrictedCommandMessage(), chatvars.playerid, server.chatColour))
botman.faultyChat = false
return true
end
igplayers[chatvars.playerid].trackerID = 0
conn:execute("DELETE FROM memTracker WHERE admin = " .. chatvars.playerid)
cursor,errorString = conn:execute("SELECT steam, homeX, homeY, homeZ, home2X, home2Y, home2Z from players")
row = cursor:fetch({}, "a")
while row do
if tonumber(row.homeX) ~= 0 and tonumber(row.homeY) ~= 0 and tonumber(row.homeZ) ~= 0 then
conn:execute("INSERT into memTracker (admin, steam, x, y, z, flag) VALUES (" .. chatvars.playerid .. "," .. row.steam .. "," .. row.homeX .. "," .. row.homeY .. "," .. row.homeZ .. ",'base1')")
end
if tonumber(row.home2X) ~= 0 and tonumber(row.home2Y) ~= 0 and tonumber(row.home2Z) ~= 0 then
conn:execute("INSERT into memTracker (admin, steam, x, y, z, flag) VALUES (" .. chatvars.playerid .. "," .. row.steam .. "," .. row.home2X .. "," .. row.home2Y .. "," .. row.home2Z .. ",'base2')")
end
row = cursor:fetch(row, "a")
end
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Bases are loaded into the tracker. Use " .. server.commandPrefix .. "nb to move forward, " .. server.commandPrefix .. "pb to move back and " .. server.commandPrefix .. "killbase to remove the current base.[-]")
botman.faultyChat = false
return true
end
end
local function cmd_DeleteBase()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}killbase"
help[2] = "Remove the current base and protection that the tracker has teleported you to. Used with " .. server.commandPrefix .. "check base."
tmp.command = help[1]
tmp.keywords = "track,base,kill,dele,remo"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or string.find(chatvars.command, "base") or string.find(chatvars.command, "remo") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "killbase" and chatvars.words[2] == nil) then
if (chatvars.accessLevel > 2) then
message(string.format("pm %s [%s]" .. restrictedCommandMessage(), chatvars.playerid, server.chatColour))
botman.faultyChat = false
return true
end
if igplayers[chatvars.playerid].atBase ~= nil then
if tonumber(igplayers[chatvars.playerid].whichBase) == 1 then
players[igplayers[chatvars.playerid].atBase].homeX = 0
players[igplayers[chatvars.playerid].atBase].homeY = 0
players[igplayers[chatvars.playerid].atBase].homeZ = 0
players[igplayers[chatvars.playerid].atBase].protect = false
conn:execute("UPDATE players SET homeX = 0, homeY = 0, homeZ = 0, protect = 0 WHERE steam = " .. igplayers[chatvars.playerid].atBase)
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Base one of " .. players[igplayers[chatvars.playerid].atBase].name .. " has been deleted.[-]")
else
players[igplayers[chatvars.playerid].atBase].home2X = 0
players[igplayers[chatvars.playerid].atBase].home2Y = 0
players[igplayers[chatvars.playerid].atBase].home2Z = 0
players[igplayers[chatvars.playerid].atBase].protect2 = false
conn:execute("UPDATE players SET home2X = 0, home2Y = 0, home2Z = 0, protect2 = 0 WHERE steam = " .. igplayers[chatvars.playerid].atBase)
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Base two of " .. players[igplayers[chatvars.playerid].atBase].name .. " has been deleted.[-]")
end
end
botman.faultyChat = false
return true
end
end
local function cmd_GoBack()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}go back"
help[2] = "Remove the current base and protection that the tracker has teleported you to. Used with " .. server.commandPrefix .. "check base."
tmp.command = help[1]
tmp.keywords = "track,back,chang,dire"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or string.find(chatvars.command, "dire") or string.find(chatvars.command, "back") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "go" and chatvars.words[2] == "back") then
if (chatvars.accessLevel > 2) then
botman.faultyChat = false
return true
end
if igplayers[chatvars.playerid].trackerReversed == true then
igplayers[chatvars.playerid].trackerReversed = false
else
igplayers[chatvars.playerid].trackerReversed = true
end
igplayers[chatvars.playerid].trackerStopped = false
botman.faultyChat = false
return true
end
end
local function cmd_GotoEnd()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}goto end"
help[2] = "Move to the end of the current track."
tmp.command = help[1]
tmp.keywords = "track,end,jump,move"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or string.find(chatvars.command, "jump") or string.find(chatvars.command, "back") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "goto" and chatvars.words[2] == "end") then
if (chatvars.accessLevel > 2) then
botman.faultyChat = false
return true
end
igplayers[chatvars.playerid].trackerReversed = true
igplayers[chatvars.playerid].trackerCount = 1000000000
botman.faultyChat = false
return true
end
end
local function cmd_GotoStart()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}goto start"
help[2] = "Move to the start of the current track."
tmp.command = help[1]
tmp.keywords = "track,start,jump,move"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or string.find(chatvars.command, "jump") or string.find(chatvars.command, "start") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "goto" and chatvars.words[2] == "start") then
if (chatvars.accessLevel > 2) then
botman.faultyChat = false
return true
end
igplayers[chatvars.playerid].trackerReversed = false
igplayers[chatvars.playerid].trackerCount = 0
botman.faultyChat = false
return true
end
end
local function cmd_Jump()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}jump {number of steps}"
help[2] = "Jump forward {number} steps or backwards if given a negative number."
tmp.command = help[1]
tmp.keywords = "track,jump,move"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or string.find(chatvars.command, "jump") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "jump" and chatvars.number ~= nil) then
if (chatvars.accessLevel > 2) then
botman.faultyChat = false
return true
end
igplayers[chatvars.playerid].trackerCount = igplayers[chatvars.playerid].trackerCount + chatvars.number
igplayers[chatvars.playerid].trackerStopped = false
igplayers[chatvars.playerid].trackerStop = true
botman.faultyChat = false
return true
end
end
local function cmd_ResumeTracking()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}go"
help[2] = "Resume tracking."
tmp.command = help[1]
tmp.keywords = "track,go,cont"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "go" and chatvars.words[2] == nil) then
if (chatvars.accessLevel > 2) then
botman.faultyChat = false
return true
end
igplayers[chatvars.playerid].trackerStopped = false
botman.faultyChat = false
return true
end
end
local function cmd_SetSpeed()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}speed {number}"
help[2] = "The default pause between each tracked step is 3 seconds. Change it to any number of seconds from 1 to whatever."
tmp.command = help[1]
tmp.keywords = "track,step,speed"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "speed" and chatvars.number ~= nil) then
if (chatvars.accessLevel > 2) then
botman.faultyChat = false
return true
end
igplayers[chatvars.playerid].trackerSpeed = chatvars.number
botman.faultyChat = false
return true
end
end
local function cmd_SkipSteps()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}skip {number of steps}"
help[2] = "Skip {number} of steps. Instead of tracking each recorded step, you will skip {number} steps for faster but less precise tracking."
tmp.command = help[1]
tmp.keywords = "track,step,speed,skip"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "skip" and chatvars.number ~= nil) then
if (chatvars.accessLevel > 2) then
botman.faultyChat = false
return true
end
igplayers[chatvars.playerid].trackerSkip = chatvars.number
botman.faultyChat = false
return true
end
end
local function cmd_Stop()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}stop"
help[2] = "Stop tracking. Resume it with " .. server.commandPrefix .. "go"
tmp.command = help[1]
tmp.keywords = "track,stop"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "stop" or chatvars.words[1] == "sotp" or chatvars.words[1] == "s") and chatvars.words[2] == nil and chatvars.playerid ~= 0 then
if (chatvars.accessLevel > 2) then
botman.faultyChat = false
return true
end
r = rand(50)
if r == 49 then
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]HAMMER TIME![-]")
end
if igplayers[chatvars.playerid].trackerStopped ~= nil then
if not igplayers[chatvars.playerid].trackerStopped then
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Tracking stopped.[-]")
end
end
if igplayers[chatvars.playerid].following ~= nil then
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You have stopped following " .. players[igplayers[chatvars.playerid].following].name .. ".[-]")
end
if igplayers[chatvars.playerid].location ~= nil then
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You have stopped recording random spawn points.[-]")
end
igplayers[chatvars.playerid].trackerStopped = true
igplayers[chatvars.playerid].following = nil
igplayers[chatvars.playerid].location = nil
botman.faultyChat = false
return true
end
end
local function cmd_StopTracking()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}stop tracking"
help[2] = "Stops tracking and clears the tracking data from memory. This happens when you exit the server anyway so you don't have to do this."
tmp.command = help[1]
tmp.keywords = "track,stop"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "stop" and chatvars.words[2] == "tracking") then
if (chatvars.accessLevel > 2) then
botman.faultyChat = false
return true
end
igplayers[chatvars.playerid].trackerStopped = true
conn:execute("DELETE FROM memTracker WHERE admin = " .. chatvars.playerid)
igplayers[chatvars.playerid].trackerCount = nil
botman.faultyChat = false
return true
end
end
local function cmd_TrackPlayer()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}track {player name} session {number} (session is optional and defaults to the latest)\n"
help[1] = " {#}track {player name} session {number} range {distance}\n"
help[1] = help[1] .. " {#}next (track the next session)\n"
help[1] = help[1] .. " {#}last (track the previous session)"
help[2] = "Track the movements of a player. If a session is given, you will track their movements from that session.\n"
help[2] = help[2] .. "If you add the word hax, hacking or cheat the bot will only send you to coordinates that were flagged as flying or clipping."
tmp.command = help[1]
tmp.keywords = "track,next,last"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if ((chatvars.words[1] == "track") or (chatvars.words[1] == "next") or (chatvars.words[1] == "last")) then
if (chatvars.accessLevel > 2) then
message(string.format("pm %s [%s]" .. restrictedCommandMessage(), chatvars.playerid, server.chatColour))
botman.faultyChat = false
return true
end
tmp = {}
conn:execute("DELETE FROM memTracker WHERE admin = " .. chatvars.playerid)
igplayers[chatvars.playerid].trackerStopped = false
igplayers[chatvars.playerid].trackerReversed = false
if igplayers[chatvars.playerid].trackerSpeed == nil then
igplayers[chatvars.playerid].trackerSpeed = 4
end
if igplayers[chatvars.playerid].trackerSkip == nil then
igplayers[chatvars.playerid].trackerSkip = 1
end
if (chatvars.words[1] ~= "next") and (chatvars.words[1] ~= "last") then
igplayers[chatvars.playerid].trackerCountdown = igplayers[chatvars.playerid].trackerSpeed
igplayers[chatvars.playerid].trackerCount = 0
igplayers[chatvars.playerid].trackerSteam = 0
igplayers[chatvars.playerid].trackerSession = 0
else
if (chatvars.words[1] == "next") then
igplayers[chatvars.playerid].trackerSession = igplayers[chatvars.playerid].trackerSession + 1
igplayers[chatvars.playerid].trackerCount = 0
igplayers[chatvars.playerid].trackerReversed = false
end
if (chatvars.words[1] == "last") then
igplayers[chatvars.playerid].trackerSession = igplayers[chatvars.playerid].trackerSession - 1
igplayers[chatvars.playerid].trackerCount = 1000000000
igplayers[chatvars.playerid].trackerReversed = true
end
tmp.id = igplayers[chatvars.playerid].trackerSteam
tmp.session = igplayers[chatvars.playerid].trackerSession
end
for i=1,chatvars.wordCount,1 do
if chatvars.words[i] == "track" then
tmp.name = chatvars.words[i+1]
tmp.id = LookupPlayer(tmp.name)
if tmp.id == 0 then
tmp.id = LookupArchivedPlayer(tmp.name)
if not (tmp.id == 0) then
if (chatvars.playername ~= "Server") then
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Player " .. playersArchived[tmp.id].name .. " was archived. There won't be any tracking data for them.[-]")
else
irc_chat(chatvars.ircAlias, "Player " .. playersArchived[tmp.id].name .. " was archived. There won't be any tracking data for them.")
end
botman.faultyChat = false
return true
end
end
if tmp.id ~= 0 then
tmp.session = players[tmp.id].sessionCount
igplayers[chatvars.playerid].trackerSession = players[tmp.id].sessionCount
igplayers[chatvars.playerid].trackerSteam = tmp.id
igplayers[chatvars.playerid].trackerLastSession = true
end
end
if chatvars.words[i] == "session" then
tmp.session = chatvars.words[i+1]
igplayers[chatvars.playerid].trackerSession = tmp.session
if tonumber(tmp.session) == players[tmp.id].sessionCount then
igplayers[chatvars.playerid].trackerLastSession = true
else
igplayers[chatvars.playerid].trackerLastSession = false
end
end
if chatvars.words[i] == "here" then
tmp.x = chatvars.intX
tmp.z = chatvars.intZ
tmp.dist = 200
end
if chatvars.words[i] == "range" or chatvars.words[i] == "dist" or chatvars.words[i] == "distance" then
tmp.x = chatvars.intX
tmp.z = chatvars.intZ
tmp.dist = chatvars.words[i+1]
end
if chatvars.words[i] == "hax" or chatvars.words[i] == "hack" or chatvars.words[i] == "hacking" or chatvars.words[i] == "cheat" then
filter = " and flag like '%F%'"
end
end
if tmp.id ~= 0 then
if tmp.dist ~= nil then
conn:execute("INSERT into memTracker (SELECT trackerID, " .. chatvars.playerid .. " AS admin, steam, timestamp, x, y, z, SESSION , flag from tracker where steam = " .. tmp.id .. " and session = " .. tmp.session .. " and abs(x - " .. tmp.x .. ") <= " .. tmp.dist .. " AND abs(z - " .. tmp.z .. ") <= " .. tmp.dist .. " " .. filter .. ")")
else
conn:execute("INSERT into memTracker (SELECT trackerID, " .. chatvars.playerid .. " AS admin, steam, timestamp, x, y, z, SESSION , flag from tracker where steam = " .. tmp.id .. " and session = " .. tmp.session .. " " .. filter .. ")")
end
else
if tmp.name == nil then
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]Player name, game id, or steam id required.[-]")
else
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]No player or steam id matched " .. tmp.name .. "[-]")
end
end
botman.faultyChat = false
return true
end
end
local function cmd_VisitNextBase()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}nb"
help[2] = "Visit the next base in the tracker."
tmp.command = help[1]
tmp.keywords = "track,next,base,visit"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "nb" and chatvars.words[2] == nil) then
if (chatvars.accessLevel > 2) then
message(string.format("pm %s [%s]" .. restrictedCommandMessage(), chatvars.playerid, server.chatColour))
botman.faultyChat = false
return true
end
igplayers[chatvars.playerid].trackerID = igplayers[chatvars.playerid].trackerID + 1
cursor,errorString = conn:execute("select * from memTracker where admin = " .. chatvars.playerid .. " and trackerID > " .. igplayers[chatvars.playerid].trackerID .. " order by trackerID limit 1")
row = cursor:fetch({}, "a")
if row then
sendCommand("tele " .. chatvars.playerid .. " " .. row.x .. " " .. row.y .. " " .. row.z)
igplayers[chatvars.playerid].atBase = row.steam
igplayers[chatvars.playerid].trackerID = row.trackerID
if row.flag == "base1" then
igplayers[chatvars.playerid].whichBase = 1
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]This is base one of " .. players[igplayers[chatvars.playerid].atBase].name .. ".[-]")
else
igplayers[chatvars.playerid].whichBase = 2
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]This is base two of " .. players[igplayers[chatvars.playerid].atBase].name .. ".[-]")
end
end
botman.faultyChat = false
return true
end
end
local function cmd_VisitPreviousBase()
if (chatvars.showHelp and not skipHelp) or botman.registerHelp then
help = {}
help[1] = " {#}pb"
help[2] = "Visit the previous base in the tracker."
tmp.command = help[1]
tmp.keywords = "track,prev,base,visit"
tmp.accessLevel = 2
tmp.description = help[2]
tmp.notes = ""
tmp.ingameOnly = 1
help[3] = helpCommandRestrictions(tmp)
if botman.registerHelp then
registerHelp(tmp)
end
if string.find(chatvars.command, "track") or chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, help[1])
if not shortHelp then
irc_chat(chatvars.ircAlias, help[2])
irc_chat(chatvars.ircAlias, help[3])
irc_chat(chatvars.ircAlias, ".")
end
chatvars.helpRead = true
end
end
if (chatvars.words[1] == "pb" and chatvars.words[2] == nil) then
if (chatvars.accessLevel > 2) then
message(string.format("pm %s [%s]" .. restrictedCommandMessage(), chatvars.playerid, server.chatColour))
botman.faultyChat = false
return true
end
igplayers[chatvars.playerid].trackerID = igplayers[chatvars.playerid].trackerID - 1
cursor,errorString = conn:execute("select * from memTracker where admin = " .. chatvars.playerid .. " and trackerID < " .. igplayers[chatvars.playerid].trackerID .. " order by trackerID desc limit 1")
row = cursor:fetch({}, "a")
if row then
sendCommand("tele " .. chatvars.playerid .. " " .. row.x .. " " .. row.y .. " " .. row.z)
igplayers[chatvars.playerid].atBase = row.steam
igplayers[chatvars.playerid].trackerID = row.trackerID
if row.flag == "base1" then
igplayers[chatvars.playerid].whichBase = 1
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]This is base one of " .. players[igplayers[chatvars.playerid].atBase].name .. ".[-]")
else
igplayers[chatvars.playerid].whichBase = 2
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]This is base two of " .. players[igplayers[chatvars.playerid].atBase].name .. ".[-]")
end
else
message("pm " .. chatvars.playerid .. " [" .. server.chatColour .. "]You have reached the first base.[-]")
end
botman.faultyChat = false
return true
end
end
-- ################## End of command functions ##################
if botman.registerHelp then
irc_chat(chatvars.ircAlias, "==== Registering help - tracker commands ====")
if debug then dbug("Registering help - tracker commands") end
tmp.topicDescription = "All player movement is recorded every 3 seconds.\n"
tmp.topicDescription = tmp.topicDescription .. "The tracker allows admins to follow a player's movements now or in the past so long as there is tracking data recorded.\n"
tmp.topicDescription = tmp.topicDescription .. "The tracker can also be used to visit every recorded player base using special commands.\n"
tmp.topicDescription = tmp.topicDescription .. "The tracker runs slowly by default to give admins time to look around and time to command the tracker. Several controls are available to change speed, direction and more."
cursor,errorString = conn:execute("SELECT * FROM helpTopics WHERE topic = 'tracker'")
rows = cursor:numrows()
if rows == 0 then
cursor,errorString = conn:execute("SHOW TABLE STATUS LIKE 'helpTopics'")
row = cursor:fetch(row, "a")
tmp.topicID = row.Auto_increment
conn:execute("INSERT INTO helpTopics (topic, description) VALUES ('tracker', '" .. escape(tmp.topicDescription) .. "')")
end
end
-- don't proceed if there is no leading slash
if (string.sub(chatvars.command, 1, 1) ~= server.commandPrefix and server.commandPrefix ~= "") then
botman.faultyChat = false
return false
end
if chatvars.showHelp then
if chatvars.words[3] then
if not string.find(chatvars.words[3], "track") then
skipHelp = true
end
end
if chatvars.words[1] == "help" then
skipHelp = false
end
if chatvars.words[1] == "list" then
shortHelp = true
end
end
if chatvars.showHelp and not skipHelp and chatvars.words[1] ~= "help" then
irc_chat(chatvars.ircAlias, ".")
irc_chat(chatvars.ircAlias, "Tracker Commands:")
irc_chat(chatvars.ircAlias, "=================")
irc_chat(chatvars.ircAlias, ".")
end
if chatvars.showHelpSections then
irc_chat(chatvars.ircAlias, "tracker")
end
if debug then dbug("debug tracker end of remote commands") end
-- ################### do not run remote commands beyond this point unless displaying command help ################
if chatvars.playerid == 0 and not (chatvars.showHelp or botman.registerHelp) then
botman.faultyChat = false
return false
end
-- ################### do not run remote commands beyond this point unless displaying command help ################
-- ################### Staff only beyond this point ################
-- Don't proceed if this is a player. Server and staff only here.
if (chatvars.playername ~= "Server") then
if (chatvars.accessLevel > 2) then
botman.faultyChat = false
return false
end
end
-- ##################################################################
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_TrackPlayer()
if result then
if debug then dbug("debug cmd_TrackPlayer triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_SkipSteps()
if result then
if debug then dbug("debug cmd_SkipSteps triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_SetSpeed()
if result then
if debug then dbug("debug cmd_SetSpeed triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_Jump()
if result then
if debug then dbug("debug cmd_Jump triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_GotoStart()
if result then
if debug then dbug("debug cmd_GotoStart triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_GotoEnd()
if result then
if debug then dbug("debug cmd_GotoEnd triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_GoBack()
if result then
if debug then dbug("debug cmd_GoBack triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_Stop()
if result then
if debug then dbug("debug cmd_Stop triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_ResumeTracking()
if result then
if debug then dbug("debug cmd_ResumeTracking triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_StopTracking()
if result then
if debug then dbug("debug cmd_StopTracking triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_CheckBases()
if result then
if debug then dbug("debug cmd_CheckBases triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_VisitNextBase()
if result then
if debug then dbug("debug cmd_VisitNextBase triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_VisitPreviousBase()
if result then
if debug then dbug("debug cmd_VisitPreviousBase triggered") end
return result
end
if (debug) then dbug("debug tracker line " .. debugger.getinfo(1).currentline) end
result = cmd_DeleteBase()
if result then
if debug then dbug("debug cmd_DeleteBase triggered") end
return result
end
if botman.registerHelp then
irc_chat(chatvars.ircAlias, "**** Tracker commands help registered ****")
if debug then dbug("Tracker commands help registered") end
topicID = topicID + 1
end
if debug then dbug("debug tracker end") end
-- can't touch dis
if true then
return result
end
end
| gpl-3.0 |
nasomi/darkstar | scripts/globals/items/magma_steak.lua | 36 | 1537 | -----------------------------------------
-- ID: 6071
-- Item: Magma Steak
-- Food Effect: 180 Min, All Races
-----------------------------------------
-- Strength +8
-- Attack +23% Cap 180
-- Ranged Attack +23% Cap 180
-- Vermin Killer +5
-----------------------------------------
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,10800,6071);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_STR, 8);
target:addMod(MOD_FOOD_ATTP, 23);
target:addMod(MOD_FOOD_ATT_CAP, 180);
target:addMod(MOD_FOOD_RATTP, 23);
target:addMod(MOD_FOOD_RATT_CAP, 180);
target:addMod(MOD_VERMIN_KILLER, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_STR, 8);
target:delMod(MOD_FOOD_ATTP, 23);
target:delMod(MOD_FOOD_ATT_CAP, 180);
target:delMod(MOD_FOOD_RATTP, 23);
target:delMod(MOD_FOOD_RATT_CAP, 180);
target:delMod(MOD_VERMIN_KILLER, 5);
end;
| gpl-3.0 |
shangjiyu/luci-with-extra | applications/luci-app-multiwan/luasrc/model/cbi/multiwan/multiwan.lua | 147 | 5025 | require("luci.tools.webadmin")
m = Map("multiwan", translate("Multi-WAN"),
translate("Multi-WAN allows for the use of multiple uplinks for load balancing and failover."))
s = m:section(NamedSection, "config", "multiwan", "")
e = s:option(Flag, "enabled", translate("Enable"))
e.rmempty = false
e.default = e.enabled
function e.write(self, section, value)
if value == "0" then
os.execute("/etc/init.d/multiwan stop")
else
os.execute("/etc/init.d/multiwan enable")
end
Flag.write(self, section, value)
end
s = m:section(TypedSection, "interface", translate("WAN Interfaces"),
translate("Health Monitor detects and corrects network changes and failed connections."))
s.addremove = true
weight = s:option(ListValue, "weight", translate("Load Balancer Distribution"))
weight:value("10", "10")
weight:value("9", "9")
weight:value("8", "8")
weight:value("7", "7")
weight:value("6", "6")
weight:value("5", "5")
weight:value("4", "4")
weight:value("3", "3")
weight:value("2", "2")
weight:value("1", "1")
weight:value("disable", translate("None"))
weight.default = "10"
weight.optional = false
weight.rmempty = false
interval = s:option(ListValue, "health_interval", translate("Health Monitor Interval"))
interval:value("disable", translate("Disable"))
interval:value("5", "5 sec.")
interval:value("10", "10 sec.")
interval:value("20", "20 sec.")
interval:value("30", "30 sec.")
interval:value("60", "60 sec.")
interval:value("120", "120 sec.")
interval.default = "10"
interval.optional = false
interval.rmempty = false
icmp_hosts = s:option(Value, "icmp_hosts", translate("Health Monitor ICMP Host(s)"))
icmp_hosts:value("disable", translate("Disable"))
icmp_hosts:value("dns", "DNS Server(s)")
icmp_hosts:value("gateway", "WAN Gateway")
icmp_hosts.default = "dns"
icmp_hosts.optional = false
icmp_hosts.rmempty = false
timeout = s:option(ListValue, "timeout", translate("Health Monitor ICMP Timeout"))
timeout:value("1", "1 sec.")
timeout:value("2", "2 sec.")
timeout:value("3", "3 sec.")
timeout:value("4", "4 sec.")
timeout:value("5", "5 sec.")
timeout:value("10", "10 sec.")
timeout.default = "3"
timeout.optional = false
timeout.rmempty = false
fail = s:option(ListValue, "health_fail_retries", translate("Attempts Before WAN Failover"))
fail:value("1", "1")
fail:value("3", "3")
fail:value("5", "5")
fail:value("10", "10")
fail:value("15", "15")
fail:value("20", "20")
fail.default = "3"
fail.optional = false
fail.rmempty = false
recovery = s:option(ListValue, "health_recovery_retries", translate("Attempts Before WAN Recovery"))
recovery:value("1", "1")
recovery:value("3", "3")
recovery:value("5", "5")
recovery:value("10", "10")
recovery:value("15", "15")
recovery:value("20", "20")
recovery.default = "5"
recovery.optional = false
recovery.rmempty = false
failover_to = s:option(ListValue, "failover_to", translate("Failover Traffic Destination"))
failover_to:value("disable", translate("None"))
luci.tools.webadmin.cbi_add_networks(failover_to)
failover_to:value("fastbalancer", translate("Load Balancer(Performance)"))
failover_to:value("balancer", translate("Load Balancer(Compatibility)"))
failover_to.default = "balancer"
failover_to.optional = false
failover_to.rmempty = false
dns = s:option(Value, "dns", translate("DNS Server(s)"))
dns:value("auto", translate("Auto"))
dns.default = "auto"
dns.optional = false
dns.rmempty = true
s = m:section(TypedSection, "mwanfw", translate("Multi-WAN Traffic Rules"),
translate("Configure rules for directing outbound traffic through specified WAN Uplinks."))
s.template = "cbi/tblsection"
s.anonymous = true
s.addremove = true
src = s:option(Value, "src", translate("Source Address"))
src.rmempty = true
src:value("", translate("all"))
luci.tools.webadmin.cbi_add_knownips(src)
dst = s:option(Value, "dst", translate("Destination Address"))
dst.rmempty = true
dst:value("", translate("all"))
luci.tools.webadmin.cbi_add_knownips(dst)
proto = s:option(Value, "proto", translate("Protocol"))
proto:value("", translate("all"))
proto:value("tcp", "TCP")
proto:value("udp", "UDP")
proto:value("icmp", "ICMP")
proto.rmempty = true
ports = s:option(Value, "ports", translate("Ports"))
ports.rmempty = true
ports:value("", translate("all", translate("all")))
wanrule = s:option(ListValue, "wanrule", translate("WAN Uplink"))
luci.tools.webadmin.cbi_add_networks(wanrule)
wanrule:value("fastbalancer", translate("Load Balancer(Performance)"))
wanrule:value("balancer", translate("Load Balancer(Compatibility)"))
wanrule.default = "fastbalancer"
wanrule.optional = false
wanrule.rmempty = false
s = m:section(NamedSection, "config", "", "")
s.addremove = false
default_route = s:option(ListValue, "default_route", translate("Default Route"))
luci.tools.webadmin.cbi_add_networks(default_route)
default_route:value("fastbalancer", translate("Load Balancer(Performance)"))
default_route:value("balancer", translate("Load Balancer(Compatibility)"))
default_route.default = "balancer"
default_route.optional = false
default_route.rmempty = false
return m
| apache-2.0 |
amirik22/i4bot | plugins/remind.lua | 279 | 1873 | local filename='data/remind.lua'
local cronned = load_from_file(filename)
local function save_cron(msg, text,date)
local origin = get_receiver(msg)
if not cronned[date] then
cronned[date] = {}
end
local arr = { origin, text } ;
table.insert(cronned[date], arr)
serialize_to_file(cronned, filename)
return 'Saved!'
end
local function delete_cron(date)
for k,v in pairs(cronned) do
if k == date then
cronned[k]=nil
end
end
serialize_to_file(cronned, filename)
end
local function cron()
for date, values in pairs(cronned) do
if date < os.time() then --time's up
send_msg(values[1][1], "Time's up:"..values[1][2], ok_cb, false)
delete_cron(date) --TODO: Maybe check for something else? Like user
end
end
end
local function actually_run(msg, delay,text)
if (not delay or not text) then
return "Usage: !remind [delay: 2h3m1s] text"
end
save_cron(msg, text,delay)
return "I'll remind you on " .. os.date("%x at %H:%M:%S",delay) .. " about '" .. text .. "'"
end
local function run(msg, matches)
local sum = 0
for i = 1, #matches-1 do
local b,_ = string.gsub(matches[i],"[a-zA-Z]","")
if string.find(matches[i], "s") then
sum=sum+b
end
if string.find(matches[i], "m") then
sum=sum+b*60
end
if string.find(matches[i], "h") then
sum=sum+b*3600
end
end
local date=sum+os.time()
local text = matches[#matches]
local text = actually_run(msg, date, text)
return text
end
return {
description = "remind plugin",
usage = {
"!remind [delay: 2hms] text",
"!remind [delay: 2h3m] text",
"!remind [delay: 2h3m1s] text"
},
patterns = {
"^!remind ([0-9]+[hmsdHMSD]) (.+)$",
"^!remind ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$",
"^!remind ([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD])([0-9]+[hmsdHMSD]) (.+)$"
},
run = run,
cron = cron
}
| gpl-2.0 |
nasomi/darkstar | scripts/zones/Metalworks/npcs/_6ld.lua | 17 | 1318 | -----------------------------------
-- Area: Metalworks
-- Door: _6ld (President's Office)
-- @pos 92 -19 0.1 237
-----------------------------------
package.loaded["scripts/zones/Metalworks/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Metalworks/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(BASTOK) == XARCABARD_LAND_OF_TRUTHS and player:hasKeyItem(SHADOW_FRAGMENT)) then
player:startEvent(0x025b);
else
player:startEvent(0x025c);
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x025b) then
finishMissionTimeline(player,1,csid,option);
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Cloister_of_Flames/bcnms/sugar-coated_directive.lua | 19 | 1731 | ----------------------------------------
-- Area: Cloister of Flames
-- BCNM: Sugar Coated Directive (ASA-4)
-- @pos -721 0 -598 207
----------------------------------------
package.loaded["scripts/zones/Cloister_of_Flames/TextIDs"] = nil;
----------------------------------------
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Cloister_of_Flames/TextIDs");
----------------------------------------
-- After registering the BCNM via bcnmRegister(bcnmid)
function onBcnmRegister(player,instance)
end;
-- Physically entering the BCNM via bcnmEnter(bcnmid)
function onBcnmEnter(player,instance)
end;
-- Leaving the BCNM by every mean possible, given by the LeaveCode
-- 1=Select Exit on circle
-- 2=Winning the BC
-- 3=Disconnected or warped out
-- 4=Losing the BC
-- via bcnmLeave(1) or bcnmLeave(2). LeaveCodes 3 and 4 are called
-- from the core when a player disconnects or the time limit is up, etc
function onBcnmLeave(player,instance,leavecode)
-- print("leave code "..leavecode);
if (leavecode == 2) then -- play end CS. Need time and battle id for record keeping + storage
if (player:hasCompleteQuest(ASA,SUGAR_COATED_DIRECTIVE)) then
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,1);
else
player:startEvent(0x7d01,1,1,1,instance:getTimeInside(),1,3,0);
end
elseif (leavecode == 4) then
player:startEvent(0x7d02);
end
end;
function onEventUpdate(player,csid,option)
-- print("bc update csid "..csid.." and option "..option);
end;
function onEventFinish(player,csid,option)
-- print("bc finish csid "..csid.." and option "..option);
if (csid == 0x7d01) then
player:addExp(400);
player:setVar("ASA4_Scarlet","1");
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Inner_Horutoto_Ruins/npcs/_5cs.lua | 17 | 2441 | -----------------------------------
-- Area: Inner Horutoto Ruins
-- NPC: _5cs (Magical Gizmo) #4
-- Involved In Mission: The Horutoto Ruins Experiment
-----------------------------------
package.loaded["scripts/zones/Inner_Horutoto_Ruins/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Inner_Horutoto_Ruins/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
-- The Magical Gizmo Number, this number will be compared to the random
-- value created by the mission The Horutoto Ruins Experiment, when you
-- reach the Gizmo Door and have the cutscene
local magical_gizmo_no = 4; -- of the 6
-- Check if we are on Windurst Mission 1-1
if (player:getCurrentMission(WINDURST) == THE_HORUTOTO_RUINS_EXPERIMENT and player:getVar("MissionStatus") == 2) then
-- Check if we found the correct Magical Gizmo or not
if (player:getVar("MissionStatus_rv") == magical_gizmo_no) then
player:startEvent(0x0036);
else
if (player:getVar("MissionStatus_op4") == 2) then
-- We've already examined this
player:messageSpecial(EXAMINED_RECEPTACLE);
else
-- Opened the wrong one
player:startEvent(0x0037);
end
end
end
return 1;
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
-- If we just finished the cutscene for Windurst Mission 1-1
-- The cutscene that we opened the correct Magical Gizmo
if (csid == 0x0036) then
player:setVar("MissionStatus",3);
player:setVar("MissionStatus_rv", 0);
player:addKeyItem(CRACKED_MANA_ORBS);
player:messageSpecial(KEYITEM_OBTAINED,CRACKED_MANA_ORBS);
elseif (csid == 0x0037) then
-- Opened the wrong one
player:setVar("MissionStatus_op4", 2);
-- Give the message that thsi orb is not broken
player:messageSpecial(NOT_BROKEN_ORB);
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/Southern_San_dOria/npcs/Lusiane.lua | 36 | 1830 | -----------------------------------
-- Area: Southern San d'Oria
-- NPC: Lusiane
-- Standard Merchant NPC
-----------------------------------
package.loaded["scripts/zones/Southern_San_dOria/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/shop");
require("scripts/globals/quests");
require("scripts/zones/Southern_San_dOria/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
-- "Flyers for Regine" conditional script
FlyerForRegine = player:getQuestStatus(SANDORIA,FLYERS_FOR_REGINE);
if (FlyerForRegine == 1) then
count = trade:getItemCount();
MagicFlyer = trade:hasItemQty(532,1);
if (MagicFlyer == true and count == 1) then
player:messageSpecial(FLYER_REFUSED);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:showText(npc,LUSIANE_SHOP_DIALOG);
stock = {0x43ed,496,1, -- Bamboo Fishing Rod
0x43f3,9,2, -- Lugworm
0x43ee,217,2, -- Yew Fishing Rod
0x43f4,3,3, -- Little Worm
0x13cc,110,3, -- Scroll of Light Threnoldy
0x13ca,1265,3, -- Scroll of Lightning Threnoldy
0x43ef,66,3} -- Willow Fishing Rod
showNationShop(player, SANDORIA, 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 |
TeamHypersomnia/Augmentations | hypersomnia/content/official/gfx/resistance_torso_heavy_walk_4.meta.lua | 2 | 2771 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 0.40000000596046448,
amplification = 100,
light_colors = {
"223 113 38 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
chamber = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
chamber_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {},
original_poly = {}
},
torso = {
back = {
pos = {
x = -14,
y = -10
},
rotation = 29.744880676269531
},
head = {
pos = {
x = -1,
y = -2
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 5,
y = 29
},
rotation = -48.907588958740234
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_shoulder = {
pos = {
x = -3,
y = 19
},
rotation = -160
},
shoulder = {
pos = {
x = 12,
y = -17
},
rotation = -164
},
strafe_facing_offset = 0
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
thesabbir/luci | applications/luci-app-fwknopd/luasrc/model/cbi/fwknopd.lua | 45 | 3678 | -- Copyright 2015 Jonathan Bennett <jbennett@incomsystems.biz>
-- Licensed to the public under the GNU General Public License v2.
m = Map("fwknopd", translate("Firewall Knock Operator"))
s = m:section(TypedSection, "global", translate("Enable Uci/Luci control")) -- Set uci control on or off
s.anonymous=true
s:option(Flag, "uci_enabled", translate("Enable config overwrite"), translate("When unchecked, the config files in /etc/fwknopd will be used as is, ignoring any settings here."))
qr = s:option(DummyValue, "note0", "dummy")
qr.template = "fwknopd-qr"
qr:depends("uci_enabled", "1")
s = m:section(TypedSection, "access", translate("access.conf stanzas")) -- set the access.conf settings
s.anonymous=true
s.addremove=true
s.dynamic=true
s:option(Value, "SOURCE", "SOURCE", translate("Use ANY for any source ip"))
k1 = s:option(Value, "KEY", "KEY", translate("Define the symmetric key used for decrypting an incoming SPA packet that is encrypted by the fwknop client with Rijndael."))
k1:depends("keytype", translate("Normal Key"))
k2 = s:option(Value, "KEY_BASE64", "KEY_BASE64", translate("Define the symmetric key used for decrypting an incoming SPA \
packet that is encrypted by the fwknop client with Rijndael."))
k2:depends("keytype", translate("Base 64 key"))
l1 = s:option(ListValue, "keytype", "Key type")
l1:value("Normal Key", "Normal Key")
l1:value("Base 64 key", "Base 64 key")
k3 = s:option(Value, "HMAC_KEY", "HMAC_KEY", "The hmac key")
k3:depends("hkeytype", "Normal Key")
k4 = s:option(Value, "HMAC_KEY_BASE64", "HMAC_KEY_BASE64", translate("The base64 hmac key"))
k4:depends("hkeytype", "Base 64 key")
l2 = s:option(ListValue, "hkeytype", "HMAC Key type")
l2:value("Normal Key", "Normal Key")
l2:value("Base 64 key", "Base 64 key")
s:option(Value, "OPEN_PORTS", "OPEN_PORTS", translate("Define a set of ports and protocols (tcp or udp) that will be opened if a valid knock sequence is seen. \
If this entry is not set, fwknopd will attempt to honor any proto/port request specified in the SPA data \
(unless of it matches any “RESTRICT_PORTS” entries). Multiple entries are comma-separated."))
s:option(Value, "FW_ACCESS_TIMEOUT", "FW_ACCESS_TIMEOUT", translate("Define the length of time access will be granted by fwknopd through the firewall after a \
valid knock sequence from a source IP address. If “FW_ACCESS_TIMEOUT” is not set then the default \
timeout of 30 seconds will automatically be set."))
s:option(Value, "REQUIRE_SOURCE_ADDRESS", "REQUIRE_SOURCE_ADDRESS", translate("Force all SPA packets to contain a real IP address within the encrypted data. \
This makes it impossible to use the -s command line argument on the fwknop client command line, so either -R \
has to be used to automatically resolve the external address (if the client behind a NAT) or the client must \
know the external IP and set it via the -a argument."))
s:option(DummyValue, "note1", translate("Enter custom access.conf variables below:"))
s = m:section(TypedSection, "config", translate("fwknopd.conf config options"))
s.anonymous=true
s.dynamic=true
s:option(Value, "MAX_SPA_PACKET_AGE", "MAX_SPA_PACKET_AGE", translate("Maximum age in seconds that an SPA packet will be accepted. defaults to 120 seconds"))
s:option(Value, "PCAP_INTF", "PCAP_INTF", translate("Specify the ethernet interface on which fwknopd will sniff packets."))
s:option(Value, "ENABLE_IPT_FORWARDING", "ENABLE_IPT_FORWARDING", translate("Allow SPA clients to request access to services through an iptables firewall instead of just to it."))
s:option(DummyValue, "note2", translate("Enter custom fwknopd.conf variables below:"))
return m
| apache-2.0 |
shakfu/start-vm | config/base/awesome/vicious/contrib/openweather.lua | 11 | 3426 | ---------------------------------------------------
-- Licensed under the GNU General Public License v2
-- * (c) 2013, NormalRa <normalrawr gmail com>
---------------------------------------------------
-- {{{ Grab environment
local tonumber = tonumber
local io = { popen = io.popen }
local setmetatable = setmetatable
local string = { match = string.match }
local math = {
ceil = math.ceil,
floor = math.floor
}
-- }}}
-- Openweather: provides weather information for a requested station
-- vicious.widgets.openweather
local openweather = {}
-- Initialize function tables
local _wdirs = { "N", "NE", "E", "SE", "S", "SW", "W", "NW", "N" }
local _wdata = {
["{city}"] = "N/A",
["{wind deg}"] = "N/A",
["{wind aim}"] = "N/A",
["{wind mps}"] = "N/A",
["{wind kmh}"] = "N/A",
["{sky}"] = "N/A",
["{weather}"] = "N/A",
["{temp c}"] = "N/A",
["{humid}"] = "N/A",
["{press}"] = "N/A"
}
-- {{{ Openweather widget type
local function worker(format, warg)
if not warg then return end
-- Get weather forceast using the city ID code, from:
-- * OpenWeatherMap.org
local openweather = "http://api.openweathermap.org/data/2.5/weather?id="..warg.."&mode=json&units=metric"
local f = io.popen("curl --connect-timeout 1 -fsm 3 '"..openweather.."'")
local ws = f:read("*all")
f:close()
-- Check if there was a timeout or a problem with the station
if ws == nil then return _wdata end
_wdata["{city}"] = -- City name
string.match(ws, '"name":"([%a%s%-]+)"') or _wdata["{city}"]
_wdata["{wind deg}"] = -- Wind degrees
string.match(ws, '"deg":([%d]+)') or _wdata["{wind deg}"]
_wdata["{wind mps}"] = -- Wind speed in meters per second
string.match(ws, '"speed":([%d%.]+)') or _wdata["{wind mps}"]
_wdata["{sky}"] = -- Sky conditions
string.match(ws, '"main":"([%a]+)"') or _wdata["{sky}"]
_wdata["{weather}"] = -- Weather description
string.match(ws, '"description":"([%a%s]+)"') or _wdata["{weather}"]
_wdata["{temp c}"] = -- Temperature in celsius
string.match(ws, '"temp":([%-]?[%d%.]+)') or _wdata["{temp c}"]
_wdata["{humid}"] = -- Relative humidity in percent
string.match(ws, '"humidity":([%d]+)') or _wdata["{humid}"]
_wdata["{press}"] = -- Pressure in hPa
string.match(ws, '"pressure":([%d%.]+)') or _wdata["{press}"]
-- Wind speed in km/h
if _wdata["{wind mps}"] ~= "N/A" then
_wdata["{wind mps}"] = math.floor(tonumber(_wdata["{wind mps}"]) + .5)
_wdata["{wind kmh}"] = math.ceil(_wdata["{wind mps}"] * 3.6)
end -- Temperature in °C
if _wdata["{temp c}"] ~= "N/A" then
_wdata["{temp c}"] = math.floor(tonumber(_wdata["{temp c}"]) + .5)
end -- Calculate wind direction
if _wdata["{wind deg}"] ~= "N/A" then
_wdata["{wind deg}"] = tonumber(_wdata["{wind deg}"])
-- Lua tables start at [1]
if (_wdata["{wind deg}"] / 45)%1 == 0 then
_wdata["{wind aim}"] = _wdirs[_wdata["{wind deg}"] / 45 + 1]
else
_wdata["{wind aim}"] =
_wdirs[math.ceil(_wdata["{wind deg}"] / 45) + 1]..
_wdirs[math.floor(_wdata["{wind deg}"] / 45) + 1]
end
end
return _wdata
end
-- }}}
return setmetatable(openweather, { __call = function(_, ...) return worker(...) end })
| mit |
phcosta29/rstats | lua/Rserve.lua | 1 | 15953 | local vstruct = require("vstruct")
local socket = require("socket")
local tcp = assert(socket.tcp())
local QAP1_HEADER_FORMAT = "4*u4"
local QAP1_PARAMETER_HEADER_FORMAT = "u1 u3"
local QAP1_SEXP_HEADER_TYPE_FORMAT = "[1 | b2 u6]"
local QAP1_SEXP_HEADER_LEN_FORMAT = "u3"
local function vectorToString(data)
local expressionR = table.concat{"c(", table.concat(data, ","), ")"}
return expressionR
end
local function convertionTypes(data)
local df = {}
forEachElement(data.data.cells[1], function(idx)
if belong(idx, {"FID", "cObj_", "past"}) then
return
end
df[idx] = {}
end)
forEachCell(data.data, function(cell)
forEachElement(df, function(idx, values)
table.insert(values, cell[idx])
end)
end)
df = DataFrame(df)
return df
end
Rserve_ = {
type_ = "Rserve",
--- Execute an R command. It returns an error message or a value.
-- if an entry is of an incompatible type returns with error.
-- @arg data The expression must be passed to R.
-- @usage import ("rstats")
-- R = Rserve{}
-- R:evaluate("x = 4")
evaluate = function(self, data)
if type(data) ~= "string" then
incompatibleTypeError(1, "string", data)
end
local result = luaRserveevaluate(self.host, self.port, "Sys.setenv(LANG='en'); tryCatch({"..data.."}, warning = function(war){return(list(war,0))}, error = function(err){return(list(err,1))})")
if result[1] then
if result[1][1] and type(result[1][1]) ~= "number" and type(result[1][1]) ~= "string" and type(result[1][1]) ~= "boolean" then
if result[1][1][3] and type(result[1][1][3]) ~= "number" and type(result[1][1][3]) ~= "string" and type(result[1][1][3]) ~= "boolean" then
if result[1][1][3][1] == 1 then
customError("[Rserve] Error: "..result[1][1][2][1][1])
elseif result[1][1][3][1] == 0 then
customWarning("[Rserve] Warning: "..result[1][1][2][1][1])
end
end
end
end
while type(result) == "table" and #result == 1 do
result = result[1]
end
return result
end,
--- It returns the arithmetic mean of a vector of values computed in R.
-- if an entry is of an incompatible type returns with error.
-- @arg data a table of numbers.
-- @usage import ("rstats")
-- R = Rserve{}
-- R:mean{1,2,3,4,5,6,7,8,9,10} -- 5.5
mean = function(self, data)
if type(data) ~= "table" then
incompatibleTypeError(1, "table", data)
end
local expressionR = table.concat{"mean(", vectorToString(data), ")"}
local result = self:evaluate(expressionR)
return result
end,
--- It returns the standard deviation of a vector of values computed in R.
-- if an entry is of an incompatible type returns with error.
-- @arg data a table of numbers.
-- @usage import ("rstats")
-- R = Rserve{}
-- R:sd{1,2,3,4,5,6,7,8,9,10} -- 3.02765
sd = function(self, data)
if type(data) ~= "table" then
incompatibleTypeError(1, "table", data)
end
local expressionR = table.concat{"sd(", vectorToString(data), ")"}
local result = self:evaluate(expressionR)
return result
end,
--- It returns the linear regression of a table of vectors computed in R.
-- if an entry is of an incompatible type returns with error.
-- @arg data.data a DataFrame or a CellularSpace.
-- @arg data.response Column of DataFrame or CellularSpace.
-- @arg data.terms Columns of DataFrame or CellularSpace.
-- @usage import ("rstats")
-- R = Rserve{}
-- data = CellularSpace{file = filePath("amazonia.shp", "base"),}
-- R:lm{data = data, response = "prodes_10", terms = {"distroads", "protected", "distports"}} -- 22.4337, -8.7823e-05, -11.9502
lm = function(self, data)
if type(data) ~= "table" then
incompatibleTypeError(1, "table", data)
elseif type(data.data) == "CellularSpace" then
data.data = convertionTypes(data)
end
local term = #data.terms
local stri, df, sumTerms
local str = vectorToString(data.data[data.response])
local i = term
while i > 0 do
local t = vectorToString(data.data[data.terms[i]])
if i == term then
stri = table.concat{data.terms[i], " <- ", t, ";"}
else
stri = table.concat{stri, data.terms[i], " <- ", t, ";"}
end
i = i - 1
end
df = table.concat{data.response, " = ", data.response, ", "}
i = term
while i > 0 do
if i > 1 then
df = table.concat{df, data.terms[i], " = ", data.terms[i], ", "}
else
df = table.concat{df, data.terms[i], " = ", data.terms[i], "); result = lm(formula = "}
end
i = i - 1
end
i = 1
while i <= term do
if i == 1 then
sumTerms = table.concat{data.terms[i], " + "}
else
if i == term then
sumTerms = table.concat{sumTerms, data.terms[i]}
else
sumTerms = table.concat{sumTerms, data.terms[i], " + "}
end
end
i = i + 1
end
local result = self:evaluate(table.concat{data.response, " <- ", str, "; ", stri, "; df = data.frame(", df, data.response, " ~ ", sumTerms, ", data = df)"})
local resultTable = {result[2][2][1], result[2][2][2], result[2][2][3]}
return resultTable
end,
--- It returns the principal component analysis of a table of vectors computed in R.
-- if an entry is of an incompatible type returns with error.
-- @arg data.data a DataFrame or a CellularSpace.
-- @arg data.terms Columns of DataFrame or CellularSpace.
-- @usage import ("rstats")
-- R = Rserve{}
-- data = DataFrame{ctl = {4.17, 5.58, 5.18, 6.11, 4.50, 4.61, 5.17, 4.53, 5.33, 5.14},
-- trt = {4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69},
-- weight = {4.17, 5.18, 4.50, 5.17, 5.33, 4.81, 4.41, 5.87, 4.89, 4.69}}
-- R:pca{data = data, terms = {"ctl", "trt", "weight"}} -- 1.2342, 0.9735, 0.7274
pca = function(self, data)
if type(data) ~= "table" then
incompatibleTypeError(1, "table", data)
elseif type(data.data) == "CellularSpace" then
data.data = convertionTypes(data)
end
local term = #data.terms
local str, df, i, j, resultTable
local rotation = {}
i = 1
while i <= term do
if i == 1 then
str = table.concat{data.terms[i], " <- ", vectorToString(data.data[data.terms[i]]), "; "}
df = table.concat{data.terms[i], " = ", data.terms[i], ", "}
else
str = table.concat{str, data.terms[i], " <- ", vectorToString(data.data[data.terms[i]]), "; "}
if i ~= term then
df = table.concat{df, data.terms[i], " = ", data.terms[i], ", "}
else
df = table.concat{df, data.terms[i], " = ", data.terms[i], "); "}
end
end
i = i + 1
end
local result = self:evaluate(table.concat{str, "df = data.frame(", df, "ir.pca <- prcomp(df, center = TRUE, scale. = TRUE); ir.pca;"})
i = 1
while i <= term do
j = 0
rotation[i] = {data.terms[i],{}}
while j <= term do
table.insert(rotation[i][2], result[2][3][(term * j) + i])
j = j + 1
end
i = i + 1
end
resultTable = {StandardDeviations = result[2][1], Rotation = rotation}
return resultTable
end,
--- It returns the analysis of variance of a table of vectors computed in R.
-- if an entry is of an incompatible type returns with error.
-- @arg data.data a DataFrame or a CellularSpace.
-- @arg data.terms Columns of DataFrame or CellularSpace.
-- @arg data.strategy Type of ANOVA model to be used.
-- @arg data.factors Columns of DataFrame or CellularSpace that will be the factors.
-- @tabular strategy
-- Strategy & Description \
-- "owa" & One Way Anova (Completely Randomized Design) \
-- "rbd" & Randomized Block Design (B is the blocking factor) \
-- "twfd" & Two Way Factorial Design \
-- "aoc" & Analysis of Covariance \
-- "owf" & One Within Factor \
-- ""twftbf" & Two Within Factors, Two Between Factors \
-- @usage import ("rstats")
-- R = Rserve{}
-- data = DataFrame{ctl = {4.17, 5.58, 5.18, 6.11, 4.50, 4.61, 5.17, 4.53, 5.33, 5.14},
-- trt = {4.81, 4.17, 4.41, 3.59, 5.87, 3.83, 6.03, 4.89, 4.32, 4.69},
-- weight = {4.17, 5.18, 4.50, 5.17, 5.33, 4.81, 4.41, 5.87, 4.89, 4.69}}
-- R:anova{data = data, terms = {"ctl", "trt", "weight"}, strategy = "owa", factors = {"ctl", "trt"}} -- 1.0, 8.0, 0.6409, 2.4190, 0.6409, 0.3023, 2.1196, 0.1835
anova = function(self, data)
if type(data) ~= "table" then
incompatibleTypeError(1, "table", data)
elseif type(data.data) == "CellularSpace" then
data.data = convertionTypes(data)
end
local term = #data.terms
local str, df, i, fit
i = 1
while i <= term do
if i == 1 then
str = table.concat{data.terms[i], " <- ", vectorToString(data.data[data.terms[i]]), "; "}
df = table.concat{data.terms[i], " = ", data.terms[i], ", "}
else
str = table.concat{str, data.terms[i], " <- ", vectorToString(data.data[data.terms[i]]), "; "}
if i ~= term then
df = table.concat{df, data.terms[i], " = ", data.terms[i], ", "}
else
df = table.concat{df, data.terms[i], " = ", data.terms[i], "); "}
end
end
i = i + 1
end
switch(data, "strategy"):caseof{
owa = function() fit = table.concat{"fit <- aov(", data.factors[1], " ~ ", data.factors[2], ",data = df); x = summary(fit); x;"} end,
rbd = function() fit = table.concat{"fit <- aov(", data.factors[1], " ~ ", data.factors[2], " + ", data.factors[3], ",data = df); x = summary(fit); x;"} end,
twfd = function() fit = table.concat{"fit <- aov(", data.factors[1], " ~ ", data.factors[2], " * ", data.factors[3], ",data = df); x = summary(fit); x;"} end,
aoc = function() fit = table.concat{"fit <- aov(", data.factors[1], " ~ ", data.factors[2], " + ", data.factors[3], ",data = df); x = summary(fit); x;"} end,
owf = function() fit = table.concat{"fit <- aov(", data.factors[1], " ~ ", data.factors[2], " + Error(Subject/", data.factors[2], "),data = df); x = summary(fit); x;"} end,
twftbf = function() fit = table.concat{"fit <- aov(", data.factors[1], " ~ (", data.factors[2], " * ", data.factors[3], " * ", data.factors[4], " * ", data.factors[5], ") + Error(Subject/(", data.factors[2], " * ", data.factors[3], ")) + (", data.factors[4], " * ", data.factors[5] "),data = df); x = summary(fit); x;"} end
}
local result = self:evaluate(table.concat{str, "df = data.frame(", df, fit})
return result
end
--declare = function(self, data)
-- if type(data) ~= "table" then
-- incompatibleTypeError(1, "table", data)
-- elseif type(data.data) == "CellularSpace" then
-- data.data = convertionTypes(data)
-- end
-- return data.data
--local result = self:evaluate(table.concat(data.index, " = ", data.data))
--return result
--end
}
metaTableRserve_ = {
__index = function(index)
if Rserve_[index] then
return Rserve_[index]
end
return function(self, value)
return self:evaluate(index.."("..value..")")
end
end,
__tostring = _Gtme.tostring
--__newindex = function(self, index, value)
--return self:declare({index = index, data = value})
--end
}
--- Establishes host and port for communication with R.
-- if an entry is of an incompatible type returns with error.
-- @arg attrTab.host The host name can be passed to R.
-- @arg attrTab.port The port number can be passed to R.
-- @usage import ("rstats")
-- R = Rserve{}
function Rserve(attrTab)
if type(attrTab) ~= "table" and attrTab ~= nil then
verifyNamedTable(attrTab)
else
if type(attrTab) ~= "table" and attrTab == nil then
attrTab = {host = "localhost", port = 6311}
else
if type(attrTab.host) ~= "string" and attrTab.host ~= nil then
incompatibleTypeError("host", "string", attrTab.host)
elseif attrTab.host == "localhost" or attrTab.host == nil then
defaultTableValue(attrTab, "host", "localhost")
end
if type(attrTab.port) ~= "number" and attrTab.port then
incompatibleTypeError("port", "number", attrTab.port)
elseif attrTab.port == 6311 or attrTab.port == nil then
defaultTableValue(attrTab, "port", 6311)
end
end
end
setmetatable(attrTab, metaTableRserve_)
return attrTab
end
local function splitstring(str, sep)
local res = {}
local counter = 1
local pos = 1
for i = 1, #str do
if (string.sub(str, i, i) == sep) then
res[counter] = string.sub(str, pos, i)
pos = i + 1
counter = counter + 1
end
end
return res
end
local function buildstrmsg(rexp)
local command = 3
local length = (#rexp + 4)
local offset = 0
local length2 = 0
local dptype = 4
local data = {command, length, offset, length2, dptype, #rexp, rexp}
local dp_fmt = "u1 u3 s" .. #rexp
local fmt = QAP1_HEADER_FORMAT .. " " .. dp_fmt
return vstruct.write(fmt, " ", data)
end
local function getheader(str)
if #str < 4 then
return("ERROR: Invalid header (too short)")
end
local header = string.sub(str, 1, 4)
local type = vstruct.read(QAP1_SEXP_HEADER_TYPE_FORMAT, string.sub(header, 1, 1))
local len = vstruct.read(QAP1_SEXP_HEADER_LEN_FORMAT, string.sub(header, 2, 4))
return({["exptype"] = type[2], ["hasatts"] = type[1], ["explen"] = len[1]})
end
local function parsesexp(sexp)
if #sexp < 4 then
return("WARNING: Invalid SEXP (too short) - " .. #sexp)
end
local sexpexps = {}
local sexpcounter = 1
local token = 1
repeat
local header = getheader(string.sub(sexp, token, token + 3))
token = token + 4
local sexpend = token + header.explen - 1
if header.hasatts then
local attheader = getheader(string.sub(sexp, token, token + 3))
local att = parsesexp(string.sub(sexp, token, token + attheader.explen + 3))
token = token + 4 + attheader.explen
sexpexps[sexpcounter] = att
sexpcounter = sexpcounter + 1
end
local content = string.sub(sexp, token, sexpend)
token = sexpend + 1
local data
if header.exptype == 0 then
data = "XT_NULL"
elseif header.exptype == 3 or header.exptype == 19 then
data = vstruct.read(#content .. "*s", content)
elseif header.exptype == 16 or header.exptype == 21 or header.exptype == 23 or header.exptype == 20 or header.exptype == 22 then
data = parsesexp(content)
elseif header.exptype == 32 then
local len = #content / 4
data = vstruct.read(len .. "*u4", content)
elseif header.exptype == 33 then
local len = #content / 8
data = vstruct.read(len .. "*f8", content)
elseif header.exptype == 34 then
data = splitstring(content, string.char(0))
elseif header.exptype == 36 then
local len = vstruct.read("u4", string.sub(content, 1, 4))[1]
data = vstruct.read(len .. "*b1", string.sub(content, 5))
elseif header.exptype == 48 then
data = "XT_UNKNOWN"
else
return("ERROR: unknown QAP1 expression type:" .. header.exptype)
end
sexpexps[sexpcounter] = data
sexpcounter = sexpcounter + 1
until token > #sexp
return(sexpexps)
end
local function calltcp(rsserver, rsport, msg)
tcp = socket.tcp()
tcp:settimeout(1, 'b')
tcp:connect(rsserver, rsport)
if msg and msg ~= " " then
tcp:send(msg)
end
local s, status, partial = tcp:receive('*a')
tcp:close()
return s, status, partial
end
--- Establishes connection with R and returns value.
-- if an entry is of an incompatible type returns with error.
-- @arg rsserver The rsserver(host name) must be passed to R, but not necessarily by the user.
-- @arg rsport The rsport(port number) must be passed to R, but not necessarily by the user.
-- @arg rexp The rexp(expression) must be passed to R.
-- @usage import ("rstats")
-- luaRserveevaluate("localhost", 6311, "x=2")
function luaRserveevaluate(rsserver, rsport, rexp)
local parameters = {}
local msgbin = buildstrmsg(rexp)
local s, _, partial = calltcp(rsserver, rsport, msgbin)
local res = s or partial
local qmsg = string.sub(res, 33)
local qmsgheader = vstruct.read(QAP1_HEADER_FORMAT, string.sub(qmsg, 1, 16))
local qmsgdata = string.sub(qmsg, 17)
local token = 1
local pcounter = 1
repeat
local paramheader = vstruct.read(QAP1_PARAMETER_HEADER_FORMAT, string.sub(qmsgdata, token, token + 3))
token = token + 4
local parambody = string.sub(qmsgdata, token, token + paramheader[2] - 1)
if paramheader[1] == 10 then
parameters[pcounter] = parsesexp(parambody)
else
return("ERROR: parameter type " .. paramheader[1] .. " not implemented")
end
token = token + paramheader[2]
pcounter = pcounter + 1
until token > qmsgheader[2]
return(parameters)
end
| gpl-3.0 |
Hello23-Ygopro/ygopro-ds | expansions/script/c27001001.lua | 1 | 1305 | --BT1-001 God of Destruction Champa
local ds=require "expansions.utility_dbscg"
local scard,sid=ds.GetID()
function scard.initial_effect(c)
ds.EnableLeaderAttribute(c)
ds.AddSetcode(c,CHARACTER_CHAMPA,SPECIAL_TRAIT_GOD)
--draw
ds.AddSingleAutoAttack(c,0,nil,ds.hinttg,ds.DrawOperation(PLAYER_PLAYER,1))
--give skill
ds.AddActivateMainSkill(c,1,DS_LOCATION_LEADER,scard.skop,scard.skcost,scard.sktg,DS_EFFECT_FLAG_CARD_CHOOSE)
end
scard.dragon_ball_super_card=true
scard.leader_front=sid-1
scard.skcost=ds.SendtoDropCost(nil,LOCATION_HAND,0,1)
function scard.skfilter(c,tc)
return c:IsFaceup() and (c:IsBattle() or c==tc)
end
function scard.sktg(e,tp,eg,ep,ev,re,r,rp,chk,chkc)
local c=e:GetHandler()
if chkc then return chkc:IsLocation(DS_LOCATION_IN_PLAY) and chkc:IsControler(tp) and scard.skfilter(chkc,c) end
if chk==0 then return Duel.IsExistingTarget(scard.skfilter,tp,DS_LOCATION_IN_PLAY,0,1,nil,c) end
Duel.Hint(HINT_OPSELECTED,1-tp,e:GetDescription())
Duel.Hint(HINT_SELECTMSG,tp,DS_HINTMSG_TARGET)
Duel.SelectTarget(tp,scard.skfilter,tp,DS_LOCATION_IN_PLAY,0,1,1,nil,c)
end
function scard.skop(e,tp,eg,ep,ev,re,r,rp)
local tc=Duel.GetFirstTarget()
if not tc:IsRelateToSkill(e) or tc:IsFacedown() then return end
--double strike
ds.GainSkillDoubleStrike(e:GetHandler(),tc,2)
end
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Konschtat_Highlands/npcs/Shattered_Telepoint.lua | 19 | 2234 | -----------------------------------
-- Area: Konschtat Highlands
-- NPC: Shattered telepoint
-- @pos 135 19 220 108
-----------------------------------
package.loaded["scripts/zones/Konschtat_Highlands/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/missions");
require("scripts/zones/Konschtat_Highlands/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") == 1) then
player:startEvent(0x0391,0,0,1); -- first time in promy -> have you made your preparations cs
elseif (player:getCurrentMission(COP) == THE_MOTHERCRYSTALS and (player:hasKeyItem(LIGHT_OF_HOLLA) or player:hasKeyItem(LIGHT_OF_MEA))) then
if (player:getVar("cspromy2") == 1) then
player:startEvent(0x0390); -- cs you get nearing second promyvion
else
player:startEvent(0x0391);
end
elseif (player:getCurrentMission(COP) > THE_MOTHERCRYSTALS or player:hasCompletedMission(COP,THE_LAST_VERSE) or (player:getCurrentMission(COP) == BELOW_THE_ARKS and player:getVar("PromathiaStatus") > 1)) then
player:startEvent(0x0391); -- normal cs (third promyvion and each entrance after having that promyvion visited or mission completed)
else
player:messageSpecial(TELEPOINT_HAS_BEEN_SHATTERED);
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 == 0x0390) then
player:setVar("cspromy2",0);
player:setVar("cs2ndpromy",1);
player:setPos(-267.194, -40.634, -280.019, 0, 14); -- To Hall of Transference {R}
elseif (csid == 0x0391 and option == 0) then
player:setPos(-267.194, -40.634, -280.019, 0, 14); -- To Hall of Transference {R}
end
end; | gpl-3.0 |
nasomi/darkstar | scripts/zones/The_Eldieme_Necropolis/npcs/_5fo.lua | 34 | 2569 | -----------------------------------
-- Area: The Eldieme Necropolis
-- NPC: North Plate
-- @pos 174 -32 50 195
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local state0 = 8;
local state1 = 9;
local DoorOffset = npc:getID() - 23; -- _5f1
if (npc:getAnimation() == 8) then
state0 = 9;
state1 = 8;
end
-- Gates
-- Shiva's Gate
GetNPCByID(DoorOffset):setAnimation(state0);
GetNPCByID(DoorOffset+1):setAnimation(state0);
GetNPCByID(DoorOffset+2):setAnimation(state0);
GetNPCByID(DoorOffset+3):setAnimation(state0);
GetNPCByID(DoorOffset+4):setAnimation(state0);
-- Odin's Gate
GetNPCByID(DoorOffset+5):setAnimation(state1);
GetNPCByID(DoorOffset+6):setAnimation(state1);
GetNPCByID(DoorOffset+7):setAnimation(state1);
GetNPCByID(DoorOffset+8):setAnimation(state1);
GetNPCByID(DoorOffset+9):setAnimation(state1);
-- Leviathan's Gate
GetNPCByID(DoorOffset+10):setAnimation(state0);
GetNPCByID(DoorOffset+11):setAnimation(state0);
GetNPCByID(DoorOffset+12):setAnimation(state0);
GetNPCByID(DoorOffset+13):setAnimation(state0);
GetNPCByID(DoorOffset+14):setAnimation(state0);
-- Titan's Gate
GetNPCByID(DoorOffset+15):setAnimation(state1);
GetNPCByID(DoorOffset+16):setAnimation(state1);
GetNPCByID(DoorOffset+17):setAnimation(state1);
GetNPCByID(DoorOffset+18):setAnimation(state1);
GetNPCByID(DoorOffset+19):setAnimation(state1);
-- Plates
-- East Plate
GetNPCByID(DoorOffset+20):setAnimation(state0);
GetNPCByID(DoorOffset+21):setAnimation(state0);
-- North Plate
GetNPCByID(DoorOffset+22):setAnimation(state0);
GetNPCByID(DoorOffset+23):setAnimation(state0);
-- West Plate
GetNPCByID(DoorOffset+24):setAnimation(state0);
GetNPCByID(DoorOffset+25):setAnimation(state0);
-- South Plate
GetNPCByID(DoorOffset+26):setAnimation(state0);
GetNPCByID(DoorOffset+27):setAnimation(state0);
return 0;
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 |
alexaxel705/MTA-Tomsk | shared.lua | 1 | 27170 | --[Скин] = [Стиль походки, команда, пол, оружие, диалоги, {возможные имена ботов},]
SkinData = {
[0] = {0, "Мирные жители", "Мужчина"},
[1] = {0, "Мирные жители", "Мужчина"},
[2] = {0, "Мирные жители", "Мужчина"},
[3] = {0, "Мирные жители", "Мужчина"},
[4] = {0, "Мирные жители", "Мужчина"},
[5] = {0, "Мирные жители", "Мужчина"},
[6] = {0, "Мирные жители", "Мужчина"},
[7] = {118, "Мирные жители", "Мужчина"},
[8] = {0, "Мирные жители", "Мужчина", 6, "Дворник", {"Ворчливый", "Дворник"}},
[9] = {129, "Мирные жители", "Женщина"},
[10] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[11] = {129, "Мирные жители", "Женщина"},
[12] = {132, "Мирные жители", "Женщина"},
[13] = {129, "Мирные жители", "Женщина"},
[14] = {118, "Мирные жители", "Мужчина"},
[15] = {118, "Мирные жители", "Мужчина"},
[16] = {118, "Мирные жители", "Мужчина"},
[17] = {118, "Мирные жители", "Мужчина"},
[18] = {118, "Мирные жители", "Мужчина"},
[19] = {118, "Мирные жители", "Мужчина"},
[20] = {118, "Мирные жители", "Мужчина"},
[21] = {118, "Мирные жители", "Мужчина"},
[22] = {118, "Мирные жители", "Мужчина"},
[23] = {118, "Мирные жители", "Мужчина"},
[24] = {118, "Мирные жители", "Мужчина"},
[25] = {118, "Мирные жители", "Мужчина"},
[26] = {118, "Мирные жители", "Мужчина"},
[27] = {118, "Мирные жители", "Мужчина", nil, nil, {"Строитель"}},
[28] = {118, "Мирные жители", "Мужчина"},
[29] = {118, "Мирные жители", "Мужчина"},
[30] = {121, "Колумбийский картель", "Мужчина", 29},
[31] = {129, "Мирные жители", "Женщина"},
[32] = {118, "Мирные жители", "Мужчина"},
[33] = {118, "Мирные жители", "Мужчина"},
[34] = {118, "Мирные жители", "Мужчина"},
[35] = {118, "Мирные жители", "Мужчина"},
[36] = {118, "Мирные жители", "Мужчина", 2},
[37] = {118, "Мирные жители", "Мужчина", 2},
[38] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[39] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[40] = {131, "Мирные жители", "Женщина"},
[41] = {129, "Мирные жители", "Женщина"},
[42] = {0, "Мирные жители", "Мужчина"},
[43] = {121, "Колумбийский картель", "Мужчина", 29},
[44] = {118, "Мирные жители", "Мужчина"},
[45] = {118, "Мирные жители", "Мужчина"},
[46] = {121, "Мирные жители", "Мужчина"},
[47] = {118, "Мирные жители", "Мужчина"},
[48] = {118, "Мирные жители", "Мужчина"},
[49] = {120, "Мирные жители", "Мужчина"},
[50] = {118, "Мирные жители", "Мужчина"},
[51] = {118, "Мирные жители", "Мужчина"},
[52] = {118, "Мирные жители", "Мужчина"},
[53] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[54] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[55] = {129, "Мирные жители", "Женщина"},
[56] = {129, "Мирные жители", "Женщина"},
[57] = {120, "Мирные жители", "Мужчина", nil, nil, {"Дед", "Старик"}},
[58] = {118, "Мирные жители", "Мужчина"},
[59] = {118, "Мирные жители", "Мужчина"},
[60] = {118, "Мирные жители", "Мужчина"},
[61] = {118, "Мирные жители", "Мужчина", nil, nil, {"Пилот"}},
[62] = {0, "Уголовники", "Мужчина"},
[63] = {132, "Мирные жители", "Женщина", nil, nil, {"Шлюха"}},
[64] = {132, "Мирные жители", "Женщина", nil, nil, {"Шлюха"}},
[65] = {132, "Мирные жители", "Женщина", 12, nil, {"Девушка"}},
[66] = {118, "Мирные жители", "Мужчина"},
[67] = {118, "Мирные жители", "Мужчина"},
[68] = {118, "Мирные жители", "Мужчина"},
[69] = {129, "Мирные жители", "Женщина"},
[70] = {128, "МЧС", "Мужчина"},
[71] = {128, "Мирные жители", "Мужчина", 22},
[72] = {118, "Мирные жители", "Мужчина"},
[73] = {118, "Мирные жители", "Мужчина"},
[75] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[76] = {129, "Мирные жители", "Женщина"},
[77] = {135, "Мирные жители", "Женщина", nil, "Бомж", {"Бездомная", "Бомжиха"}},
[78] = {118, "Мирные жители", "Мужчина", nil, "Бомж", {"Бездомный", "Бродяга", "Бомж"}},
[79] = {118, "Мирные жители", "Мужчина", nil, "Бомж", {"Бездомный", "Бродяга", "Бомж"}},
[80] = {118, "Мирные жители", "Мужчина", nil, nil, {"Боксер"}},
[81] = {118, "Мирные жители", "Мужчина", nil, nil, {"Боксер"}},
[82] = {118, "Мирные жители", "Мужчина"},
[83] = {118, "Мирные жители", "Мужчина"},
[84] = {118, "Мирные жители", "Мужчина"},
[85] = {132, "Мирные жители", "Женщина"},
[87] = {132, "Мирные жители", "Женщина", nil, nil, {"Стриптизерша"}},
[88] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[89] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[90] = {132, "Мирные жители", "Женщина"},
[91] = {132, "Мирные жители", "Женщина"},
[92] = {138, "Мирные жители", "Женщина", nil, nil, {"Девушка на роликах"}},
[93] = {132, "Мирные жители", "Женщина"},
[94] = {120, "Мирные жители", "Мужчина", nil, nil, {"Дед", "Старик"}},
[95] = {121, "Колумбийский картель", "Мужчина", 29},
[96] = {132, "Мирные жители", "Женщина"},
[97] = {132, "Мирные жители", "Женщина"},
[98] = {132, "Мирные жители", "Женщина"},
[99] = {138, "Мирные жители", "Мужчина", nil, nil, {"Парень на роликах"}},
[100] = {121, "Байкеры", "Мужчина", 22},
[101] = {132, "Мирные жители", "Женщина"},
[102] = {121, "Баллас", "Мужчина", 5},
[103] = {121, "Баллас", "Мужчина", 22},
[104] = {121, "Баллас", "Мужчина", 22},
[105] = {122, "Гроув-стрит", "Мужчина", 4},
[106] = {122, "Гроув-стрит", "Мужчина", 22},
[107] = {122, "Гроув-стрит", "Мужчина", 22},
[108] = {121, "Вагос", "Мужчина", 22},
[109] = {121, "Вагос", "Мужчина", 22},
[110] = {121, "Вагос", "Мужчина", 22},
[111] = {121, "Русская мафия", "Мужчина", 25},
[112] = {121, "Русская мафия", "Мужчина", 25},
[113] = {121, "Русская мафия", "Мужчина", 25},
[114] = {122, "Ацтекас", "Мужчина", 28},
[115] = {122, "Ацтекас", "Мужчина", 28},
[116] = {122, "Ацтекас", "Мужчина", 28},
[117] = {122, "Триады", "Мужчина", 22},
[118] = {122, "Триады", "Мужчина", 29},
[120] = {122, "Триады", "Мужчина", 30},
[121] = {121, "Da Nang Boys", "Мужчина", 22, nil, {"DNB", "Куми-ин"}},
[122] = {121, "Da Nang Boys", "Мужчина", 28, nil, {"DNB", "Сансита"}},
[123] = {121, "Da Nang Boys", "Мужчина", 25, nil, {"DNB", "Дэката"}},
[124] = {118, "Мирные жители", "Мужчина"},
[125] = {121, "Русская мафия", "Мужчина", 25},
[126] = {121, "Русская мафия", "Мужчина", 25},
[127] = {121, "Русская мафия", "Мужчина", 25},
[128] = {118, "Мирные жители", "Мужчина"},
[129] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[130] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[131] = {132, "Мирные жители", "Женщина"},
[132] = {120, "Мирные жители", "Мужчина", nil, nil, {"Дед", "Старик"}},
[133] = {118, "Мирные жители", "Мужчина"},
[134] = {118, "Мирные жители", "Мужчина", nil, "Бомж", {"Бездомный", "Бродяга", "Бомж"}},
[135] = {118, "Мирные жители", "Мужчина", nil, "Бомж", {"Бездомный", "Бродяга", "Бомж"}},
[136] = {118, "Мирные жители", "Мужчина", nil, "Бомж", {"Бездомный", "Бродяга", "Бомж"}},
[137] = {118, "Мирные жители", "Мужчина", nil, "Бомж", {"Бездомный", "Бродяга", "Бомж"}},
[138] = {132, "Мирные жители", "Женщина"},
[139] = {132, "Мирные жители", "Женщина"},
[140] = {132, "Мирные жители", "Женщина"},
[141] = {129, "Мирные жители", "Женщина"},
[142] = {118, "Мирные жители", "Мужчина"},
[143] = {118, "Мирные жители", "Мужчина"},
[144] = {118, "Мирные жители", "Мужчина"},
[145] = {133, "Мирные жители", "Женщина"},
[146] = {133, "Мирные жители", "Женщина"},
[147] = {118, "Мирные жители", "Мужчина"},
[148] = {129, "Мирные жители", "Женщина"},
[150] = {129, "Мирные жители", "Женщина"},
[151] = {129, "Мирные жители", "Женщина"},
[152] = {132, "Мирные жители", "Женщина"},
[153] = {118, "Мирные жители", "Мужчина", nil, nil, {"Строитель"}},
[154] = {118, "Мирные жители", "Мужчина"},
[155] = {118, "Мирные жители", "Мужчина"},
[156] = {118, "Мирные жители", "Мужчина", 9, nil, {"Парикмахер"}},
[157] = {132, "Мирные жители", "Женщина"},
[158] = {122, "Деревенщины", "Мужчина", 33},
[159] = {119, "Деревенщины", "Мужчина", 33},
[160] = {119, "Деревенщины", "Мужчина", 33},
[161] = {119, "Деревенщины", "Мужчина", 33},
[162] = {126, "Деревенщины", "Мужчина", 33},
[163] = {118, "ЦРУ", "Мужчина", 31},
[164] = {118, "ЦРУ", "Мужчина", 31},
[165] = {118, "ЦРУ", "Мужчина", 31},
[166] = {118, "ЦРУ", "Мужчина", 31},
[167] = {118, "Мирные жители", "Мужчина"},
[168] = {118, "Мирные жители", "Мужчина"},
[169] = {129, "Da Nang Boys", "Женщина", 31, nil, {"DNB", "Кумитё"}},
[170] = {118, "Мирные жители", "Мужчина"},
[171] = {118, "Мирные жители", "Мужчина"},
[172] = {129, "Мирные жители", "Женщина"},
[173] = {121, "Рифа", "Мужчина", 32},
[174] = {121, "Рифа", "Мужчина", 32},
[175] = {121, "Рифа", "Мужчина", 32},
[176] = {118, "Мирные жители", "Мужчина"},
[177] = {118, "Мирные жители", "Мужчина"},
[178] = {132, "Мирные жители", "Женщина"},
[179] = {121, "Колумбийский картель", "Мужчина", 29},
[180] = {118, "Мирные жители", "Мужчина"},
[181] = {121, "Байкеры", "Мужчина", 22},
[182] = {118, "Мирные жители", "Мужчина"},
[183] = {118, "Мирные жители", "Мужчина"},
[184] = {118, "Мирные жители", "Мужчина"},
[185] = {118, "Мирные жители", "Мужчина"},
[186] = {118, "Мирные жители", "Мужчина"},
[187] = {118, "Мирные жители", "Мужчина"},
[188] = {118, "Мирные жители", "Мужчина"},
[189] = {118, "Мирные жители", "Мужчина"},
[190] = {132, "Мирные жители", "Женщина"},
[191] = {121, "Мирные жители", "Женщина"},
[192] = {121, "Мирные жители", "Женщина"},
[193] = {132, "Мирные жители", "Женщина"},
[194] = {132, "Мирные жители", "Женщина"},
[195] = {132, "Мирные жители", "Женщина"},
[196] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[197] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[198] = {129, "Мирные жители", "Женщина"},
[199] = {134, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[200] = {118, "Мирные жители", "Мужчина", nil, "Бомж", {"Бездомный", "Бродяга", "Бомж"}},
[201] = {129, "Мирные жители", "Женщина"},
[202] = {118, "Мирные жители", "Мужчина"},
[203] = {118, "Мирные жители", "Мужчина"},
[204] = {118, "Мирные жители", "Мужчина"},
[205] = {135, "Мирные жители", "Женщина"},
[206] = {118, "Мирные жители", "Мужчина"},
[207] = {132, "Мирные жители", "Женщина", nil, nil, {"Шлюха"}},
[209] = {118, "Мирные жители", "Мужчина"},
[210] = {118, "Мирные жители", "Мужчина"},
[211] = {132, "Мирные жители", "Женщина"},
[212] = {118, "Мирные жители", "Мужчина"},
[213] = {0, "Уголовники", "Мужчина"},
[214] = {132, "Мирные жители", "Женщина"},
[215] = {134, "Мирные жители", "Женщина"},
[216] = {132, "Мирные жители", "Женщина"},
[217] = {118, "Мирные жители", "Мужчина"},
[218] = {132, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[219] = {132, "Мирные жители", "Женщина"},
[220] = {118, "Мирные жители", "Мужчина"},
[221] = {118, "Колумбийский картель", "Мужчина"},
[222] = {121, "Колумбийский картель", "Мужчина", 29},
[223] = {121, "Мирные жители", "Мужчина"},
[224] = {134, "Мирные жители", "Женщина"},
[225] = {134, "Мирные жители", "Женщина"},
[226] = {135, "Мирные жители", "Женщина"},
[227] = {118, "Мирные жители", "Мужчина"},
[228] = {118, "Мирные жители", "Мужчина"},
[229] = {118, "Мирные жители", "Мужчина"},
[230] = {118, "Мирные жители", "Мужчина", nil, "Бомж", {"Бездомный", "Бродяга", "Бомж"}},
[231] = {132, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[232] = {132, "Мирные жители", "Женщина", 16, "Бабка", {"Старуха", "Бабка"}},
[233] = {129, "Мирные жители", "Женщина"},
[234] = {120, "Мирные жители", "Мужчина", nil, nil, {"Дед", "Старик"}},
[235] = {120, "Мирные жители", "Мужчина", nil, nil, {"Дед", "Старик"}},
[236] = {120, "Мирные жители", "Мужчина", nil, nil, {"Дед", "Старик"}},
[237] = {132, "Мирные жители", "Женщина", nil, nil, {"Шлюха"}},
[238] = {132, "Мирные жители", "Женщина", nil, nil, {"Шлюха"}},
[239] = {118, "Мирные жители", "Мужчина", nil, "Бомж", {"Бездомный", "Бродяга", "Бомж"}},
[240] = {118, "Мирные жители", "Мужчина"},
[241] = {124, "Мирные жители", "Мужчина"},
[242] = {121, "Колумбийский картель", "Мужчина", 29},
[243] = {132, "Мирные жители", "Женщина", nil, nil, {"Шлюха"}},
[244] = {132, "Мирные жители", "Женщина", nil, nil, {"Шлюха"}},
[245] = {135, "Мирные жители", "Женщина"},
[246] = {132, "Мирные жители", "Женщина", nil, nil, {"Стриптизерша"}},
[247] = {121, "Байкеры", "Мужчина", 22},
[248] = {121, "Байкеры", "Мужчина", 22},
[249] = {118, "Мирные жители", "Мужчина"},
[250] = {118, "Мирные жители", "Мужчина"},
[251] = {132, "Мирные жители", "Женщина"},
[252] = {133, "Уголовники", "Мужчина"},
[253] = {118, "Мирные жители", "Мужчина"},
[254] = {121, "Байкеры", "Мужчина", 22},
[255] = {118, "Мирные жители", "Мужчина"},
[256] = {132, "Мирные жители", "Женщина"},
[257] = {132, "Мирные жители", "Женщина", nil, nil, {"Стриптизерша"}},
[258] = {124, "Мирные жители", "Мужчина"},
[259] = {124, "Мирные жители", "Мужчина"},
[260] = {118, "Мирные жители", "Мужчина", nil, nil, {"Строитель"}},
[261] = {118, "Байкеры", "Мужчина"},
[262] = {118, "Мирные жители", "Мужчина", nil, nil, {"Водитель фуры"}},
[263] = {132, "Мирные жители", "Женщина"},
[264] = {128, "Мирные жители", "Мужчина"},
[265] = {128, "Полиция", "Мужчина", 22},
[266] = {128, "Полиция", "Мужчина", 22},
[267] = {128, "Полиция", "Мужчина", 22},
[268] = {0, "Уголовники", "Мужчина"},
[269] = {122, "Гроув-стрит", "Мужчина", 22},
[270] = {122, "Гроув-стрит", "Мужчина", 30},
[271] = {122, "Гроув-стрит", "Мужчина", 30},
[272] = {118, "Мирные жители", "Мужчина"},
[273] = {118, "Мирные жители", "Мужчина"},
[274] = {128, "МЧС", "Мужчина"},
[275] = {128, "МЧС", "Мужчина"},
[276] = {128, "МЧС", "Мужчина"},
[277] = {118, "МЧС", "Мужчина", nil, nil, {"Пожарный"}},
[278] = {118, "МЧС", "Мужчина", nil, nil, {"Пожарный"}},
[279] = {118, "МЧС", "Мужчина", nil, nil, {"Пожарный"}},
[280] = {128, "Полиция", "Мужчина", 22, nil, {"Полицейский", "Мент"}},
[281] = {128, "Полиция", "Мужчина", 22, nil, {"Полицейский", "Мент"}},
[282] = {128, "Полиция", "Мужчина", 22, nil, {"Полицейский", "Мент"}},
[283] = {128, "Полиция", "Мужчина", 22, nil, {"Шериф"}},
[284] = {128, "Полиция", "Мужчина", 22, nil, {"Патрульный"}},
[285] = {128, "Полиция", "Мужчина", 32, nil, {"SWAT"}},
[286] = {128, "ФБР", "Мужчина", 30, nil, {"ФБР"}},
[287] = {0, "Военные", "Мужчина", 31, nil, {"Военный"}},
[288] = {128, "Полиция", "Мужчина", 22, nil, {"Шериф"}},
[289] = {118, "Мирные жители", "Мужчина"},
[290] = {118, "Мирные жители", "Мужчина"},
[291] = {118, "Мирные жители", "Мужчина"},
[292] = {122, "Ацтекас", "Мужчина", 30},
[293] = {122, "Гроув-стрит", "Мужчина", 22},
[294] = {122, "Триады", "Мужчина", 30},
[295] = {118, "Мирные жители", "Мужчина"},
[296] = {118, "Мирные жители", "Мужчина"},
[297] = {118, "Мирные жители", "Мужчина"},
[298] = {132, "Мирные жители", "Женщина"},
[299] = {0, "Мирные жители", "Мужчина"},
[300] = {122, "Гроув-стрит", "Мужчина", 30},
[301] = {122, "Гроув-стрит", "Мужчина", 30},
[302] = {118, "Мирные жители", "Мужчина"},
[303] = {118, "Мирные жители", "Мужчина"},
[304] = {132, "Мирные жители", "Женщина"},
[305] = {118, "Мирные жители", "Мужчина"},
[306] = {118, "Мирные жители", "Женщина"},
[307] = {118, "Мирные жители", "Женщина"},
[308] = {118, "Мирные жители", "Женщина"},
[309] = {118, "Мирные жители", "Женщина"},
[310] = {118, "Мирные жители", "Мужчина"},
[311] = {122, "Гроув-стрит", "Мужчина", 22},
[312] = {0, "Военные", "Мужчина"}
}
SkinList = {}
for model, _ in pairs(SkinData) do
SkinList[#SkinList+1] = model
end
--[Должность], {необходимая репутация, фракция, зарплата, скин}
VacancyDATA = {
["Дальнобойщик"] = {0, "Мирные жители", 4750, 182},
["Патриарх"] = {250, "Мирные жители", 5000, 68},
["Рядовой"] = {10, "Полиция", 5281, 280},
["Инспектор ДПС"] = {25, "Полиция", 8000, 284},
["Сержант"] = {100, "Полиция", 10000, 281},
["Лейтенант"] = {250, "Полиция", 15000, 282},
["SWAT"] = {300, "Полиция", 20000, 285},
["Офицер 1 класса"] = {400, "Полиция", 25000, 267},
["Офицер 2 класса"] = {500, "Полиция", 28000, 266},
["Шериф округа Red County"] = {600, "Полиция", 30000, 283},
["Помощник шерифа"] = {700, "Полиция", 15000, 288},
["Начальник LSPD"] = {700, "Полиция", 40000, 265},
["Начальник SFPD"] = {700, "Полиция", 45000},
["Начальник LVPD"] = {700, "Полиция", 50000},
["ФБР"] = {250, "ФБР", 60000, 286},
["Директор ЦРУ"] = {700, "ЦРУ", 70000, 166},
["Репортер"] = {500, "Мирные жители", 25000},
["Санитар"] = {0, "МЧС", 7500, 276},
["Ученик"] = {70, "МЧС", 7500, 275},
["Врач"] = {120, "МЧС", 15000, 274},
["Учёный CPC"] = {200, "ЦРУ", 80000, 70},
["Тайный агент по борьбе с наркотиками"] = {400, "ЦРУ", 100000, 295},
}
--[Необходимое уважение = {Звание, id скина}
BandRangs = {
["Военные"] = {
[1] = {0, "Призывник", 312},
[2] = {30, "Контрактник", 287},
},
["Гроув-стрит"] = {
[1] = {0, "Укурыш", 293},
[2] = {30, "Красавчик Флиззи", 105},
[3] = {60, "Гангстерлительный", 106},
[4] = {120, "Джин Рамми", 107},
[5] = {180, "Big Smoke", 269},
[6] = {310, "Консильери", 270}
},
["Баллас"] = {
[1] = {0, "Жаба", 102},
[2] = {30, "Гусь", 103},
[3] = {60, "Бык", 104}
},
["Колумбийский картель"] = {
[1] = {0, "La Mugre", 222},
[2] = {25, "Diego", 221},
[3] = {50, "Sombras", 95},
[4] = {75, "Sureno", 30},
[5] = {120, "Cacos", 242},
[6] = {180, "Guerrero", 179},
[7] = {250, "Лейтенант колумбийского картеля", 43}
},
["Вагос"] = {
[1] = {0, "Отмычка", 108},
[2] = {30, "Браток", 109},
[3] = {60, "Комендант", 110}
},
["Байкеры"] = {
[1] = {0, "Тусовщик", 181},
[2] = {30, "Вольный ездок", 247},
[3] = {75, "Шустрила", 248},
[4] = {130, "Дорожный капитан", 100},
[5] = {160, "Железная задница", 261},
},
["Русская мафия"] = {
[1] = {0, "Клоп", 111},
[2] = {30, "Вор", 112},
[3] = {75, "Пахан", 113},
},
["Ацтекас"] = {
[1] = {0, "Сопляк", 114},
[2] = {30, "Кирпич", 115},
[3] = {75, "Башка", 116},
[4] = {130, "Громоотвод", 292}
},
["Триады"] = {
[1] = {0, "Моль", 117},
[2] = {30, "Баклан", 118},
[3] = {75, "Зам. Лидера", 120},
[4] = {130, "Желтый дракон (Лидер)", 294}
},
["Da Nang Boys"] = {
[1] = {0, "Куми-ин", 121},
[2] = {30, "Сансита", 122},
[3] = {75, "Дэката", 123},
[4] = {130, "Кумитё (Лидер)", 169}
},
["Деревенщины"] = {
[1] = {0, "Опущенный", 162},
[2] = {50, "Чёрт", 160},
[3] = {75, "Шнырь", 159},
[4] = {120, "Блатной", 161},
[5] = {180, "Папаша", 158}
},
["Рифа"] = {
[1] = {0, "Упырь", 173},
[2] = {30, "Баклан", 174},
[3] = {75, "Капореджиме", 175},
},
["Уголовники"] = {
[1] = {0, "Потраченный", 252},
[2] = {25, "Черт", 213},
[3] = {50, "Шпана", 268},
[4] = {100, "Блатной", 62},
},
["Мирные жители"] = {
[1] = {0, "Житель", 252}
},
}
function GetSkinJob(model)
local Zvanie = "Неизвестно"
for team, dat in pairs(BandRangs) do
for i, dat2 in pairs(dat) do
if(dat2[3] == model) then
Zvanie = dat2[2]
end
end
end
for id, dat in pairs(VacancyDATA) do
if(dat[4] == model) then
Zvanie = id
end
end
return Zvanie
end
function GetSkinData()
return SkinData
end
addEvent("GetSkinData", true)
addEventHandler("GetSkinData", root, GetSkinData)
| gpl-3.0 |
TeamHypersomnia/Augmentations | hypersomnia/content/official/gfx/darkblue_fish_1.meta.lua | 16 | 1897 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 80,
light_colors = {
"0 139 161 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
TeamHypersomnia/Augmentations | hypersomnia/content/official/gfx/darkblue_fish_6.meta.lua | 16 | 1897 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 80,
light_colors = {
"0 139 161 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 6
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
jeffreyling/seq2seq-hard | beam.lua | 1 | 38755 | require 'nn'
require 'string'
require 'hdf5'
require 'nngraph'
require 'data.lua'
require 'models.lua'
require 'util.lua'
require 'logging'
ENTROPY = 0
GOLD_SIZE = 0
MUTE = true
stringx = require('pl.stringx')
cmd = torch.CmdLine()
cmd:option('-log_path', '', [[Logging path]])
-- check attn options
cmd:option('-num_argmax', 0, [[Change multisampling to do different number of argmax]])
cmd:option('-view_attn', 0, [[View attention weights at each time step]])
cmd:option('-print_attn', 1, [[Print attention weights]])
cmd:option('-print_sent_attn', 1, [[Print sentence attention instead of all attn]])
cmd:option('-no_pad', 1, [[No pad format for data]])
cmd:option('-no_pad_sent_l', 10, [[Number of `sentences` we have for a doc]])
cmd:option('-repeat_words', 0, [[Repeat words format for data]])
-- file location
cmd:option('-model', 'seq2seq_lstm_attn.t7.', [[Path to model .t7 file]])
cmd:option('-src_file', '',[[Source sequence to decode (one line per sequence)]])
cmd:option('-targ_file', '', [[True target sequence (optional)]])
cmd:option('-src_hdf5', '', [[Instead of src_file and targ_file, can provide a src_hdf5 from preprocessing]])
cmd:option('-output_file', 'pred.txt', [[Path to output the predictions (each line will be the
decoded sequence]])
cmd:option('-src_dict', 'data/demo.src.dict', [[Path to source vocabulary (*.src.dict file)]])
cmd:option('-targ_dict', 'data/demo.targ.dict', [[Path to target vocabulary (*.targ.dict file)]])
cmd:option('-char_dict', 'data/demo.char.dict', [[If using chars, path to character
vocabulary (*.char.dict file)]])
-- beam search options
cmd:option('-beam', 5,[[Beam size]])
cmd:option('-max_sent_l', 20, [[Maximum sentence length. If any sequences in srcfile are longer
than this then it will error out. This is really max num sents in doc!]])
cmd:option('-simple', 0, [[If = 1, output prediction is simply the first time the top of the beam
ends with an end-of-sentence token. If = 0, the model considers all
hypotheses that have been generated so far that ends with end-of-sentence
token and takes the highest scoring of all of them.]])
cmd:option('-replace_unk', 0, [[Replace the generated UNK tokens with the source token that
had the highest attention weight. If srctarg_dict is provided,
it will lookup the identified source token and give the corresponding
target token. If it is not provided (or the identified source token
does not exist in the table) then it will copy the source token]])
cmd:option('-srctarg_dict', 'data/en-de.dict', [[Path to source-target dictionary to replace UNK
tokens. See README.md for the format this file should be in]])
cmd:option('-score_gold', 1, [[If = 1, score the log likelihood of the gold as well]])
cmd:option('-n_best', 1, [[If > 1, it will also output an n_best list of decoded sentences]])
cmd:option('-gpuid', -1, [[ID of the GPU to use (-1 = use CPU)]])
--cmd:option('-gpuid2', -1, [[Second GPU ID]])
cmd:option('-cudnn', 0, [[If using character model, this should be = 1 if the character model
was trained using cudnn]])
opt = cmd:parse(arg)
function reset_state(state, batch_l)
local u = {}
for i = 1, #state do
state[i]:zero()
table.insert(u, state[i][{{1, batch_l}}])
end
return u
end
function copy(orig)
local orig_type = type(orig)
local copy
if orig_type == 'table' then
copy = {}
for orig_key, orig_value in pairs(orig) do
copy[orig_key] = orig_value
end
else
copy = orig
end
return copy
end
local StateAll = torch.class("StateAll")
function StateAll.initial(start)
return {start}
end
function StateAll.advance(state, token)
local new_state = copy(state)
table.insert(new_state, token)
return new_state
end
function StateAll.disallow(out)
local bad = {1, 3} -- 1 is PAD, 3 is BOS
for j = 1, #bad do
out[bad[j]] = -1e9
end
end
function StateAll.same(state1, state2)
for i = 2, #state1 do
if state1[i] ~= state2[i] then
return false
end
end
return true
end
function StateAll.next(state)
return state[#state]
end
function StateAll.heuristic(state)
return 0
end
function StateAll.print(state)
local result = ""
for i = 1, #state do
result = result .. state[i] .. " "
end
logging:info(result, MUTE)
end
function pretty_print(t)
for i,x in ipairs(t) do
local result = ""
if i > 1 then
for j = 1, x:size(1) do
result = result .. string.format("%.4f ", x[j])
end
logging:info(result, MUTE)
end
end
end
-- Convert a flat index to a row-column tuple.
function flat_to_rc(v, flat_index)
local row = math.floor((flat_index - 1) / v:size(2)) + 1
return row, (flat_index - 1) % v:size(2) + 1
end
function get_nonzeros(source)
local nonzeros = {}
for i = 1, source:size(1) do
table.insert(nonzeros, source[i]:ne(1):sum())
end
return nonzeros
end
function generate_beam(model, initial, K, max_sent_l, source, gold)
--reset decoder initial states
local n = max_sent_l
-- Backpointer table.
local prev_ks = torch.LongTensor(n, K):fill(1)
-- Current States.
local next_ys = torch.LongTensor(n, K):fill(1)
-- Current Scores.
local scores = torch.FloatTensor(n, K)
scores:zero()
local nonzeros = get_nonzeros(source)
source = source:t():contiguous() -- get words to dim 1 for LSTM
--local source_l = math.min(source:size(1), opt.max_sent_l)
local source_char_l = source:size(1)
local source_sent_l = source:size(2)
local attn_argmax = {} -- store attn weights
attn_argmax[1] = {}
local attn_list = {}
attn_list[1] = {}
local deficit_list = {}
deficit_list[1] = {}
local sentence_attn_list = {}
sentence_attn_list[1] = {}
local attn_argmax_words
if model_opt.hierarchical == 1 then
attn_argmax_words = {}
attn_argmax_words[1] = {}
end
local states = {} -- store predicted word idx
states[1] = {}
for k = 1, 1 do
table.insert(states[1], initial)
table.insert(attn_argmax[1], initial)
table.insert(attn_list[1], initial)
table.insert(sentence_attn_list[1], initial)
table.insert(deficit_list[1], initial)
next_ys[1][k] = State.next(initial)
end
local source_input
-- for batch
if model_opt.use_chars_enc == 1 then
source_input = source:view(source_char_l, 1, source:size(2)):contiguous():cuda()
else
source_input = source:view(source_char_l, 1)
end
local pad_mask = source_input:eq(1)
local source_lens = source_input:ne(1):sum(1):cuda():squeeze(1)
--source_lens[source_lens:eq(0)]:fill(1) -- prevent indexing 0
local rnn_state_mask
if model_opt.no_bow == 1 then
rnn_state_mask = torch.zeros(1, source_sent_l, source_char_l, model_opt.rnn_size):byte():cuda()
for t = 1, source_sent_l do
local idx = source_lens[1][t]
rnn_state_mask[1][t][idx]:fill(1)
end
end
--local rnn_state_enc = {}
--for i = 1, #init_fwd_enc do
--table.insert(rnn_state_enc, init_fwd_enc[i]:zero())
--end
local rnn_state_enc = reset_state(init_fwd_enc, 1*source_sent_l)
local context = context_proto[{{}, {1, source_sent_l}, {1,source_char_l}}]:clone() -- 1 x source_l x source_char_l x rnn_size
local context_bow = context_bow_proto[{{}, {1, source_sent_l}}]:clone() -- 1 x source_l x word_vec_size
local rnn_state_bow_enc
if model_opt.bow_encoder_lstm == 1 then
rnn_state_bow_enc = reset_state(init_fwd_bow_enc, 1)
end
-- pos embeds
if model_opt.pos_embeds == 1 and model_opt.hierarchical == 1 then
local pos = pos_proto[{{}, {1, source_sent_l}}]:reshape(1*source_sent_l)
local pos_states = model[layers_idx['pos_embeds']]:forward(pos) -- 1*source_sent_l x num_layers*rnn_size*2
for l = 1, model_opt.num_layers do
rnn_state_enc[l*2-1]:copy(pos_states[{{},{(l*2-2)*model_opt.rnn_size+1, (l*2-1)*model_opt.rnn_size}}])
rnn_state_enc[l*2]:copy(pos_states[{{},{(l*2-1)*model_opt.rnn_size+1, (l*2)*model_opt.rnn_size}}])
end
end
for t = 1, source_char_l do
local encoder_input = {source_input[t], table.unpack(rnn_state_enc)}
local out = model[1]:forward(encoder_input)
if model_opt.mask_padding == 1 then
local cur_mask = pad_mask[t]:view(1*source_sent_l, 1):expand(1*source_sent_l, model_opt.rnn_size)
for L = 1, model_opt.num_layers do
out[L*2-1]:maskedFill(cur_mask, 0)
out[L*2]:maskedFill(cur_mask, 0)
end
end
rnn_state_enc = out
context[{{},{},t}]:copy(out[#out]:view(1, source_sent_l, model_opt.rnn_size))
end
local masked_selecter, rnn_states
if model_opt.no_bow == 1 then
masked_selecter = make_last_state_selecter(model_opt.rnn_size, 1, source_sent_l) -- TODO: seems wrong
rnn_states = masked_selecter:forward({context, rnn_state_mask})
end
if model_opt.hierarchical == 1 then
local bow_out
if model_opt.pos_embeds_sent == 1 then
local pos = pos_proto[{{}, {1, source_sent_l}}]
bow_out = model[layers_idx['bow_encoder']]:forward({source_input:permute(2,3,1):contiguous(), pos})
else
bow_out = model[layers_idx['bow_encoder']]:forward(source_input:permute(2,3,1):contiguous())
end
if model_opt.bow_encoder_lstm == 1 then
-- pass bag of words through LSTM over sentences for context
for t = 1, source_sent_l do
local bow_encoder_input
if model_opt.no_bow == 1 then
bow_encoder_input = {rnn_states[t], table.unpack(rnn_state_bow_enc)}
else
bow_encoder_input = {bow_out[t], table.unpack(rnn_state_bow_enc)}
end
local out = model[layers_idx['bow_encoder_lstm']]:forward(bow_encoder_input)
rnn_state_bow_enc = out
context_bow[{{}, t}]:copy(out[#out])
end
else
context_bow:copy(bow_out)
end
end
rnn_state_dec = {}
for i = 1, #init_fwd_dec do
table.insert(rnn_state_dec, init_fwd_dec[i]:zero())
end
if model_opt.init_dec == 1 then
init_dec_module = make_init_dec_module(model_opt, 1, source_sent_l)
for L = 1, model_opt.num_layers do
rnn_state_dec[L*2-1+model_opt.input_feed]:copy(
init_dec_module:forward(rnn_state_enc[L*2-1]):expand(K, model_opt.rnn_size))
rnn_state_dec[L*2+model_opt.input_feed]:copy(
init_dec_module:forward(rnn_state_enc[L*2]):expand(K, model_opt.rnn_size))
end
end
if model_opt.brnn == 1 then
local rnn_state_enc = reset_state(init_fwd_enc, 1*source_sent_l)
--for i = 1, #rnn_state_enc do
--rnn_state_enc[i]:zero()
--end
for t = source_char_l, 1, -1 do
local encoder_input = {source_input[t], table.unpack(rnn_state_enc)}
local out = model[layers_idx['encoder_bwd']]:forward(encoder_input)
rnn_state_enc = out
context[{{},{},t}]:add(out[#out]:view(1, source_sent_l, model_opt.rnn_size))
end
if model_opt.init_dec == 1 then
for L = 1, model_opt.num_layers do
rnn_state_dec[L*2-1+model_opt.input_feed]:add(
init_dec_module:forward(rnn_state_enc[L*2-1]:expand(K, model_opt.rnn_size)))
rnn_state_dec[L*2+model_opt.input_feed]:add(
init_dec_module:forward(rnn_state_enc[L*2]:expand(K, model_opt.rnn_size)))
end
end
end
context = context:expand(K, source_sent_l, source_char_l, model_opt.rnn_size)
if model_opt.hierarchical == 1 then
context_bow = context_bow:expand(K, source_sent_l, model_opt.bow_size)
end
out_float = torch.FloatTensor()
local i = 1
local done = false
local max_score = -1e9
local found_eos = false
while (not done) and (i < n) do
i = i+1
states[i] = {}
attn_argmax[i] = {}
attn_list[i] = {}
sentence_attn_list[i] = {}
deficit_list[i] = {}
if model_opt.hierarchical == 1 then
attn_argmax_words[i] = {}
end
local decoder_input1
if model_opt.use_chars_dec == 1 then
decoder_input1 = word2charidx_targ:index(1, next_ys:narrow(1,i-1,1):squeeze())
else
decoder_input1 = next_ys:narrow(1,i-1,1):squeeze()
if opt.beam == 1 then
decoder_input1 = torch.LongTensor({decoder_input1})
end
end
local decoder_input = {decoder_input1, table.unpack(rnn_state_dec)}
local out_decoder = model[2]:forward(decoder_input)
local decoder_attn_input
if model_opt.hierarchical == 1 then
decoder_attn_input = {out_decoder[#out_decoder], context, context_bow}
else
decoder_attn_input = {out_decoder[#out_decoder], context}
end
local attn_out = model[layers_idx['decoder_attn']]:forward(decoder_attn_input)
local out = model[3]:forward(attn_out) -- K x vocab_size
rnn_state_dec = {} -- to be modified later
if model_opt.input_feed == 1 then
table.insert(rnn_state_dec, attn_out)
end
for j = 1, #out_decoder do
table.insert(rnn_state_dec, out_decoder[j])
end
out_float:resize(out:size()):copy(out)
for k = 1, K do
State.disallow(out_float:select(1, k))
out_float[k]:add(scores[i-1][k])
end
-- All the scores available.
local flat_out = out_float:view(-1)
if i == 2 then
flat_out = out_float[1] -- all outputs same for first batch
end
if model_opt.start_symbol == 1 then
decoder_softmax.output[{{},1}]:zero()
decoder_softmax.output[{{},source_l}]:zero()
end
for k = 1, K do
while true do
local score, index = flat_out:max(1)
local score = score[1]
local prev_k, y_i = flat_to_rc(out_float, index[1])
states[i][k] = State.advance(states[i-1][prev_k], y_i)
local diff = true
for k2 = 1, k-1 do
if State.same(states[i][k2], states[i][k]) then
diff = false
end
end
if i < 2 or diff then
if opt.view_attn == 1 then
-- outdated...
print('decoder attention at time ' .. i)
if model_opt.hierarchical == 1 then
print('row:', decoder_softmax.output) -- K x source_sent_l
print('words:', decoder_softmax_words.output:view(K, source_sent_l, source_char_l))
else
print('all words:', decoder_softmax.output:view(K, source_sent_l, source_char_l))
end
io.read()
end
if model_opt.hierarchical == 1 then
local row_attn = decoder_softmax.output[prev_k]:clone()
local word_attn = decoder_softmax_words.output:reshape(K, source_sent_l, source_char_l)[prev_k]:clone()
local result
for r = 1, row_attn:size(1) do
if nonzeros[r] > 0 then -- ignore blank sentences
word_attn[r]:mul(row_attn[r])
local cur = word_attn[r][{{1, nonzeros[r]}}]
if result == nil then
result = cur
else
result = torch.cat(result, cur, 1)
end
end
end
attn_list[i][k] = State.advance(attn_list[i-1][prev_k], result)
sentence_attn_list[i][k] = State.advance(sentence_attn_list[i-1][prev_k], row_attn)
deficit_list[i][k] = State.advance(deficit_list[i-1][prev_k], 1-result:sum())
max_attn, max_index = result:max(1)
attn_argmax[i][k] = State.advance(attn_argmax[i-1][prev_k],max_index[1])
else
-- sum the rows
local pre_attn = decoder_softmax.output:reshape(K, source_sent_l, source_char_l)[prev_k]:clone()
local row_attn = pre_attn:sum(2):squeeze(2)
local result
for r = 1, source_sent_l do
local cur
if nonzeros[r] > 0 then -- ignore blank sentences
cur = pre_attn[r][{{1, nonzeros[r]}}]
if result == nil then
result = cur
else
result = torch.cat(result, cur, 1)
end
end
end
attn_list[i][k] = State.advance(attn_list[i-1][prev_k], result)
sentence_attn_list[i][k] = State.advance(sentence_attn_list[i-1][prev_k], row_attn)
deficit_list[i][k] = State.advance(deficit_list[i-1][prev_k], 1-result:sum())
max_attn, max_index = result:max(1)
attn_argmax[i][k] = State.advance(attn_argmax[i-1][prev_k],max_index[1])
end
prev_ks[i][k] = prev_k
next_ys[i][k] = y_i
scores[i][k] = score
flat_out[index[1]] = -1e9
break -- move on to next k
end
flat_out[index[1]] = -1e9
end
end
for j = 1, #rnn_state_dec do
rnn_state_dec[j]:copy(rnn_state_dec[j]:index(1, prev_ks[i]))
end
end_hyp = states[i][1]
end_score = scores[i][1]
end_attn_argmax = attn_argmax[i][1]
end_attn_list = attn_list[i][1]
end_sentence_attn_list = sentence_attn_list[i][1]
end_deficit_list = deficit_list[i][1]
if end_hyp[#end_hyp] == END then
done = true
found_eos = true
else
for k = 1, K do
local possible_hyp = states[i][k]
if possible_hyp[#possible_hyp] == END then
found_eos = true
if scores[i][k] > max_score then
max_hyp = possible_hyp
max_score = scores[i][k]
max_attn_argmax = attn_argmax[i][k]
max_attn_list = attn_list[i][k]
max_sentence_attn_list = sentence_attn_list[i][k]
max_deficit_list = deficit_list[i][k]
end
end
end
end
end
local gold_score = 0
if opt.score_gold == 1 then
local gold_sentence_attn_list = {}
gold_sentence_attn_list[1] = initial
local gold_attn_list = {}
gold_attn_list[1] = initial
rnn_state_dec = {}
for i = 1, #init_fwd_dec do
table.insert(rnn_state_dec, init_fwd_dec[i][{{1}}]:zero())
end
if model_opt.init_dec == 1 then
for L = 1, model_opt.num_layers do
--rnn_state_dec[L*2]:copy(init_dec_module:forward(rnn_state_enc[L*2-1][{{1}}]))
--rnn_state_dec[L*2+1]:copy(init_dec_module:forward(rnn_state_enc[L*2][{{1}}]))
rnn_state_dec[L*2]:copy(init_dec_module:forward(rnn_state_enc[L*2-1]))
rnn_state_dec[L*2+1]:copy(init_dec_module:forward(rnn_state_enc[L*2]))
end
end
local target_l = gold:size(1)
for t = 2, target_l do
local decoder_input1
if model_opt.use_chars_dec == 1 then
decoder_input1 = word2charidx_targ:index(1, gold[{{t-1}}])
else
decoder_input1 = gold[{{t-1}}]
end
local decoder_input = {decoder_input1, table.unpack(rnn_state_dec)}
local out_decoder = model[2]:forward(decoder_input)
local decoder_attn_input
if model_opt.hierarchical == 1 then
decoder_attn_input = {out_decoder[#out_decoder], context[{{1}}], context_bow[{{1}}]}
else
decoder_attn_input = {out_decoder[#out_decoder], context[{{1}}]}
end
local attn_out = model[layers_idx['decoder_attn']]:forward(decoder_attn_input)
if opt.print_attn == 1 or opt.print_sent_attn == 1 then
gold_sentence_attn_list[t] = {}
gold_attn_list[t] = {}
if model_opt.hierarchical == 1 then
local row_attn = decoder_softmax.output[1]:clone()
local word_attn = decoder_softmax_words.output:clone()
local result
for r = 1, row_attn:size(1) do
if nonzeros[r] > 0 then -- ignore blank sentences
word_attn[r]:mul(row_attn[r])
local cur = word_attn[r][{{1, nonzeros[r]}}]
if result == nil then
result = cur
else
result = torch.cat(result, cur, 1)
end
end
end
gold_sentence_attn_list[t] = row_attn
gold_attn_list[t] = result
else
local pre_attn = decoder_softmax.output:clone()
if opt.no_pad == 1 then
pre_attn = pre_attn:view(opt.no_pad_sent_l, model_opt.max_word_l)
end
local row_attn = pre_attn:sum(2):squeeze(2)
local result
for r = 1, source_sent_l do
local cur
if nonzeros[r] > 0 then -- ignore blank sentences
cur = pre_attn[r][{{1, nonzeros[r]}}]
if result == nil then
result = cur
else
result = torch.cat(result, cur, 1)
end
end
end
gold_sentence_attn_list[t] = row_attn
gold_attn_list[t] = result
end
end
local out = model[3]:forward(attn_out) -- K x vocab_size
rnn_state_dec = {} -- to be modified later
if model_opt.input_feed == 1 then
table.insert(rnn_state_dec, attn_out)
end
for j = 1, #out_decoder do
table.insert(rnn_state_dec, out_decoder[j])
end
gold_score = gold_score + out[1][gold[t]]
end
if opt.print_attn == 1 then
logging:info('ATTN GOLD', MUTE)
pretty_print(gold_attn_list)
end
if opt.print_sent_attn == 1 then
-- sentence attn
logging:info('ATTN LEVEL GOLD', MUTE)
pretty_print(gold_sentence_attn_list)
for j = 2, #gold_sentence_attn_list do
local p = gold_sentence_attn_list[j]
ENTROPY = ENTROPY + p:cmul(torch.log(p + 1e-8)):sum()
GOLD_SIZE = GOLD_SIZE + p:size(1)
end
end
end
if opt.simple == 1 or end_score > max_score or not found_eos then
max_hyp = end_hyp
max_score = end_score
max_attn_argmax = end_attn_argmax
max_attn_list = end_attn_list
max_sentence_attn_list = end_sentence_attn_list
max_deficit_list = end_deficit_list
end
return max_hyp, max_score, max_attn_argmax, gold_score, states[i], scores[i], attn_argmax[i], max_attn_list, max_deficit_list, max_sentence_attn_list
end
function idx2key(file)
local f = io.open(file,'r')
local t = {}
for line in f:lines() do
local c = {}
for w in line:gmatch'([^%s]+)' do
table.insert(c, w)
end
t[tonumber(c[2])] = c[1]
end
return t
end
function flip_table(u)
local t = {}
for key, value in pairs(u) do
t[value] = key
end
return t
end
function get_layer(layer)
if layer.name ~= nil then
if layer.name == 'decoder_attn' then
decoder_attn = layer
elseif layer.name:sub(1,3) == 'hop' then
hop_attn = layer
elseif layer.name:sub(1,7) == 'softmax' then
table.insert(softmax_layers, layer)
elseif layer.name == 'word_vecs_enc' then
word_vecs_enc = layer
elseif layer.name == 'word_vecs_dec' then
word_vecs_dec = layer
elseif layer.name == 'sampler' then
sampler_layer = layer
end
end
if layer.__typename == 'nn.SoftPlus' then
probe_layer = layer
end
end
function sent2wordidx(sent, word2idx, start_symbol)
local t = {}
local u = {}
if start_symbol == 1 then
table.insert(t, START)
table.insert(u, START_WORD)
end
for word in sent:gmatch'([^%s]+)' do
local idx = word2idx[word] or UNK
table.insert(t, idx)
table.insert(u, word)
end
if start_symbol == 1 then
table.insert(t, END)
table.insert(u, END_WORD)
end
return torch.LongTensor(t), u
end
function doc2charidx(doc, char2idx, max_word_l, start_symbol)
local words = {}
local st = 1
for idx in doc:gmatch("()(</s>)") do
local sent = doc:sub(st, idx-2)
st = idx + 5
table.insert(words, {})
if start_symbol == 1 then
table.insert(words[#words], START_WORD)
end
for word in sent:gmatch'([^%s]+)' do
table.insert(words[#words], word)
end
if start_symbol == 1 then
table.insert(words[#words], END_WORD)
elseif opt.no_pad == 1 then
table.insert(words[#words], "</s>")
end
end
--local chars = torch.ones(#words, max_word_l)
--for i = 1, #words do
--chars[i] = word2charidx(words[i], char2idx, max_word_l, chars[i])
--end
local chars
if opt.no_pad == 1 then
local rep_words = opt.repeat_words
chars = torch.ones(opt.no_pad_sent_l, max_word_l)
local i = 1
local j = 1
local done = false
for _,word in ipairs(words) do
for _, char in ipairs(word) do
local char_idx = char2idx[char] or UNK
chars[i][j] = char_idx
j = j+1
if j == max_word_l + 1 then
i = i+1
if i == opt.no_pad_sent_l + 1 then
done = true
break
end
if rep_words > 0 then
-- copy last row over
local tail = chars[{{i-1}, {max_word_l-rep_words+1, max_word_l}}]
chars[{{i},{1,rep_words}}]:copy(tail)
j = rep_words + 1
else
j = 1
end
end
end
if done then break end
end
else
chars = torch.ones(#words, max_word_l)
for i = 1, #words do
chars[i] = word2charidx(words[i], char2idx, max_word_l, chars[i], start_symbol)
end
end
return chars, words
end
function word2charidx(word, char2idx, max_word_l, t, start_symbol)
local i = 1
if start_symbol == 1 then
t[1] = START
i = 2
end
--for _, char in utf8.next, word do
--char = utf8.char(char)
for _,char in ipairs(word) do
local char_idx = char2idx[char] or UNK
t[i] = char_idx
i = i+1
if i > max_word_l then
if start_symbol == 1 then
t[i] = END
end
break
end
end
if (i < max_word_l) and (start_symbol == 1) then
t[i] = END
end
return t
end
function wordidx2sent(sent, idx2word, source_str, attn, skip_end)
local t = {}
if skip_end == nil then skip_end = true end
local start_i = 1
local end_i
if torch.isTensor(sent) then
end_i = sent:size(1)
else
end_i = #sent
end
if skip_end then
start_i = start_i + 1
end_i = end_i - 1
end
for i = start_i, end_i do -- skip START and END
if sent[i] == UNK then
if opt.replace_unk == 1 then
local s = source_str[attn[i]]
if phrase_table[s] ~= nil then
logging:info(s .. ':' ..phrase_table[s])
end
local r = phrase_table[s] or s
table.insert(t, r)
else
table.insert(t, idx2word[sent[i]])
end
else
table.insert(t, idx2word[sent[i]])
end
end
return table.concat(t, ' ')
end
function clean_sent(sent)
local s = stringx.replace(sent, UNK_WORD, '')
s = stringx.replace(s, START_WORD, '')
s = stringx.replace(s, END_WORD, '')
--s = stringx.replace(s, START_CHAR, '')
--s = stringx.replace(s, END_CHAR, '')
return s
end
function strip(s)
return s:gsub("^%s+",""):gsub("%s+$","")
end
function iterate_tensor(t)
assert(torch.isTensor(t), 'non-tensor provided')
local i = 0
local function f(t, _)
if i < t:size(1) then
i = i+1
return t[i]
else
return nil
end
end
return f, t, nil
end
function main()
-- some globals
PAD = 1; UNK = 2; START = 3; END = 4
PAD_WORD = '<blank>'; UNK_WORD = '<unk>'; START_WORD = '<d>'; END_WORD = '</d>'
START_CHAR = '{'; END_CHAR = '}'
MAX_SENT_L = opt.max_sent_l
-- parse input params
opt = cmd:parse(arg)
assert(opt.log_path ~= '', 'need to set logging')
logging = logger(opt.log_path)
logging:info("Command line args:")
logging:info(arg)
logging:info("End command line args")
logging:info('max_sent_l: ' .. MAX_SENT_L)
if path.exists(opt.src_hdf5) then
logging:info('using hdf5 file ' .. opt.src_hdf5)
else
assert(path.exists(opt.src_file), 'src_file does not exist')
end
assert(path.exists(opt.model), 'model does not exist')
if opt.gpuid >= 0 then
require 'cutorch'
require 'cunn'
if opt.cudnn == 1 then
require 'cudnn'
end
end
logging:info('loading ' .. opt.model .. '...')
checkpoint = torch.load(opt.model)
logging:info('done!')
if opt.replace_unk == 1 then
phrase_table = {}
if path.exists(opt.srctarg_dict) then
local f = io.open(opt.srctarg_dict,'r')
for line in f:lines() do
local c = line:split("|||")
phrase_table[strip(c[1])] = c[2]
end
end
end
-- load model and word2idx/idx2word dictionaries
model, model_opt = checkpoint[1], checkpoint[2]
for i = 1, #model do
model[i]:evaluate()
end
layers_idx = model_opt.save_idx
assert(opt.src_dict ~= '', 'need dictionary')
opt.targ_dict = opt.src_dict
opt.char_dict = opt.src_dict
idx2word_src = idx2key(opt.src_dict)
word2idx_src = flip_table(idx2word_src)
idx2word_targ = idx2key(opt.targ_dict)
word2idx_targ = flip_table(idx2word_targ)
-- load character dictionaries if needed
if model_opt.use_chars_enc == 1 or model_opt.use_chars_dec == 1 then
--utf8 = require 'lua-utf8'
char2idx = flip_table(idx2key(opt.char_dict))
model[1]:apply(get_layer)
end
if model_opt.use_chars_dec == 1 then
word2charidx_targ = torch.LongTensor(#idx2word_targ, model_opt.max_word_l):fill(PAD)
for i = 1, #idx2word_targ do
word2charidx_targ[i] = word2charidx(idx2word_targ[i], char2idx,
model_opt.max_word_l, word2charidx_targ[i])
end
end
-- load gold labels if it exists
if path.exists(opt.targ_file) then
logging:info('loading GOLD labels at ' .. opt.targ_file)
gold = {}
local file = io.open(opt.targ_file, 'r')
for line in file:lines() do
table.insert(gold, line)
end
else
if opt.src_hdf5 == '' then
-- no gold data
opt.score_gold = 0
end
end
local file
local src_sents = {}
local num_sents = 0
if opt.src_hdf5 ~= '' then
file = hdf5.open(opt.src_hdf5, 'r')
local source_char = file:read('source_char'):all()
num_sents = source_char:size(1)
for i = 1, num_sents do
table.insert(src_sents, source_char[i])
end
-- reinit gold
gold = {}
local targets = file:read('target'):all()
for i = 1, num_sents do
table.insert(gold, targets[i])
end
else
file = io.open(opt.src_file, "r")
for line in file:lines() do
table.insert(src_sents, line)
num_sents = num_sents + 1
end
end
if opt.gpuid >= 0 then
cutorch.setDevice(opt.gpuid)
for i = 1, #model do
model[i]:double():cuda()
model[i]:evaluate()
end
end
softmax_layers = {}
model[2]:apply(get_layer)
decoder_attn = model[layers_idx['decoder_attn']]
decoder_attn:apply(get_layer)
decoder_softmax = softmax_layers[1]
decoder_softmax_words = softmax_layers[2]
if model_opt.hierarchical == 0 then
assert(decoder_softmax_words == nil)
end
if model_opt.hierarchical == 1 and model_opt.attn_type == 'hard' then
if opt.num_argmax > 0 then
sampler_layer.multisampling = opt.num_argmax -- do this number of argmax
end
end
attn_layer = torch.zeros(opt.beam, MAX_SENT_L)
MAX_WORD_L = model_opt.max_word_l
context_proto = torch.zeros(1, MAX_SENT_L, MAX_WORD_L, model_opt.rnn_size)
context_bow_proto = torch.zeros(1, MAX_SENT_L, model_opt.bow_size)
if model_opt.pos_embeds == 1 or model_opt.pos_embeds_sent == 1 then
pos_proto = torch.LongTensor(1, MAX_SENT_L):zero():cuda()
for t = 1, MAX_SENT_L do
pos_proto[{{}, {t}}]:fill(t)
end
end
local h_init_dec = torch.zeros(opt.beam, model_opt.rnn_size)
--local h_init_enc = torch.zeros(1, model_opt.rnn_size)
local h_init_enc = torch.zeros(MAX_SENT_L, model_opt.rnn_size)
if opt.gpuid >= 0 then
h_init_enc = h_init_enc:cuda()
h_init_dec = h_init_dec:cuda()
cutorch.setDevice(opt.gpuid)
context_proto = context_proto:cuda()
context_bow_proto = context_bow_proto:cuda()
attn_layer = attn_layer:cuda()
end
init_fwd_enc = {}
init_fwd_dec = {} -- initial context
init_fwd_bow_enc = {}
if model_opt.input_feed == 1 then
table.insert(init_fwd_dec, h_init_dec:clone())
end
for L = 1, model_opt.num_layers do
table.insert(init_fwd_enc, h_init_enc:clone())
table.insert(init_fwd_enc, h_init_enc:clone())
table.insert(init_fwd_dec, h_init_dec:clone()) -- memory cell
table.insert(init_fwd_dec, h_init_dec:clone()) -- hidden state
if model_opt.bow_encoder_lstm == 1 then
table.insert(init_fwd_bow_enc, h_init_enc:clone())
table.insert(init_fwd_bow_enc, h_init_enc:clone())
end
end
pred_score_total = 0
gold_score_total = 0
pred_words_total = 0
gold_words_total = 0
total_deficit = 0
State = StateAll
local sent_id = 0
pred_sents = {}
local out_file = io.open(opt.output_file,'w')
for _,line in ipairs(src_sents) do
sent_id = sent_id + 1
local source, source_str
local target, target_str
if opt.src_hdf5 == '' then
line = clean_sent(line)
logging:info('SENT ' .. sent_id .. ': ' ..line, MUTE)
if model_opt.use_chars_enc == 0 then
assert(false, 'do not use now')
source, source_str = sent2wordidx(line, word2idx_src, model_opt.start_symbol)
else
source, source_str = doc2charidx(line, char2idx, model_opt.max_word_l, model_opt.start_symbol)
end
if opt.score_gold == 1 then
target, target_str = sent2wordidx(gold[sent_id], word2idx_targ, 1)
end
else
-- line is a tensor
source_str = wordidx2sent(line:view(line:nElement()), idx2word_src, nil, nil, false)
logging:info('SENT ' .. sent_id .. ': ' .. source_str, MUTE)
source = line
if opt.score_gold == 1 then
target = gold[sent_id]
local nonzero = target:ne(1):sum()
target = target[{{1, nonzero}}] -- remove padding
gold[sent_id] = target
target_str = wordidx2sent(gold[sent_id], idx2word_targ, nil, nil, false)
end
end
state = State.initial(START)
pred, pred_score, attn, gold_score, all_sents, all_scores, all_attn, attn_list, deficit_list, sentence_attn_list = generate_beam(model, state, opt.beam, MAX_SENT_L, source, target) -- use attn_list to print attn
pred_score_total = pred_score_total + pred_score
pred_words_total = pred_words_total + #pred - 1
pred_sent = wordidx2sent(pred, idx2word_targ, source_str, attn, true)
out_file:write(pred_sent .. '\n')
logging:info('PRED ' .. sent_id .. ': ' .. pred_sent, MUTE)
if gold ~= nil then
if opt.src_hdf5 == '' then
logging:info('GOLD ' .. sent_id .. ': ' .. gold[sent_id], MUTE)
else
logging:info('GOLD ' .. sent_id .. ': ' .. target_str, MUTE)
end
if opt.score_gold == 1 then
logging:info(string.format("PRED SCORE: %.4f, GOLD SCORE: %.4f", pred_score, gold_score), MUTE)
gold_score_total = gold_score_total + gold_score
gold_words_total = gold_words_total + target:size(1) - 1
end
end
if opt.n_best > 1 then
for n = 1, opt.n_best do
pred_sent_n = wordidx2sent(all_sents[n], idx2word_targ, source_str, all_attn[n], false)
local out_n = string.format("%d ||| %s ||| %.4f", n, pred_sent_n, all_scores[n])
logging:info(out_n, MUTE)
out_file:write(out_n .. '\n')
end
end
if opt.print_attn == 1 then
logging:info('ATTN PRED', MUTE)
pretty_print(attn_list)
end
if opt.print_sent_attn == 1 then
logging:info('ATTN LEVEL PRED', MUTE)
pretty_print(sentence_attn_list)
end
--deficit_list[1] = 0
--total_deficit = total_deficit + torch.Tensor(deficit_list):sum()
----print(deficit_list)
----io.read()
--end
logging:info('', MUTE)
end
logging:info(string.format("PRED AVG SCORE: %.4f, PRED PPL: %.4f", pred_score_total / pred_words_total,
math.exp(-pred_score_total/pred_words_total)))
if opt.score_gold == 1 then
logging:info(string.format("GOLD AVG SCORE: %.4f, GOLD PPL: %.4f",
gold_score_total / gold_words_total,
math.exp(-gold_score_total/gold_words_total)))
end
logging:info(string.format("attn deficit: %.4f", total_deficit/pred_words_total))
logging:info(string.format("gold entropy: %.4f", ENTROPY / GOLD_SIZE))
out_file:close()
end
main()
| mit |
Gamerbude/Wasteland | mods/cme/sheep/init.lua | 1 | 5837 | --= Sheep for Creatures MOB-Engine (cme) =--
-- Copyright (c) 2015-2016 BlockMen <blockmen2015@gmail.com>
--
-- init.lua
--
-- This software is provided 'as-is', without any express or implied warranty. In no
-- event will the authors be held liable for any damages arising from the use of
-- this software.
--
-- Permission is granted to anyone to use this software for any purpose, including
-- commercial applications, and to alter it and redistribute it freely, subject to the
-- following restrictions:
--
-- 1. The origin of this software must not be misrepresented; you must not
-- claim that you wrote the original software. If you use this software in a
-- product, an acknowledgment in the product documentation is required.
-- 2. Altered source versions must be plainly marked as such, and must not
-- be misrepresented as being the original software.
-- 3. This notice may not be removed or altered from any source distribution.
--
-- shears
core.register_tool(":creatures:shears", {
description = "Shears",
inventory_image = "creatures_shears.png",
})
core.register_craft({
output = 'creatures:shears',
recipe = {
{'', 'default:steel_ingot'},
{'default:steel_ingot', 'default:stick'},
}
})
local function setColor(self)
if self and self.object then
local ext = ".png"
if self.has_wool ~= true then
ext = ".png^(creatures_sheep_shaved.png^[colorize:" .. self.wool_color:gsub("grey", "gray") .. ":50)"
end
self.object:set_properties({textures = {"creatures_sheep.png^creatures_sheep_" .. self.wool_color .. ext}})
end
end
local function shear(self, drop_count, sound)
if self.has_wool == true then
self.has_wool = false
local pos = self.object:getpos()
if sound then
core.sound_play("creatures_shears", {pos = pos, gain = 1, max_hear_distance = 10})
end
setColor(self)
creatures.dropItems(pos, {{"wool:" .. self.wool_color, drop_count}})
end
end
-- white, grey, brown, black (see wool colors as reference)
local colors = {"white", "grey", "brown", "black"}
local def = {
name = "creatures:sheep",
stats = {
hp = 8,
lifetime = 450, -- 7,5 Minutes
can_jump = 1,
can_swim = true,
can_burn = true,
can_panic = true,
has_falldamage = true,
has_kockback = true,
},
model = {
mesh = "creatures_sheep.b3d",
textures = {"creatures_sheep.png^creatures_sheep_white.png"},
collisionbox = {-0.5, -0.01, -0.55, 0.5, 1.1, 0.55},
rotation = -90.0,
animations = {
idle = {start = 1, stop = 60, speed = 15},
walk = {start = 81, stop = 101, speed = 18},
walk_long = {start = 81, stop = 101, speed = 18},
eat = {start = 107, stop = 170, speed = 12, loop = false},
follow = {start = 81, stop = 101, speed = 15},
death = {start = 171, stop = 191, speed = 32, loop = false, duration = 2.52},
},
},
sounds = {
on_damage = {name = "creatures_sheep", gain = 1.0, distance = 10},
on_death = {name = "creatures_sheep", gain = 1.0, distance = 10},
swim = {name = "creatures_splash", gain = 1.0, distance = 10,},
random = {
idle = {name = "creatures_sheep", gain = 0.6, distance = 10, time_min = 23},
},
},
modes = {
idle = {chance = 0.5, duration = 10, update_yaw = 8},
walk = {chance = 0.14, duration = 4.5, moving_speed = 1.3},
walk_long = {chance = 0.11, duration = 8, moving_speed = 1.3, update_yaw = 5},
-- special modes
follow = {chance = 0, duration = 20, radius = 4, timer = 5, moving_speed = 1, items = {"farming:wheat"}},
eat = { chance = 0.25,
duration = 4,
nodes = {
"default:grass_1", "default:grass_2", "default:grass_3",
"default:grass_4", "default:grass_5", "default:dirt_with_grass", "default:grass"
}
},
},
drops = function(self)
local items = {{"creatures:flesh"}}
if self.has_wool then
table.insert(items, {"wool:" .. self.wool_color, {min = 1, max = 2}})
end
creatures.dropItems(self.object:getpos(), items)
end,
spawning = {
abm_nodes = {
spawn_on = {"default:dirt_with_grass"},
},
abm_interval = 65,
abm_chance = 65535,
max_number = 1,
number = {min = 1, max = 3},
time_range = {min = 5100, max = 18300},
light = {min = 10, max = 15},
height_limit = {min = 0, max = 25},
spawn_egg = {
description = "Sheep Spawn-Egg",
texture = "creatures_egg_sheep.png",
},
spawner = {
description = "Sheep Spawner",
range = 8,
player_range = 20,
number = 6,
}
},
on_punch = function(self, puncher)
shear(self)
end,
get_staticdata = function(self)
return {
has_wool = self.has_wool,
wool_color = self.wool_color,
}
end,
on_activate = function(self, staticdata)
if self.has_wool == nil then
self.has_wool = true
end
if not self.wool_color then
self.wool_color = colors[math.random(1, #colors)]
end
-- update fur
setColor(self)
end,
on_rightclick = function(self, clicker)
local item = clicker:get_wielded_item()
if item then
local name = item:get_name()
if name == "farming:wheat" then
self.target = clicker
self.mode = "follow"
self.modetimer = 0
if not self.tamed then
self.fed_cnt = (self.fed_cnt or 0) + 1
end
-- play eat sound?
item:take_item()
elseif name == "creatures:shears" and self.has_wool then
shear(self, math.random(2, 3), true)
item:add_wear(65535/100)
end
if not core.setting_getbool("creative_mode") then
clicker:set_wielded_item(item)
end
end
return true
end,
on_step = function(self, dtime)
if self.mode == "eat" and self.eat_node then
self.regrow_wool = true
end
if self.last_mode == "eat" and (self.modetimer and self.modetimer == 0) and self.regrow_wool then
self.has_wool = true
self.regrow_wool = nil
setColor(self)
end
if self.fed_cnt and self.fed_cnt > 4 then
self.tamed = true
self.fed_cnt = nil
end
end
}
creatures.register_mob(def)
| gpl-3.0 |
icplus/OP-SDK | package/ramips/ui/luci-mtk/src/modules/admin-full/luasrc/model/cbi/admin_network/ifaces.lua | 36 | 15568 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 2008-2011 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local fs = require "nixio.fs"
local ut = require "luci.util"
local pt = require "luci.tools.proto"
local nw = require "luci.model.network"
local fw = require "luci.model.firewall"
arg[1] = arg[1] or ""
local has_dnsmasq = fs.access("/etc/config/dhcp")
local has_firewall = fs.access("/etc/config/firewall")
m = Map("network", translate("Interfaces") .. " - " .. arg[1]:upper(), translate("On this page you can configure the network interfaces. You can bridge several interfaces by ticking the \"bridge interfaces\" field and enter the names of several network interfaces separated by spaces. You can also use <abbr title=\"Virtual Local Area Network\">VLAN</abbr> notation <samp>INTERFACE.VLANNR</samp> (<abbr title=\"for example\">e.g.</abbr>: <samp>eth0.1</samp>)."))
m:chain("wireless")
if has_firewall then
m:chain("firewall")
end
nw.init(m.uci)
fw.init(m.uci)
local net = nw:get_network(arg[1])
local function backup_ifnames(is_bridge)
if not net:is_floating() and not m:get(net:name(), "_orig_ifname") then
local ifcs = net:get_interfaces() or { net:get_interface() }
if ifcs then
local _, ifn
local ifns = { }
for _, ifn in ipairs(ifcs) do
ifns[#ifns+1] = ifn:name()
end
if #ifns > 0 then
m:set(net:name(), "_orig_ifname", table.concat(ifns, " "))
m:set(net:name(), "_orig_bridge", tostring(net:is_bridge()))
end
end
end
end
-- redirect to overview page if network does not exist anymore (e.g. after a revert)
if not net then
luci.http.redirect(luci.dispatcher.build_url("admin/network/network"))
return
end
-- protocol switch was requested, rebuild interface config and reload page
if m:formvalue("cbid.network.%s._switch" % net:name()) then
-- get new protocol
local ptype = m:formvalue("cbid.network.%s.proto" % net:name()) or "-"
local proto = nw:get_protocol(ptype, net:name())
if proto then
-- backup default
backup_ifnames()
-- if current proto is not floating and target proto is not floating,
-- then attempt to retain the ifnames
--error(net:proto() .. " > " .. proto:proto())
if not net:is_floating() and not proto:is_floating() then
-- if old proto is a bridge and new proto not, then clip the
-- interface list to the first ifname only
if net:is_bridge() and proto:is_virtual() then
local _, ifn
local first = true
for _, ifn in ipairs(net:get_interfaces() or { net:get_interface() }) do
if first then
first = false
else
net:del_interface(ifn)
end
end
m:del(net:name(), "type")
end
-- if the current proto is floating, the target proto not floating,
-- then attempt to restore ifnames from backup
elseif net:is_floating() and not proto:is_floating() then
-- if we have backup data, then re-add all orphaned interfaces
-- from it and restore the bridge choice
local br = (m:get(net:name(), "_orig_bridge") == "true")
local ifn
local ifns = { }
for ifn in ut.imatch(m:get(net:name(), "_orig_ifname")) do
ifn = nw:get_interface(ifn)
if ifn and not ifn:get_network() then
proto:add_interface(ifn)
if not br then
break
end
end
end
if br then
m:set(net:name(), "type", "bridge")
end
-- in all other cases clear the ifnames
else
local _, ifc
for _, ifc in ipairs(net:get_interfaces() or { net:get_interface() }) do
net:del_interface(ifc)
end
m:del(net:name(), "type")
end
-- clear options
local k, v
for k, v in pairs(m:get(net:name())) do
if k:sub(1,1) ~= "." and
k ~= "type" and
k ~= "ifname" and
k ~= "_orig_ifname" and
k ~= "_orig_bridge"
then
m:del(net:name(), k)
end
end
-- set proto
m:set(net:name(), "proto", proto:proto())
m.uci:save("network")
m.uci:save("wireless")
-- reload page
luci.http.redirect(luci.dispatcher.build_url("admin/network/network", arg[1]))
return
end
end
-- dhcp setup was requested, create section and reload page
if m:formvalue("cbid.dhcp._enable._enable") then
m.uci:section("dhcp", "dhcp", nil, {
interface = arg[1],
start = "100",
limit = "150",
leasetime = "12h"
})
m.uci:save("dhcp")
luci.http.redirect(luci.dispatcher.build_url("admin/network/network", arg[1]))
return
end
local ifc = net:get_interface()
s = m:section(NamedSection, arg[1], "interface", translate("Common Configuration"))
s.addremove = false
s:tab("general", translate("General Setup"))
s:tab("advanced", translate("Advanced Settings"))
s:tab("physical", translate("Physical Settings"))
if has_firewall then
s:tab("firewall", translate("Firewall Settings"))
end
st = s:taboption("general", DummyValue, "__status", translate("Status"))
local function set_status()
-- if current network is empty, print a warning
if not net:is_floating() and net:is_empty() then
st.template = "cbi/dvalue"
st.network = nil
st.value = translate("There is no device assigned yet, please attach a network device in the \"Physical Settings\" tab")
else
st.template = "admin_network/iface_status"
st.network = arg[1]
st.value = nil
end
end
m.on_init = set_status
m.on_after_save = set_status
p = s:taboption("general", ListValue, "proto", translate("Protocol"))
p.default = net:proto()
if not net:is_installed() then
p_install = s:taboption("general", Button, "_install")
p_install.title = translate("Protocol support is not installed")
p_install.inputtitle = translate("Install package %q" % net:opkg_package())
p_install.inputstyle = "apply"
p_install:depends("proto", net:proto())
function p_install.write()
return luci.http.redirect(
luci.dispatcher.build_url("admin/system/packages") ..
"?submit=1&install=%s" % net:opkg_package()
)
end
end
p_switch = s:taboption("general", Button, "_switch")
p_switch.title = translate("Really switch protocol?")
p_switch.inputtitle = translate("Switch protocol")
p_switch.inputstyle = "apply"
local _, pr
for _, pr in ipairs(nw:get_protocols()) do
p:value(pr:proto(), pr:get_i18n())
if pr:proto() ~= net:proto() then
p_switch:depends("proto", pr:proto())
end
end
auto = s:taboption("advanced", Flag, "auto", translate("Bring up on boot"))
auto.default = (net:proto() == "none") and auto.disabled or auto.enabled
delegate = s:taboption("advanced", Flag, "delegate", translate("Use builtin IPv6-management"))
delegate.default = delegate.enabled
if not net:is_virtual() then
br = s:taboption("physical", Flag, "type", translate("Bridge interfaces"), translate("creates a bridge over specified interface(s)"))
br.enabled = "bridge"
br.rmempty = true
br:depends("proto", "static")
br:depends("proto", "dhcp")
br:depends("proto", "none")
stp = s:taboption("physical", Flag, "stp", translate("Enable <abbr title=\"Spanning Tree Protocol\">STP</abbr>"),
translate("Enables the Spanning Tree Protocol on this bridge"))
stp:depends("type", "bridge")
stp.rmempty = true
end
if not net:is_floating() then
ifname_single = s:taboption("physical", Value, "ifname_single", translate("Interface"))
ifname_single.template = "cbi/network_ifacelist"
ifname_single.widget = "radio"
ifname_single.nobridges = true
ifname_single.rmempty = false
ifname_single.network = arg[1]
ifname_single:depends("type", "")
function ifname_single.cfgvalue(self, s)
-- let the template figure out the related ifaces through the network model
return nil
end
function ifname_single.write(self, s, val)
local i
local new_ifs = { }
local old_ifs = { }
for _, i in ipairs(net:get_interfaces() or { net:get_interface() }) do
old_ifs[#old_ifs+1] = i:name()
end
for i in ut.imatch(val) do
new_ifs[#new_ifs+1] = i
-- if this is not a bridge, only assign first interface
if self.option == "ifname_single" then
break
end
end
table.sort(old_ifs)
table.sort(new_ifs)
for i = 1, math.max(#old_ifs, #new_ifs) do
if old_ifs[i] ~= new_ifs[i] then
backup_ifnames()
for i = 1, #old_ifs do
net:del_interface(old_ifs[i])
end
for i = 1, #new_ifs do
net:add_interface(new_ifs[i])
end
break
end
end
end
end
if not net:is_virtual() then
ifname_multi = s:taboption("physical", Value, "ifname_multi", translate("Interface"))
ifname_multi.template = "cbi/network_ifacelist"
ifname_multi.nobridges = true
ifname_multi.rmempty = false
ifname_multi.network = arg[1]
ifname_multi.widget = "checkbox"
ifname_multi:depends("type", "bridge")
ifname_multi.cfgvalue = ifname_single.cfgvalue
ifname_multi.write = ifname_single.write
end
if has_firewall then
fwzone = s:taboption("firewall", Value, "_fwzone",
translate("Create / Assign firewall-zone"),
translate("Choose the firewall zone you want to assign to this interface. Select <em>unspecified</em> to remove the interface from the associated zone or fill out the <em>create</em> field to define a new zone and attach the interface to it."))
fwzone.template = "cbi/firewall_zonelist"
fwzone.network = arg[1]
fwzone.rmempty = false
function fwzone.cfgvalue(self, section)
self.iface = section
local z = fw:get_zone_by_network(section)
return z and z:name()
end
function fwzone.write(self, section, value)
local zone = fw:get_zone(value)
if not zone and value == '-' then
value = m:formvalue(self:cbid(section) .. ".newzone")
if value and #value > 0 then
zone = fw:add_zone(value)
else
fw:del_network(section)
end
end
if zone then
fw:del_network(section)
zone:add_network(section)
end
end
end
function p.write() end
function p.remove() end
function p.validate(self, value, section)
if value == net:proto() then
if not net:is_floating() and net:is_empty() then
local ifn = ((br and (br:formvalue(section) == "bridge"))
and ifname_multi:formvalue(section)
or ifname_single:formvalue(section))
for ifn in ut.imatch(ifn) do
return value
end
return nil, translate("The selected protocol needs a device assigned")
end
end
return value
end
local form, ferr = loadfile(
ut.libpath() .. "/model/cbi/admin_network/proto_%s.lua" % net:proto()
)
if not form then
s:taboption("general", DummyValue, "_error",
translate("Missing protocol extension for proto %q" % net:proto())
).value = ferr
else
setfenv(form, getfenv(1))(m, s, net)
end
local _, field
for _, field in ipairs(s.children) do
if field ~= st and field ~= p and field ~= p_install and field ~= p_switch then
if next(field.deps) then
local _, dep
for _, dep in ipairs(field.deps) do
dep.deps.proto = net:proto()
end
else
field:depends("proto", net:proto())
end
end
end
--
-- Display DNS settings if dnsmasq is available
--
if has_dnsmasq and net:proto() == "static" then
m2 = Map("dhcp", "", "")
local has_section = false
m2.uci:foreach("dhcp", "dhcp", function(s)
if s.interface == arg[1] then
has_section = true
return false
end
end)
if not has_section and has_dnsmasq then
s = m2:section(TypedSection, "dhcp", translate("DHCP Server"))
s.anonymous = true
s.cfgsections = function() return { "_enable" } end
x = s:option(Button, "_enable")
x.title = translate("No DHCP Server configured for this interface")
x.inputtitle = translate("Setup DHCP Server")
x.inputstyle = "apply"
elseif has_section then
s = m2:section(TypedSection, "dhcp", translate("DHCP Server"))
s.addremove = false
s.anonymous = true
s:tab("general", translate("General Setup"))
s:tab("advanced", translate("Advanced Settings"))
s:tab("ipv6", translate("IPv6 Settings"))
function s.filter(self, section)
return m2.uci:get("dhcp", section, "interface") == arg[1]
end
local ignore = s:taboption("general", Flag, "ignore",
translate("Ignore interface"),
translate("Disable <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr> for " ..
"this interface."))
local start = s:taboption("general", Value, "start", translate("Start"),
translate("Lowest leased address as offset from the network address."))
start.optional = true
start.datatype = "or(uinteger,ip4addr)"
start.default = "100"
local limit = s:taboption("general", Value, "limit", translate("Limit"),
translate("Maximum number of leased addresses."))
limit.optional = true
limit.datatype = "uinteger"
limit.default = "150"
local ltime = s:taboption("general", Value, "leasetime", translate("Leasetime"),
translate("Expiry time of leased addresses, minimum is 2 minutes (<code>2m</code>)."))
ltime.rmempty = true
ltime.default = "12h"
local dd = s:taboption("advanced", Flag, "dynamicdhcp",
translate("Dynamic <abbr title=\"Dynamic Host Configuration Protocol\">DHCP</abbr>"),
translate("Dynamically allocate DHCP addresses for clients. If disabled, only " ..
"clients having static leases will be served."))
dd.default = dd.enabled
s:taboption("advanced", Flag, "force", translate("Force"),
translate("Force DHCP on this network even if another server is detected."))
-- XXX: is this actually useful?
--s:taboption("advanced", Value, "name", translate("Name"),
-- translate("Define a name for this network."))
mask = s:taboption("advanced", Value, "netmask",
translate("<abbr title=\"Internet Protocol Version 4\">IPv4</abbr>-Netmask"),
translate("Override the netmask sent to clients. Normally it is calculated " ..
"from the subnet that is served."))
mask.optional = true
mask.datatype = "ip4addr"
s:taboption("advanced", DynamicList, "dhcp_option", translate("DHCP-Options"),
translate("Define additional DHCP options, for example \"<code>6,192.168.2.1," ..
"192.168.2.2</code>\" which advertises different DNS servers to clients."))
for i, n in ipairs(s.children) do
if n ~= ignore then
n:depends("ignore", "")
end
end
o = s:taboption("ipv6", ListValue, "ra", translate("Router Advertisement-Service"))
o:value("", translate("disabled"))
o:value("server", translate("server mode"))
o:value("relay", translate("relay mode"))
o:value("hybrid", translate("hybrid mode"))
o = s:taboption("ipv6", ListValue, "dhcpv6", translate("DHCPv6-Service"))
o:value("", translate("disabled"))
o:value("server", translate("server mode"))
o:value("relay", translate("relay mode"))
o:value("hybrid", translate("hybrid mode"))
o = s:taboption("ipv6", ListValue, "ndp", translate("NDP-Proxy"))
o:value("", translate("disabled"))
o:value("relay", translate("relay mode"))
o:value("hybrid", translate("hybrid mode"))
o = s:taboption("ipv6", ListValue, "ra_management", translate("DHCPv6-Mode"))
o:value("", translate("stateless"))
o:value("1", translate("stateless + stateful"))
o:value("2", translate("stateful-only"))
o:depends("dhcpv6", "server")
o:depends("dhcpv6", "hybrid")
o.default = "1"
o = s:taboption("ipv6", Flag, "ra_default", translate("Always announce default router"),
translate("Announce as default router even if no public prefix is available."))
o:depends("ra", "server")
o:depends("ra", "hybrid")
s:taboption("ipv6", DynamicList, "dns", translate("Announced DNS servers"))
s:taboption("ipv6", DynamicList, "domain", translate("Announced DNS domains"))
else
m2 = nil
end
end
return m, m2
| gpl-2.0 |
icplus/OP-SDK | package/ramips/ui/luci-mtk/src/applications/luci-freifunk-widgets/luasrc/controller/freifunk/widgets.lua | 78 | 1124 | --[[
LuCI - Lua Configuration Interface
Copyright 2012 Manuel Munz <freifunk at somakoma de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local require = require
module "luci.controller.freifunk.widgets"
function index()
local page = node("admin", "freifunk", "widgets")
page.target = cbi("freifunk/widgets/widgets_overview")
page.title = _("Widgets")
page.i18n = "widgets"
page.order = 30
local page = node("admin", "freifunk", "widgets", "widget")
page.target = cbi("freifunk/widgets/widget")
page.leaf = true
local page = node("freifunk", "search_redirect")
page.target = call("search_redirect")
page.leaf = true
end
function search_redirect()
local dsp = require "luci.dispatcher"
local http = require "luci.http"
local engine = http.formvalue("engine")
local searchterms = http.formvalue("searchterms") or ""
if engine then
http.redirect(engine .. searchterms)
else
http.redirect(dsp.build_url())
end
end
| gpl-2.0 |
EnjoyHacking/nn | CosineEmbeddingCriterion.lua | 23 | 3849 | local CosineEmbeddingCriterion, parent = torch.class('nn.CosineEmbeddingCriterion', 'nn.Criterion')
function CosineEmbeddingCriterion:__init(margin)
parent.__init(self)
margin = margin or 0
self.margin = margin
self.gradInput = {torch.Tensor(), torch.Tensor()}
self.sizeAverage = true
end
function CosineEmbeddingCriterion:updateOutput(input,y)
local input1, input2 = input[1], input[2]
-- keep backward compatibility
if type(y) == 'number' then
self._y = self._y or input1.new(1)
self._y[1] = y
y = self._y
end
if input1:dim() == 1 then
input1 = input1:view(1,-1)
input2 = input2:view(1,-1)
end
if not self.buffer then
self.buffer = input1.new()
self.w1 = input1.new()
self.w22 = input1.new()
self.w = input1.new()
self.w32 = input1.new()
self._outputs = input1.new()
-- comparison operators behave differently from cuda/c implementations
if input1:type() == 'torch.CudaTensor' then
self._idx = input1.new()
else
self._idx = torch.ByteTensor()
end
end
self.buffer:cmul(input1,input2)
self.w1:sum(self.buffer,2)
local epsilon = 1e-12
self.buffer:cmul(input1,input1)
self.w22:sum(self.buffer,2):add(epsilon)
-- self._outputs is also used as a temporary buffer
self._outputs:resizeAs(self.w22):fill(1)
self.w22:cdiv(self._outputs, self.w22)
self.w:resizeAs(self.w22):copy(self.w22)
self.buffer:cmul(input2,input2)
self.w32:sum(self.buffer,2):add(epsilon)
self.w32:cdiv(self._outputs, self.w32)
self.w:cmul(self.w32)
self.w:sqrt()
self._outputs:cmul(self.w1,self.w)
self._outputs = self._outputs:select(2,1)
y.eq(self._idx,y,-1)
self._outputs[self._idx] = self._outputs[self._idx]:add(-self.margin):cmax(0)
y.eq(self._idx,y,1)
self._outputs[self._idx] = self._outputs[self._idx]:mul(-1):add(1)
self.output = self._outputs:sum()
if self.sizeAverage then
self.output = self.output/y:size(1)
end
return self.output
end
function CosineEmbeddingCriterion:updateGradInput(input, y)
local v1 = input[1]
local v2 = input[2]
local not_batch = false
-- keep backward compatibility
if type(y) == 'number' then
self._y = self._y or input1.new(1)
self._y[1] = y
y = self._y
end
if v1:dim() == 1 then
v1 = v1:view(1,-1)
v2 = v2:view(1,-1)
not_batch = true
end
local gw1 = self.gradInput[1]
local gw2 = self.gradInput[2]
gw1:resizeAs(v1):copy(v2)
gw2:resizeAs(v1):copy(v1)
self.w = self.w:expandAs(v1)
self.buffer:cmul(self.w1,self.w22)
self.buffer = self.buffer:expandAs(v1)
gw1:addcmul(-1,self.buffer,v1)
gw1:cmul(self.w)
self.buffer:cmul(self.w1,self.w32)
self.buffer = self.buffer:expandAs(v1)
gw2:addcmul(-1,self.buffer,v2)
gw2:cmul(self.w)
-- self._idx = self._outputs <= 0
y.le(self._idx,self._outputs,0)
self._idx = self._idx:view(-1,1):expand(gw1:size())
gw1[self._idx] = 0
gw2[self._idx] = 0
y.eq(self._idx,y,1)
self._idx = self._idx:view(-1,1):expand(gw2:size())
gw1[self._idx] = gw1[self._idx]:mul(-1)
gw2[self._idx] = gw2[self._idx]:mul(-1)
if self.sizeAverage then
gw1:div(y:size(1))
gw2:div(y:size(1))
end
if not_batch then
self.gradInput[1] = gw1:select(1,1)
self.gradInput[2] = gw2:select(1,1)
end
-- fix for torch bug
-- https://github.com/torch/torch7/issues/289
self.buffer:resize()
return self.gradInput
end
function CosineEmbeddingCriterion:type(type)
self._idx = nil
parent.type(self,type)
-- comparison operators behave differently from cuda/c implementations
if type == 'torch.CudaTensor' then
self._idx = torch.CudaTensor()
else
self._idx = torch.ByteTensor()
end
return self
end
| bsd-3-clause |
ngeiswei/ardour | share/scripts/normalize_all_tracks.lua | 6 | 1784 | ardour { ["type"] = "EditorAction",
name = "Normalize All Tracks",
license = "MIT",
author = "Ardour Team",
description = [[Normalize all regions using a common gain-factor per track.]]
}
function factory () return function ()
-- target values -- TODO: use a LuaDialog.Dialog and ask..
local target_peak = -1 --dBFS
local target_rms = -18 --dBFS/RMS
-- prepare undo operation
Session:begin_reversible_command ("Normalize Tracks")
local add_undo = false -- keep track if something has changed
-- loop over all tracks in the session
for track in Session:get_tracks():iter() do
local norm = 0 -- per track gain
-- loop over all regions on track
for r in track:to_track():playlist():region_list():iter() do
-- test if it's an audio region
local ar = r:to_audioregion ()
if ar:isnil () then goto next end
local peak = ar:maximum_amplitude (nil)
local rms = ar:rms (nil)
-- check if region is silent
if (peak > 0) then
local f_rms = rms / 10 ^ (.05 * target_rms)
local f_peak = peak / 10 ^ (.05 * target_peak)
local tg = (f_peak > f_rms) and f_peak or f_rms -- max (f_peak, f_rms)
norm = (tg > norm) and tg or norm -- max (tg, norm)
end
::next::
end
-- apply same gain to all regions on track
if norm > 0 then
for r in track:to_track():playlist():region_list():iter() do
local ar = r:to_audioregion ()
if ar:isnil () then goto skip end
ar:to_stateful ():clear_changes ()
ar:set_scale_amplitude (1 / norm)
add_undo = true
::skip::
end
end
end
-- all done. now commit the combined undo operation
if add_undo then
-- the 'nil' command here means to use all collected diffs
Session:commit_reversible_command (nil)
else
Session:abort_reversible_command ()
end
end end
| gpl-2.0 |
RhenaudTheLukark/CreateYourFrisk | Assets/Mods/Examples/Lua/Monsters/poseurIntroAndLaunchMusic.lua | 1 | 1496 | comments = {"Smells like the work\rof an enemy stand.", "Poseur is posing like his\rlife depends on it.", "Poseur's limbs shouldn't be\rmoving in this way."}
commands = {"Act 1", "Act 2", "Act 3"}
randomdialogue = {"Check\nit\nout."}
sprite = "poseur" --Always PNG. Extension is added automatically.
name = "Poseur"
hp = 60
atk = 4
def = 1
check = "Do not insult its hair."
dialogbubble = "right" -- See documentation for what bubbles you have available.
canspare = false
xp = 10
gold = 20
posecount = 0
-- Function launched inside the intro when the music is resumed.
function LaunchMusic()
Audio.Unpause()
end
-- Happens after the slash animation but before the animation.
function HandleAttack(attackstatus)
if attackstatus == -1 then
-- player pressed fight but didn't press Z afterwards
currentdialogue = {"Do\nno\nharm."}
else
-- player did actually attack
if hp > 30 then
currentdialogue = {"You're\nstrong!"}
else
currentdialogue = {"Too\nstrong\n..."}
end
end
end
-- This handles the commands; all-caps versions of the commands list you have above.
function HandleCustomCommand(command)
if command == "ACT 1" then
currentdialogue = {"Selected\nAct 1."}
elseif command == "ACT 2" then
currentdialogue = {"Selected\nAct 2."}
elseif command == "ACT 3" then
currentdialogue = {"Selected\nAct 3."}
end
BattleDialog({"You selected " .. command .. "."})
end | gpl-3.0 |
nasomi/darkstar | scripts/zones/Bastok_Markets_[S]/npcs/Pagdako.lua | 31 | 1385 | -----------------------------------
-- Area: Bastok Markets (S)
-- NPC: Pagdako
-- Quest NPC
-- pos -200 -6 -93
-----------------------------------
package.loaded["scripts/zones/Bastok_Markets_[S]/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Bastok_Markets_[S]/TextIDs");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(CRYSTAL_WAR,FIRES_OF_DISCONTENT) == QUEST_ACCEPTED) then
if (player:getVar("FiresOfDiscProg") == 0) then
player:startEvent(0x007A);
else
player:startEvent(0x007B);
end
else
player:startEvent(0x006A);
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 == 0x007A) then
player:setVar("FiresOfDiscProg",1);
end
end;
| gpl-3.0 |
Hello23-Ygopro/ygopro-ds | expansions/script/c27002048.lua | 1 | 1511 | --BT2-042 Trunks, The Constant Hope
local ds=require "expansions.utility_dbscg"
local scard,sid=ds.GetID()
function scard.initial_effect(c)
ds.EnableBattleAttribute(c)
ds.AddSetcode(c,CHARACTER_TRUNKS_FUTURE,SPECIAL_TRAIT_SAIYAN,SPECIAL_TRAIT_EARTHLING)
ds.AddPlayProcedure(c,COLOR_BLUE,2,4)
--evolve
ds.EnableEvolve(c,aux.FilterBoolFunction(Card.IsCharacter,CHARACTER_TRUNKS_FUTURE),COLOR_BLUE,2,3)
--triple strike
ds.EnableTripleStrike(c,scard.tscon)
--to combo
ds.AddSingleAutoAttack(c,0,nil,scard.tctg,scard.tcop,DS_EFFECT_FLAG_CARD_CHOOSE)
ds.AddSingleAutoBeBattleTarget(c,0,nil,scard.tctg,scard.tcop,DS_EFFECT_FLAG_CARD_CHOOSE)
end
scard.dragon_ball_super_card=true
scard.combo_cost=1
--triple strike
function scard.tscon(e)
local tp=e:GetHandlerPlayer()
return (Duel.IsExistingMatchingCard(ds.BattleAreaFilter(Card.IsCharacter),tp,DS_LOCATION_BATTLE,0,1,nil,CHARACTER_SON_GOKU)
and Duel.IsExistingMatchingCard(ds.BattleAreaFilter(Card.IsCharacter),tp,DS_LOCATION_BATTLE,0,1,nil,CHARACTER_VEGETA))
or (Duel.IsExistingMatchingCard(ds.DropAreaFilter(Card.IsCharacter),tp,DS_LOCATION_DROP,0,1,nil,CHARACTER_SON_GOKU)
and Duel.IsExistingMatchingCard(ds.DropAreaFilter(Card.IsCharacter),tp,DS_LOCATION_DROP,0,1,nil,CHARACTER_VEGETA))
end
--to combo
function scard.tcfilter(c)
return c:IsBattle() and c:IsColor(COLOR_BLUE)
end
scard.tctg=ds.ChooseCardFunction(PLAYER_PLAYER,ds.DropAreaFilter(scard.tcfilter),DS_LOCATION_DROP,0,0,1,DS_HINTMSG_TOCOMBO)
scard.tcop=ds.ChooseSendtoComboOperation
| gpl-3.0 |
nasomi/darkstar | scripts/globals/mobskills/Tribulation.lua | 18 | 1128 | ---------------------------------------------
-- Tribulation
--
-- Description: Inflicts Bio and blinds all targets in an area of effect.
-- Type: Enfeebling
-- Utsusemi/Blink absorb: Ignores shadows
-- Range: AoE
-- Notes: Bio effect can take away up to 39/tick.
---------------------------------------------
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 blinded = false;
local bio = false;
blinded = MobStatusEffectMove(mob, target, EFFECT_BLINDNESS, 20, 0, 120);
bio = MobStatusEffectMove(mob, target, EFFECT_BIO, 39, 0, 120);
skill:setMsg(MSG_ENFEEB_IS);
-- display blind first, else bio
if (blinded == MSG_ENFEEB_IS) then
typeEffect = EFFECT_BLINDNESS;
elseif (bio == MSG_ENFEEB_IS) then
typeEffect = EFFECT_BIO;
else
skill:setMsg(MSG_MISS);
end
return typeEffect;
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Port_Windurst/npcs/Yaman-Hachuman.lua | 19 | 1715 | -----------------------------------
-- Area: Port Windurst
-- NPC: Yaman-Hachuman
-- Type: Standard NPC
-- Involved in Quests: Wonder Wands
-- @pos -101.209 -4.25 110.886 240
-----------------------------------
package.loaded["scripts/zones/Port_Windurst/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Port_Windurst/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local WonderWands = player:getQuestStatus(WINDURST,WONDER_WANDS);
local WildcatWindurst = player:getVar("WildcatWindurst");
if (player:getQuestStatus(WINDURST,LURE_OF_THE_WILDCAT_WINDURST) == QUEST_ACCEPTED and player:getMaskBit(WildcatWindurst,16) == false) then
player:startEvent(0x0270);
elseif (WonderWands == QUEST_ACCEPTED) then
player:startEvent(0x0100,0,0,0,17061);
elseif (WonderWands == QUEST_COMPLETED) then
player:startEvent(0x010c);
else
player:startEvent(0xe9);
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 == 0x0270) then
player:setMaskBit(player:getVar("WildcatWindurst"),"WildcatWindurst",16,true);
end
end;
| gpl-3.0 |
srush/OpenNMT | tools/utils/BPE.lua | 1 | 3331 | local unicode = require 'tools.utils.unicode'
local BPE = torch.class('BPE')
function BPE:__init(codesfile_path)
self.split = string.split
-- to be able to run the code without torch
if not self.split then
self.split = function(t, sep)
local fields = {}
local pattern = string.format("([^%s]+)", sep)
t:gsub(pattern, function(c) fields[#fields+1] = c end)
return fields
end
end
self.codes = {}
local f = assert(io.open(codesfile_path, "r"))
local t = f:read("*line")
local i = 1
while not(t == nil) do
local l = self.split(t, " ")
if #l == 2 then
self.codes[t] = i
i = i + 1
end
t=f:read("*line")
end
end
local function getPairs(word)
local pairs = {}
for i = 1, #word-1, 1 do
table.insert(pairs, word[i] .. ' ' .. word[i+1])
end
return pairs
end
local function str2word(l)
local word = {}
for _, c in unicode.utf8_iter(l) do
table.insert(word, c)
end
return word
end
function BPE:minPair(pairsTable)
local mintmp = 100000
local minpair = ''
for i = 1, #pairsTable, 1 do
local pair_cur = pairsTable[i]
if self.codes[pair_cur] then
local scoretmp = self.codes[pair_cur]
if (scoretmp < mintmp) then
mintmp = scoretmp
minpair = pair_cur
end
end
end
return minpair
end
function BPE:encode(l)
local word = str2word(l)
if #word == 1 then
return word
end
table.insert(word, '</w>')
local pairs = getPairs(word)
while true do
local bigram = self:minPair(pairs)
if bigram == '' then break end
bigram = self.split(bigram, ' ')
local new_word = {}
local merge = false
for _, xx in ipairs(word) do
if (merge) then
if xx == bigram[2] then
table.insert(new_word, bigram[1] .. bigram[2])
merge = false
elseif xx == bigram[1] then
table.insert(new_word, bigram[1])
else
table.insert(new_word, bigram[1])
table.insert(new_word, xx)
merge = false
end
else
if bigram[1] == xx then
merge = true
else
table.insert(new_word, xx)
end
end
end
word = new_word
if #word == 1 then
break
else
pairs = getPairs(word)
end
end
if word[#word] == '</w>' then
table.remove(word, #word)
elseif string.sub(word[#word],-string.len('</w>')) == '</w>' then
word[#word] = string.sub(word[#word], 1, -string.len('</w>')-1)
end
return word
end
function BPE:segment(tokens, separator)
local bpeSegment = {}
for i=1, #tokens do
local token = tokens[i]
local left_sep = false
local right_sep = false
if token:sub(1, #separator) == separator then
token = token:sub(#separator + 1)
left_sep = true
end
if token:sub(-#separator, -1) == separator then
token = token:sub(1, -#separator-1)
right_sep = true
end
local bpeTokens = self:encode(token)
if left_sep then
bpeTokens[1] = separator .. bpeTokens[1]
end
if right_sep then
bpeTokens[#bpeTokens] = bpeTokens[#bpeTokens] .. separator
end
for j=1, #bpeTokens-1 do
table.insert(bpeSegment, bpeTokens[j] .. separator)
end
table.insert(bpeSegment, bpeTokens[#bpeTokens])
end
return bpeSegment
end
return BPE
| mit |
hqren/Atlas | lib/ro-pooling.lua | 40 | 7080 | --[[ $%BEGINLICENSE%$
Copyright (c) 2008, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
---
-- a flexible statement based load balancer with connection pooling
--
-- * build a connection pool of min_idle_connections for each backend and
-- maintain its size
-- * reusing a server-side connection when it is idling
--
--- config
--
-- connection pool
local min_idle_connections = 4
local max_idle_connections = 8
-- debug
local is_debug = false
--- end of config
---
-- read/write splitting sends all non-transactional SELECTs to the slaves
--
-- is_in_transaction tracks the state of the transactions
local is_in_transaction = 0
---
-- get a connection to a backend
--
-- as long as we don't have enough connections in the pool, create new connections
--
function connect_server()
-- make sure that we connect to each backend at least ones to
-- keep the connections to the servers alive
--
-- on read_query we can switch the backends again to another backend
if is_debug then
print()
print("[connect_server] ")
end
local least_idle_conns_ndx = 0
local least_idle_conns = 0
for i = 1, #proxy.global.backends do
local s = proxy.global.backends[i]
local pool = s.pool -- we don't have a username yet, try to find a connections which is idling
local cur_idle = pool.users[""].cur_idle_connections
if is_debug then
print(" [".. i .."].connected_clients = " .. s.connected_clients)
print(" [".. i .."].idling_connections = " .. cur_idle)
print(" [".. i .."].type = " .. s.type)
print(" [".. i .."].state = " .. s.state)
end
if s.state ~= proxy.BACKEND_STATE_DOWN then
-- try to connect to each backend once at least
if cur_idle == 0 then
proxy.connection.backend_ndx = i
if is_debug then
print(" [".. i .."] open new connection")
end
return
end
-- try to open at least min_idle_connections
if least_idle_conns_ndx == 0 or
( cur_idle < min_idle_connections and
cur_idle < least_idle_conns ) then
least_idle_conns_ndx = i
least_idle_conns = s.idling_connections
end
end
end
if least_idle_conns_ndx > 0 then
proxy.connection.backend_ndx = least_idle_conns_ndx
end
if proxy.connection.backend_ndx > 0 then
local s = proxy.global.backends[proxy.connection.backend_ndx]
local pool = s.pool -- we don't have a username yet, try to find a connections which is idling
local cur_idle = pool.users[""].cur_idle_connections
if cur_idle >= min_idle_connections then
-- we have 4 idling connections in the pool, that's good enough
if is_debug then
print(" using pooled connection from: " .. proxy.connection.backend_ndx)
end
return proxy.PROXY_IGNORE_RESULT
end
end
if is_debug then
print(" opening new connection on: " .. proxy.connection.backend_ndx)
end
-- open a new connection
end
---
-- put the successfully authed connection into the connection pool
--
-- @param auth the context information for the auth
--
-- auth.packet is the packet
function read_auth_result( auth )
if auth.packet:byte() == proxy.MYSQLD_PACKET_OK then
-- auth was fine, disconnect from the server
proxy.connection.backend_ndx = 0
elseif auth.packet:byte() == proxy.MYSQLD_PACKET_EOF then
-- we received either a
--
-- * MYSQLD_PACKET_ERR and the auth failed or
-- * MYSQLD_PACKET_EOF which means a OLD PASSWORD (4.0) was sent
print("(read_auth_result) ... not ok yet");
elseif auth.packet:byte() == proxy.MYSQLD_PACKET_ERR then
-- auth failed
end
end
---
-- read/write splitting
function read_query( packet )
if is_debug then
print("[read_query]")
print(" authed backend = " .. proxy.connection.backend_ndx)
print(" used db = " .. proxy.connection.client.default_db)
end
if packet:byte() == proxy.COM_QUIT then
-- don't send COM_QUIT to the backend. We manage the connection
-- in all aspects.
proxy.response = {
type = proxy.MYSQLD_PACKET_OK,
}
return proxy.PROXY_SEND_RESULT
end
if proxy.connection.backend_ndx == 0 then
-- we don't have a backend right now
--
-- let's pick a master as a good default
for i = 1, #proxy.global.backends do
local s = proxy.global.backends[i]
local pool = s.pool -- we don't have a username yet, try to find a connections which is idling
local cur_idle = pool.users[proxy.connection.client.username].cur_idle_connections
if cur_idle > 0 and
s.state ~= proxy.BACKEND_STATE_DOWN and
s.type == proxy.BACKEND_TYPE_RW then
proxy.connection.backend_ndx = i
break
end
end
end
if true or proxy.connection.client.default_db and proxy.connection.client.default_db ~= proxy.connection.server.default_db then
-- sync the client-side default_db with the server-side default_db
proxy.queries:append(2, string.char(proxy.COM_INIT_DB) .. proxy.connection.client.default_db, { resultset_is_needed = true })
end
proxy.queries:append(1, packet)
return proxy.PROXY_SEND_QUERY
end
---
-- as long as we are in a transaction keep the connection
-- otherwise release it so another client can use it
function read_query_result( inj )
local res = assert(inj.resultset)
local flags = res.flags
if inj.id ~= 1 then
-- ignore the result of the USE <default_db>
return proxy.PROXY_IGNORE_RESULT
end
is_in_transaction = flags.in_trans
if not is_in_transaction then
-- release the backend
proxy.connection.backend_ndx = 0
end
end
---
-- close the connections if we have enough connections in the pool
--
-- @return nil - close connection
-- IGNORE_RESULT - store connection in the pool
function disconnect_client()
if is_debug then
print("[disconnect_client]")
end
if proxy.connection.backend_ndx == 0 then
-- currently we don't have a server backend assigned
--
-- pick a server which has too many idling connections and close one
for i = 1, #proxy.global.backends do
local s = proxy.global.backends[i]
local pool = s.pool -- we don't have a username yet, try to find a connections which is idling
local cur_idle = pool.users[proxy.connection.client.username].cur_idle_connections
if s.state ~= proxy.BACKEND_STATE_DOWN and
cur_idle > max_idle_connections then
-- try to disconnect a backend
proxy.connection.backend_ndx = i
if is_debug then
print(" [".. i .."] closing connection, idling: " .. cur_idle)
end
return
end
end
end
end
| gpl-2.0 |
thesabbir/luci | applications/luci-app-statistics/luasrc/model/cbi/luci_statistics/collectd.lua | 68 | 2082 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
require("luci.sys")
m = Map("luci_statistics",
translate("Collectd Settings"),
translate(
"Collectd is a small daemon for collecting data from " ..
"various sources through different plugins. On this page " ..
"you can change general settings for the collectd daemon."
))
-- general config section
s = m:section( NamedSection, "collectd", "luci_statistics" )
-- general.hostname (Hostname)
hostname = s:option( Value, "Hostname", translate("Hostname") )
hostname.default = luci.sys.hostname()
hostname.optional = true
-- general.basedir (BaseDir)
basedir = s:option( Value, "BaseDir", translate("Base Directory") )
basedir.default = "/var/run/collectd"
-- general.include (Include)
include = s:option( Value, "Include", translate("Directory for sub-configurations") )
include.default = "/etc/collectd/conf.d/*.conf"
-- general.plugindir (PluginDir)
plugindir = s:option( Value, "PluginDir", translate("Directory for collectd plugins") )
plugindir.default = "/usr/lib/collectd/"
-- general.pidfile (PIDFile)
pidfile = s:option( Value, "PIDFile", translate("Used PID file") )
pidfile.default = "/var/run/collectd.pid"
-- general.typesdb (TypesDB)
typesdb = s:option( Value, "TypesDB", translate("Datasets definition file") )
typesdb.default = "/etc/collectd/types.db"
-- general.interval (Interval)
interval = s:option( Value, "Interval", translate("Data collection interval"), translate("Seconds") )
interval.default = 60
interval.isnumber = true
-- general.readthreads (ReadThreads)
readthreads = s:option( Value, "ReadThreads", translate("Number of threads for data collection") )
readthreads.default = 5
readthreads.isnumber = true
-- general.fqdnlookup (FQDNLookup)
fqdnlookup = s:option( Flag, "FQDNLookup", translate("Try to lookup fully qualified hostname") )
fqdnlookup.enabled = "true"
fqdnlookup.disabled = "false"
fqdnlookup.default = "false"
fqdnlookup.optional = true
fqdnlookup:depends( "Hostname", "" )
return m
| apache-2.0 |
iassael/learning-to-communicate | code/game/ColorDigit.lua | 1 | 4430 | require 'torch'
local class = require 'class'
local log = require 'include.log'
local kwargs = require 'include.kwargs'
local util = require 'include.util'
local ColorDigit = class('ColorDigit')
function ColorDigit:__init(opt)
self.opt = opt
self.step_counter = 1
-- Preprocess data
local dataset = (require 'mnist').traindataset()
local data = {}
local lookup = {}
for i = 1, dataset.size do
-- Shift 0 class
local y = dataset[i].y + 1
-- Create array
if not data[y] then
data[y] = {}
end
-- Move data
data[y][#data[y] + 1] = {
x = dataset[i].x,
y = y
}
lookup[i] = y
end
self.mnist = data
self.mnist.lookup = lookup
-- Rewards
self.reward = torch.zeros(self.opt.bs)
self.terminal = torch.zeros(self.opt.bs)
-- Spawn new game
self:reset()
end
function ColorDigit:loadDigit()
-- Pick random digit and color
local color_id = torch.zeros(self.opt.bs)
local number = torch.zeros(self.opt.bs)
local x = torch.zeros(self.opt.bs, self.opt.game_colors, self.opt.game_dim, self.opt.game_dim):type(self.opt.dtype)
for b = 1, self.opt.bs do
-- Pick number
local num
if self.opt.game_use_mnist == 1 then
local index = torch.random(#self.mnist.lookup)
num = self.mnist.lookup[index]
elseif torch.uniform() < self.opt.game_bias then
num = 1
else
num = torch.random(10)
end
number[b] = num
-- Pick color
color_id[b] = torch.random(self.opt.game_colors)
-- Pick dataset id
local id = torch.random(#self.mnist[num])
x[b][color_id[b]] = self.mnist[num][id].x
end
return { x, color_id, number }
end
function ColorDigit:reset()
-- Load images
self.state = { self:loadDigit(), self:loadDigit() }
-- Reset rewards
self.reward:zero()
self.terminal:zero()
-- Reset counter
self.step_counter = 1
return self
end
function ColorDigit:getActionRange()
return nil
end
function ColorDigit:getCommLimited()
return nil
end
function ColorDigit:getReward(a)
local color_1 = self.state[1][2]
local color_2 = self.state[2][2]
local digit_1 = self.state[1][3]
local digit_2 = self.state[2][3]
local reward = torch.zeros(self.opt.bs, self.opt.game_nagents)
for b = 1, self.opt.bs do
if self.opt.game_level == "extra_hard_local" then
if a[b][2] <= self.opt.game_action_space and self.step_counter > 1 then
reward[b] = 2 * (-1) ^ (digit_1[b] + a[b][2] + color_2[b]) + (-1) ^ (digit_2[b] + a[b][2] + color_1[b])
end
if a[b][1] <= self.opt.game_action_space and self.step_counter > 1 then
reward[b] = reward[b] + 2 * (-1) ^ (digit_2[b] + a[b][1] + color_1[b]) + (-1) ^ (digit_1[b] + a[b][1] + color_2[b])
end
elseif self.opt.game_level == "many_bits" then
if a[b][1] <= self.opt.game_action_space and self.step_counter == self.opt.nsteps then
if digit_2[b] == a[b][1] then
reward[b] = reward[b] + 0.5
end
end
if a[b][2] <= self.opt.game_action_space and self.step_counter == self.opt.nsteps then
if digit_1[b] == a[b][2] then
reward[b] = reward[b] + 0.5
end
end
else
error("[ColorDigit] wrong level")
end
end
local reward_coop = torch.zeros(self.opt.bs, self.opt.game_nagents)
reward_coop[{ {}, { 2 } }] = (reward[{ {}, { 2 } }] + reward[{ {}, { 1 } }] * self.opt.game_coop) / (1 + self.opt.game_coop)
reward_coop[{ {}, { 1 } }] = (reward[{ {}, { 1 } }] + reward[{ {}, { 2 } }] * self.opt.game_coop) / (1 + self.opt.game_coop)
return reward_coop
end
function ColorDigit:step(a)
local reward, terminal
reward = self:getReward(a)
if self.step_counter == self.opt.nsteps then
self.terminal:fill(1)
end
self.step_counter = self.step_counter + 1
return reward, self.terminal:clone()
end
function ColorDigit:getState()
if self.opt.game_use_digits == 1 then
return { self.state[1][3], self.state[2][3] }
else
return { self.state[1][1], self.state[2][1] }
end
end
return ColorDigit
| apache-2.0 |
nasomi/darkstar | scripts/globals/items/plate_of_sole_sushi_+1.lua | 14 | 1750 | -----------------------------------------
-- ID: 5163
-- Item: plate_of_sole_sushi_+1
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 20
-- Strength 5
-- Dexterity 6
-- Accuracy % 16
-- Ranged ACC % 16
-- Sleep Resist 5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,5163);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_STR, 5);
target:addMod(MOD_DEX, 6);
target:addMod(MOD_ACCP, 16);
target:addMod(MOD_FOOD_ACC_CAP, 76);
target:addMod(MOD_RACCP, 16);
target:addMod(MOD_FOOD_RACC_CAP, 76);
target:addMod(MOD_SLEEPRES, 5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_STR, 5);
target:delMod(MOD_DEX, 6);
target:delMod(MOD_ACCP, 16);
target:delMod(MOD_FOOD_ACC_CAP, 76);
target:delMod(MOD_RACCP, 16);
target:delMod(MOD_FOOD_RACC_CAP, 76);
target:delMod(MOD_SLEEPRES, 5);
end;
| gpl-3.0 |
Ingenious-Gaming/Starfall | lua/weapons/gmod_tool/stools/starfall_processor.lua | 1 | 6342 | TOOL.Category = "Chips, Gates"
TOOL.Name = "Starfall - Processor"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.Tab = "Wire"
-- ------------------------------- Sending / Recieving ------------------------------- --
include( "starfall/sflib.lua" )
TOOL.ClientConVar[ "Model" ] = "models/spacecode/sfchip.mdl"
cleanup.Register( "starfall_processor" )
if SERVER then
CreateConVar( "sbox_maxstarfall_processor", 10, { FCVAR_REPLICATED, FCVAR_NOTIFY, FCVAR_ARCHIVE } )
else
language.Add( "Tool.starfall_processor.name", "Starfall - Processor" )
language.Add( "Tool.starfall_processor.desc", "Spawns a starfall processor (Press shift+f to switch to screen and back again)" )
language.Add( "Tool.starfall_processor.0", "Primary: Spawns a processor / uploads code, Secondary: Opens editor" )
language.Add( "sboxlimit_starfall_processor", "You've hit the Starfall processor limit!" )
language.Add( "undone_Starfall Processor", "Undone Starfall Processor" )
end
function TOOL:LeftClick ( trace )
if not trace.HitPos then return false end
if trace.Entity:IsPlayer() then return false end
if CLIENT then return true end
local ply = self:GetOwner()
if trace.Entity:IsValid() and trace.Entity:GetClass() == "starfall_processor" then
local ent = trace.Entity
if not SF.RequestCode( ply, function ( mainfile, files )
if not mainfile then return end
if not IsValid( ent ) then return end -- Probably removed during transfer
ent:Compile( files, mainfile )
end ) then
SF.AddNotify( ply, "Cannot upload SF code, please wait for the current upload to finish.", NOTIFY_ERROR, 7, NOTIFYSOUND_ERROR1 )
end
return true
end
self:SetStage( 0 )
local model = self:GetClientInfo( "Model" )
if not self:GetSWEP():CheckLimit( "starfall_processor" ) then return false end
if not SF.RequestCode( ply, function ( mainfile, files )
if not mainfile then return end
local ppdata = {}
SF.Preprocessor.ParseDirectives( mainfile, files[ mainfile ], {}, ppdata )
if ppdata.models and ppdata.models[ mainfile ] and ppdata.models[ mainfile ] ~= "" then
model = ppdata.models[ mainfile ]
end
local sf = SF.MakeSF( ply, "starfall_processor", trace, model )
sf:Compile( files, mainfile )
end ) then
SF.AddNotify( ply, "Cannot upload SF code, please wait for the current upload to finish.", NOTIFY_ERROR, 7, NOTIFYSOUND_ERROR1 )
end
return true
end
function TOOL:RightClick ( trace )
if SERVER then self:GetOwner():SendLua( "SF.Editor.open()" ) end
return false
end
function TOOL:Reload ( trace )
return false
end
function TOOL:DrawHUD () end
function TOOL:Think () end
if CLIENT then
local function get_active_tool ( ply, tool )
-- find toolgun
local activeWep = ply:GetActiveWeapon()
if not IsValid( activeWep ) or activeWep:GetClass() ~= "gmod_tool" or activeWep.Mode ~= tool then return end
return activeWep:GetToolObject( tool )
end
local modelHologram = nil
hook.Add( "Think", "SF_Update_modelHologram_Processor", function ()
if modelHologram == nil or not modelHologram:IsValid() then
modelHologram = ents.CreateClientProp()
modelHologram:SetRenderMode( RENDERMODE_TRANSALPHA )
modelHologram:SetColor( Color( 255, 255, 255, 170 ) )
modelHologram:Spawn()
end
local tool = get_active_tool( LocalPlayer(), "starfall_processor" )
if tool then
local model = tool.ClientConVar[ "HologramModel" ] or tool:GetClientInfo( "Model" )
if model and model ~= "" and modelHologram:GetModel() ~= model then
modelHologram:SetModel( model )
end
local min = modelHologram:OBBMins()
local trace = LocalPlayer():GetEyeTrace()
if trace.Hit and not ( IsValid( trace.Entity ) and ( trace.Entity:IsPlayer() or trace.Entity:GetClass() == "starfall_processor" ) ) then
modelHologram:SetPos( trace.HitPos - trace.HitNormal * min.z )
modelHologram:SetAngles( trace.HitNormal:Angle() + Angle( 90, 0, 0 ) )
modelHologram:SetNoDraw( false )
else
modelHologram:SetNoDraw( true )
end
else
modelHologram:SetNoDraw( true )
end
end )
hook.Add( "PlayerBindPress", "wire_adv", function ( ply, bind, pressed )
if not pressed then return end
if bind == "impulse 100" and ply:KeyDown( IN_SPEED ) then
local self = get_active_tool( ply, "starfall_processor" )
if not self then
self = get_active_tool( ply, "starfall_screen" )
if not self then return end
RunConsoleCommand( "gmod_tool", "starfall_processor" ) -- switch back to processor
return true
end
RunConsoleCommand( "gmod_tool", "starfall_screen" ) -- switch to screen
return true
end
end )
local lastclick = CurTime()
local function GotoDocs ( button )
gui.OpenURL( "http://sf.inp.io" ) -- old one: http://colonelthirtytwo.net/sfdoc/
end
function TOOL.BuildCPanel ( panel )
panel:AddControl( "Header", { Text = "#Tool.starfall_processor.name", Description = "#Tool.starfall_processor.desc" } )
local gateModels = list.Get( "Starfall_gate_Models" )
table.Merge( gateModels, list.Get( "Wire_gate_Models" ) )
local modelPanel = WireDermaExts.ModelSelect( panel, "starfall_processor_Model", gateModels, 2 )
panel:AddControl( "Label", { Text = "" } )
local docbutton = vgui.Create( "DButton" , panel )
panel:AddPanel( docbutton )
docbutton:SetText( "Starfall Documentation" )
docbutton.DoClick = GotoDocs
local filebrowser = vgui.Create( "StarfallFileBrowser" )
panel:AddPanel( filebrowser )
filebrowser.tree:setup( "starfall" )
filebrowser:SetSize( 235,400 )
local lastClick = 0
filebrowser.tree.DoClick = function ( self, node )
if CurTime() <= lastClick + 0.5 then
if not node:GetFileName() or string.GetExtensionFromFilename( node:GetFileName() ) ~= "txt" then return end
local fileName = string.gsub( node:GetFileName(), "starfall/", "", 1 )
local code = file.Read( node:GetFileName(), "DATA" )
for k, v in pairs( SF.Editor.getTabHolder().tabs ) do
if v.filename == fileName and v.code == code then
SF.Editor.selectTab( v )
SF.Editor.open()
return
end
end
SF.Editor.addTab( fileName, code )
SF.Editor.open()
end
lastClick = CurTime()
end
local openeditor = vgui.Create( "DButton", panel )
panel:AddPanel( openeditor )
openeditor:SetText( "Open Editor" )
openeditor.DoClick = SF.Editor.open
end
end
| bsd-3-clause |
m13790115/eset | plugins/invite.lua | 1111 | 1195 | do
local function callbackres(extra, success, result) -- Callback for res_user in line 27
local user = 'user#id'..result.id
local chat = 'chat#id'..extra.chatid
if is_banned(result.id, extra.chatid) then -- Ignore bans
send_large_msg(chat, 'User is banned.')
elseif is_gbanned(result.id) then -- Ignore globall bans
send_large_msg(chat, 'User is globaly banned.')
else
chat_add_user(chat, user, ok_cb, false) -- Add user on chat
end
end
function run(msg, matches)
local data = load_data(_config.moderation.data)
if not is_realm(msg) then
if data[tostring(msg.to.id)]['settings']['lock_member'] == 'yes' and not is_admin(msg) then
return 'Group is private.'
end
end
if msg.to.type ~= 'chat' then
return
end
if not is_momod(msg) then
return
end
--if not is_admin(msg) then -- For admins only !
--return 'Only admins can invite.'
--end
local cbres_extra = {chatid = msg.to.id}
local username = matches[1]
local username = username:gsub("@","")
res_user(username, callbackres, cbres_extra)
end
return {
patterns = {
"^[!/]invite (.*)$"
},
run = run
}
end
| gpl-2.0 |
actboy168/YDWE | Development/Component/plugin/w3x2lni/script/core/slk/backend_txtlni.lua | 3 | 2094 |
local function sortpairs(t)
local sort = {}
for k, v in pairs(t) do
sort[#sort+1] = {k, v}
end
table.sort(sort, function (a, b)
return a[1] < b[1]
end)
local n = 1
return function()
local v = sort[n]
if not v then
return
end
n = n + 1
return v[1], v[2]
end
end
local function format_value(value)
if tonumber(value) then
return tostring(value)
elseif type(value) == 'string' then
if value:match '[\n\r]' then
return ('[=[\r\n%s]=]'):format(value)
else
return ('%q'):format(value)
end
end
end
local function maxindex(t)
local i = 0
for k in pairs(t) do
i = math.max(i, k)
end
return i
end
local function write_data(f, k, v)
if k:find '[^%w_]' then
k = ('%q'):format(k)
end
if type(v) == 'table' then
local l = {}
for i = 1, maxindex(v) do
l[i] = format_value(v[i]) or ''
end
if #l == 0 then
return
elseif#l == 1 then
f[#f+1] = ('%s = %s'):format(k, l[1])
else
f[#f+1] = ('%s = {%s}'):format(k, table.concat(l, ', '))
end
else
f[#f+1] = ('%s = %s'):format(k, format_value(v))
end
end
local function is_enable(obj)
for key, value in pairs(obj) do
if key:sub(1, 1) ~= '_' then
if type(value) == 'table' then
if next(value) then
return true
end
else
return true
end
end
end
return false
end
return function (w2l, t)
if not t then
return
end
local f = {}
for i, o in sortpairs(t) do
if is_enable(o) then
f[#f+1] = ('[%s]'):format(i)
for k, v in sortpairs(o) do
if k:sub(1, 1) ~= '_' then
write_data(f, k, v)
end
end
f[#f+1] = ''
end
end
return #f > 0 and table.concat(f, '\r\n')
end
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Bastok_Mines/npcs/Babenn.lua | 17 | 2308 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Babenn
-- Finishes Quest: The Eleventh's Hour
-- Involved in Quests: Riding on the Clouds
-- @zone 234
-- @pos 73 -1 34
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
package.loaded["scripts/globals/settings"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/titles");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
if (player:getQuestStatus(JEUNO,RIDING_ON_THE_CLOUDS) == QUEST_ACCEPTED and player:getVar("ridingOnTheClouds_2") == 1) then
if (trade:hasItemQty(1127,1) and trade:getItemCount() == 1) then -- Trade Kindred seal
player:setVar("ridingOnTheClouds_2",0);
player:tradeComplete();
player:addKeyItem(SMILING_STONE);
player:messageSpecial(KEYITEM_OBTAINED,SMILING_STONE);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if (player:getQuestStatus(BASTOK,THE_ELEVENTH_S_HOUR) == QUEST_ACCEPTED and player:getVar("EleventhsHour") == 1) then
player:startEvent(0x002d);
else
player:startEvent(0x0028);
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 == 0x002d) then
if (player:getFreeSlotsCount() > 1) then
player:setVar("EleventhsHour",0);
player:delKeyItem(OLD_TOOLBOX);
player:addTitle(PURSUER_OF_THE_TRUTH);
player:addItem(16629);
player:messageSpecial(ITEM_OBTAINED,16629);
player:addFame(BASTOK,BAS_FAME*30);
player:completeQuest(BASTOK,THE_ELEVENTH_S_HOUR);
else
player:messageSpecial(ITEM_CANNOT_BE_OBTAINED, 16629);
end
end
end; | gpl-3.0 |
shangjiyu/luci-with-extra | applications/luci-app-mwan3/luasrc/model/cbi/mwan/policy.lua | 108 | 3104 | -- ------ extra functions ------ --
function policyCheck() -- check to see if any policy names exceed the maximum of 15 characters
uci.cursor():foreach("mwan3", "policy",
function (section)
if string.len(section[".name"]) > 15 then
nameTooLong = 1
err_name_list = err_name_list .. section[".name"] .. " "
end
end
)
end
function policyWarn() -- display status and warning messages at the top of the page
if nameTooLong == 1 then
return "<font color=\"ff0000\"><strong>WARNING: Some policies have names exceeding the maximum of 15 characters!</strong></font>"
else
return ""
end
end
-- ------ policy configuration ------ --
ds = require "luci.dispatcher"
sys = require "luci.sys"
nameTooLong = 0
err_name_list = " "
policyCheck()
m5 = Map("mwan3", translate("MWAN Policy Configuration"),
translate(policyWarn()))
m5:append(Template("mwan/config_css"))
mwan_policy = m5:section(TypedSection, "policy", translate("Policies"),
translate("Policies are profiles grouping one or more members controlling how MWAN distributes traffic<br />" ..
"Member interfaces with lower metrics are used first. Interfaces with the same metric load-balance<br />" ..
"Load-balanced member interfaces distribute more traffic out those with higher weights<br />" ..
"Names may contain characters A-Z, a-z, 0-9, _ and no spaces. Names must be 15 characters or less<br />" ..
"Policies may not share the same name as configured interfaces, members or rules"))
mwan_policy.addremove = true
mwan_policy.dynamic = false
mwan_policy.sectionhead = "Policy"
mwan_policy.sortable = true
mwan_policy.template = "cbi/tblsection"
mwan_policy.extedit = ds.build_url("admin", "network", "mwan", "configuration", "policy", "%s")
function mwan_policy.create(self, section)
TypedSection.create(self, section)
m5.uci:save("mwan3")
luci.http.redirect(ds.build_url("admin", "network", "mwan", "configuration", "policy", section))
end
use_member = mwan_policy:option(DummyValue, "use_member", translate("Members assigned"))
use_member.rawhtml = true
function use_member.cfgvalue(self, s)
local memberConfig, memberList = self.map:get(s, "use_member"), ""
if memberConfig then
for k,v in pairs(memberConfig) do
memberList = memberList .. v .. "<br />"
end
return memberList
else
return "—"
end
end
last_resort = mwan_policy:option(DummyValue, "last_resort", translate("Last resort"))
last_resort.rawhtml = true
function last_resort.cfgvalue(self, s)
local action = self.map:get(s, "last_resort")
if action == "blackhole" then
return "blackhole (drop)"
elseif action == "default" then
return "default (use main routing table)"
else
return "unreachable (reject)"
end
end
errors = mwan_policy:option(DummyValue, "errors", translate("Errors"))
errors.rawhtml = true
function errors.cfgvalue(self, s)
if not string.find(err_name_list, " " .. s .. " ") then
return ""
else
return "<span title=\"Name exceeds 15 characters\"><img src=\"/luci-static/resources/cbi/reset.gif\" alt=\"error\"></img></span>"
end
end
return m5
| apache-2.0 |
Hello23-Ygopro/ygopro-ds | expansions/script/c27002071.lua | 1 | 2411 | --BT2-064 Mafuba
local ds=require "expansions.utility_dbscg"
local scard,sid=ds.GetID()
function scard.initial_effect(c)
--place on top
ds.AddCounterBattleCardAttackSkill(c,0,scard.topop,scard.topcost)
local e1=Effect.CreateEffect(c)
e1:SetType(EFFECT_TYPE_SINGLE+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(DS_EVENT_PLAY_SUCCESS)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e1:SetOperation(scard.cedop)
c:RegisterEffect(e1)
end
scard.dragon_ball_super_card=true
scard.donot_drop_as_cost=true
scard.topcost=ds.PayEnergyCost(COLOR_BLUE,1,1)
function scard.topop(e,tp,eg,ep,ev,re,r,rp)
Duel.NegateAttack()
local c=e:GetHandler()
if not c:IsRelateToSkill(e) then return end
local a=Duel.GetAttacker()
local g=a:GetStackGroup()
if g:GetCount()~=0 then
Duel.PlaceOnTop(c,g)
end
Duel.PlaceOnTop(c,a)
Duel.Play(c,0,tp,1-tp,false,false,DS_POS_FACEUP_REST)
--to drop
local e1=Effect.CreateEffect(c)
e1:SetDescription(aux.Stringid(sid,1))
e1:SetType(EFFECT_TYPE_FIELD+EFFECT_TYPE_CONTINUOUS)
e1:SetCode(EVENT_PHASE+PHASE_END)
e1:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE+EFFECT_FLAG_IGNORE_IMMUNE)
e1:SetRange(DS_LOCATION_BATTLE)
e1:SetCountLimit(1)
e1:SetCondition(scard.tgcon)
e1:SetOperation(scard.tgop)
e1:SetLabel(Duel.GetTurnCount())
e1:SetReset(RESET_PHASE+PHASE_END+RESET_OPPO_TURN,2)
Duel.RegisterEffect(e1,tp)
--cannot attack
local e2=Effect.CreateEffect(c)
e2:SetType(EFFECT_TYPE_SINGLE)
e2:SetCode(DS_SKILL_CANNOT_ATTACK)
e2:SetProperty(EFFECT_FLAG_CANNOT_DISABLE+EFFECT_FLAG_UNCOPYABLE)
e2:SetReset(RESET_EVENT+RESETS_STANDARD-RESET_TURN_SET)
c:RegisterEffect(e2,true)
--cannot switch position
local e3=e2:Clone()
e3:SetCode(DS_SKILL_CANNOT_SWITCH_POS_SKILL)
c:RegisterEffect(e3,true)
end
function scard.tgcon(e,tp,eg,ep,ev,re,r,rp)
return Duel.GetTurnPlayer()~=tp and Duel.GetTurnCount()~=e:GetLabel()
end
function scard.tgop(e,tp,eg,ep,ev,re,r,rp)
Duel.Hint(HINT_CARD,0,sid)
local c=e:GetHandler()
local g=c:GetStackGroup()
local mg=Group.CreateGroup()
for tc in aux.Next(g) do
mg:AddCard(tc)
end
Duel.SendtoDrop(c,DS_REASON_SKILL)
--keep stacked cards
local mc=mg:GetFirst()
Duel.MoveToField(mc,tp,1-tp,DS_LOCATION_BZONE,DS_POS_FACEUP_REST,true)
mg:RemoveCard(mc)
if mg:GetCount()~=0 then
Duel.PlaceOnTop(mc,mg)
end
end
function scard.cedop(e,tp,eg,ep,ev,re,r,rp)
Duel.SetChainLimitTillChainEnd(aux.FALSE)
end
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Al_Zahbi/TextIDs.lua | 9 | 2053 | -- Variable TextID Description text
-- General Texts
ITEM_CANNOT_BE_OBTAINED = 6379; -- You cannot obtain the item <item> come back again after sorting your inventory
ITEM_OBTAINED = 6384; -- Obtained: <item>
GIL_OBTAINED = 6385; -- Obtained <number> gil
KEYITEM_OBTAINED = 6387; -- Obtained key item: <keyitem>
FISHING_MESSAGE_OFFSET = 7043; -- You can't fish here
HOMEPOINT_SET = 7515; -- Home point set!
IMAGE_SUPPORT_ACTIVE = 7530; -- You have to wait a bit longer before asking for synthesis image support again.
IMAGE_SUPPORT = 7532; -- Your ?Multiple Choice (Parameter 1)?[fishing/woodworking/smithing/goldsmithing/clothcraft/leatherworking/bonecraft/alchemy/cooking] skills went up ...
SANCTION = 7951; -- You have received the Empire's Sanction.
--Other Texts
ITEM_DELIVERY_DIALOG = 7813; -- No need to wrap your goods. Just hand them over and they're as good as delivered! (I've got to be nice as long as the manager's got his eye on me...)
-- Shop Texts
ALLARD_SHOP_DIALOG = 7597; -- Hey, how ya doin'? Welcome to the armor shop of the Ulthalam Parade's leading star--Allard, in the flesh!
CHAYAYA_SHOP_DIALOG = 7609; -- Chayaya's Projectiles! Get your darts and more at Chayaya's Projectiles! Just don't touch the stuff in the high drawers, okay
KAHAHHOBICHAI_SHOP_DIALOG = 7591; -- Step rrright up to Kahah Hobichai's Blades! We've got everything your battle-thirrrsty heart desires!
ZAFIF_SHOP_DIALOG = 7603; -- Welcome... I'm Zafif, and this is my magic shop... I hope you can find something of use here.
DEHBI_MOSHAL_SHOP_DIALOG = 7817; -- Welcome to the Carpenters' Guild!
NDEGO_SHOP_DIALOG = 7819; -- The Blacksmiths' Guild thanks you for your business!
BORNAHN_SHOP_DIALOG = 7821; -- Welcome! We have all your goldsmithing needs right here!
TATEN_BILTEN_SHOP_DIALOG = 7823; -- Weave something beautiful with the materials you buy here, okay?
-- NPC Texts
CHOCOBO_HAPPY = 7826; -- The chocobo appears to be extremely happy.
| gpl-3.0 |
nasomi/darkstar | scripts/zones/The_Celestial_Nexus/mobs/Eald_narche.lua | 18 | 2569 | -----------------------------------
-- Area: The Celestial Nexus
-- NPC: Eald'Narche - Phase 1
-- Zilart Mission 16 BCNM Fight
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/status");
require("scripts/globals/magic");
function onMobInitialize(mob)
--50% fast cast
mob:addMod(MOD_UFASTCAST, 50);
end
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
mob:SetAutoAttackEnabled(false);
mob:setMobMod(MOBMOD_STANDBACK_TIME, 0);
mob:setMobMod(MOBMOD_GA_CHANCE,25);
mob:addStatusEffectEx(EFFECT_PHYSICAL_SHIELD, 0, 1, 0, 0);
mob:addStatusEffectEx(EFFECT_ARROW_SHIELD, 0, 1, 0, 0);
mob:addStatusEffectEx(EFFECT_MAGIC_SHIELD, 0, 1, 0, 0);
end;
function onMobEngaged(mob, target)
mob:addStatusEffectEx(EFFECT_SILENCE, 0, 1, 0, 5);
GetMobByID(mob:getID() + 1):updateEnmity(target);
end;
function onMobFight(mob, target)
if (mob:getBattleTime() % 9 <= 2) then
local orbital1 = mob:getID()+3;
local orbital2 = mob:getID()+4;
if (GetMobAction(orbital1) == ACTION_NONE) then
GetMobByID(orbital1):setPos(mob:getPos());
SpawnMob(orbital1):updateEnmity(target);
elseif (GetMobAction(orbital2) == ACTION_NONE) then
GetMobByID(orbital2):setPos(mob:getPos());
SpawnMob(orbital2):updateEnmity(target);
end
end
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
DespawnMob(mob:getID()+1);
DespawnMob(mob:getID()+3);
DespawnMob(mob:getID()+4);
local battlefield = killer:getBattlefield();
killer:startEvent(0x7d04, battlefield:getBattlefieldNumber());
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("updateCSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option,target)
--printf("finishCSID: %u",csid);
--printf("RESULT: %u",option);
if (csid == 0x7d04) then
DespawnMob(target:getID());
mob = SpawnMob(target:getID()+2);
mob:updateEnmity(player);
--the "30 seconds of rest" you get before he attacks you, and making sure he teleports first in range
mob:addStatusEffectEx(EFFECT_BIND, 0, 1, 0, 30);
mob:addStatusEffectEx(EFFECT_SILENCE, 0, 1, 0, 40);
end
end; | gpl-3.0 |
Wouterz90/SuperSmashDota | Game/scripts/vscripts/libraries/containers.lua | 10 | 88873 | CONTAINERS_VERSION = "0.80"
require('libraries/timers')
require('libraries/playertables')
local ID_BASE = "cont_"
FORCE_NIL = false
CONTAINERS_DEBUG = IsInToolsMode() -- Should we print debugging prints for containers
--[[
Containers API Calls
Containers:AddItemToUnit(unit, item)
Containers:CreateContainer(cont)
Containers:CreateShop(cont)
Containers:DeleteContainer(c, deleteContents)
Containers:DisplayError(pid, message)
Containers:EmitSoundOnClient(pid, sound)
Containers:GetDefaultInventory(unit)
Containers:GetEntityContainers(entity)
Containers:SetDefaultInventory(unit, container)
Containers:SetItemLimit(limit)
Containers:SetRangeAction(unit, tab)
Containers:UsePanoramaInventory(useInventory)
Containers:OnButtonPressed(playerID, container, unit, buttonNumber, buttonName)
Containers:OnCloseClicked(playerID, container, unit)
Containers:OnDragFrom(playerID, container, unit, item, fromSlot, toContainer, toSlot)
Containers:OnDragTo(playerID, container, unit, item, fromSlot, toContainer, toSlot)
Containers:OnDragWithin(playerID, container, unit, item, fromSlot, toSlot)
Containers:OnDragWorld(playerID, container, unit, item, slot, position, entity)
Containers:OnLeftClick(playerID, container, unit, item, slot)
Containers:OnRightClick(playerID, container, unit, item, slot)
Container Creation:
Containers:CreateContainer({
layout = {3,2,2},
skins = {"Skin1", "Another"}, --{}
buttons = {}, -- {"Take All"}
headerText = "#lootbox",
draggable = true,
position = "200px 200px 0px", -- "30% 40%" -- "mouse" -- "entity"
equipment = true,
range = 250,
closeOnOrder = true,
forceOwner = false,
forcePurchaser = false,
entity = PlayerResource:GetSelectedHeroEntity(0),
pids = {0}, -- {[2]=true, [4]=true}
items = {}, -- {CreateItem(...), CreateItem(...)} -- {[3]=CreateItem(...), [5]=CreateItem(...):GetEntityIndex()}
cantDragFrom = {}, -- {3,5}
cantDragTo = {},
layoutFile = "file://{resources}/layout/custom_game/containers/alt_container_example.xml", nil->default
OnLeftClick = function(playerID, container, unit, item, slot) ... end, -- nil->default, false->do nothing
OnRightClick = function(playerID, container, unit, item, slot) ... end, -- nil->default, false->do nothing
OnDragFrom = function(playerID, container, unit, item, fromSlot, toContainer, toSlot) ... end, -- nil->default, false->do nothing
OnDragTo = function(playerID, container, unit, item, fromSlot, toContainer, toSlot) ... end, -- nil->default, false->do nothing
OnDragWithin = function(playerID, container, unit, item, fromSlot, toSlot) ... end, -- nil->default, false->do nothing
OnDragWorld = function(playerID, container, unit, item, slot, position, entity) ... end, -- nil->default, false->do nothing
OnCloseClicked = function(playerID, container, unit) ... end, -- nil->default, false->do nothing
OnButtonPressed = function(playerID, container, unit, buttonNumber, buttonName) ... end, -- nil->default, false->do nothing
OnEntityOrder = function(playerID, container, unit, target), -- nil->do nothing
OnEntityDrag = function(playerID, container, unit, target, fromContainer, item) ... end, -- nil->do nothing
OnClose = function(playerID, container) ... end, -- nil->default
OnOpen = function(playerID, container) ... end, -- nil->default,
OnSelect = function(playerID, container, selectedEntity) ... end, -- nil->default,
OnDeselect = function(playerID, container, deselectedEntity) ... end, -- nil->default,,
-- return true to allow the item add event. slot is -1 if no slot is specified.
AddItemFilter = function(container, item, slot), -- nil->no filter
-- See containers/container_events.js for javascript callback registration and handling
-- nil means to use the default
OnLeftClickJS = "ExampleLeftClick",
OnRightClickJS = "ExampleRightClick",
OnDoubleClickJS = "ExampleDoubleClick",
OnMouseOutJS = "ExampleMouseOut",
OnMouseOverJS = "ExampleMouseOver",
OnButtonPressedJS = "ExampleButtonPressed",
OnCloseClickedJS = "ExampleCloseClicked",
)}
Container Functions:
c:ActivateItem(unit, item, playerID)
c:AddItem(item, slot, column, bypassFilter)
c:AddSkin(skin)
c:AddSubscription(pid)
c:CanDragFrom(pid)
c:CanDragTo(pid)
c:CanDragWithin(pid)
c:ClearSlot(slot)
c:Close(pid)
c:ContainsItem(item)
c:Delete(deleteContents)
c:GetAllItems()
c:GetAllOpen()
c:GetButtonName(number)
c:GetButtons()
c:GetCanDragFromPlayers()
c:GetCanDragToPlayers()
c:GetCanDragWithinPlayers()
c:GetContainerIndex()
c:GetEntity()
c:GetForceOwner()
c:GetForcePurchaser()
c:GetHeaderText()
c:GetItemInRowColumn(row, column)
c:GetItemInSlot(slot)
c:GetItemsByName(name)
c:GetLayout()
c:GetNumItems()
c:GetRange()
c:GetRowColumnForItem(item)
c:GetSize()
c:GetSkins()
c:GetSlotForItem(item)
c:GetSubscriptions()
c:HasSkin(skin)
c:IsCloseOnOrder()
c:IsDraggable()
c:IsEquipment()
c:IsInventory()
c:IsOpen(pid)
c:IsSubscribed(pid)
c:OnButtonPressed(fun)
c:OnButtonPressedJS(jsCallback)
c:OnClose(fun)
c:OnCloseClicked(fun)
c:OnCloseClickedJS(jsCallback)
c:OnDeselect(fun)
c:OnDoubleClickJS(jsCallback)
c:OnDragFrom(fun)
c:OnDragTo(fun)
c:OnDragWithin(fun)
c:OnDragWorld(fun)
c:OnEntityDrag(fun)
c:OnEntityOrder(fun)
c:OnLeftClick(fun)
c:OnLeftClickJS(jsCallback)
c:OnMouseOutJS(jsCallback)
c:OnMouseOverJS(jsCallback)
c:OnOpen(fun)
c:OnRightClick(fun)
c:OnRightClickJS(jsCallback)
c:OnSelect(fun)
c:Open(pid)
c:RemoveButton(number)
c:RemoveItem(item)
c:RemoveSkin(skin)
c:RemoveSubscription(pid)
c:SetButton(number, name)
c:SetCanDragFrom(pid, canDrag)
c:SetCanDragTo(pid, canDrag)
c:SetCanDragWithin(pid, canDrag)
c:SetCloseOnOrder(close)
c:SetDraggable(drag)
c:SetEntity(entity)
c:SetEquipment(equip)
c:SetForceOwner(owner)
c:SetForcePurchaser(purchaser)
c:SetHeaderText(header)
c:SetLayout(layout, removeOnContract)
c:SetRange(range)
c:SwapItems(item1, item2, allowCombine)
c:SwapSlots(slot1, slot2, allowCombine)
Shop Creation:
Containers:CreateShop({
-- Same as CreateContainer but with the additions of
items = {}, -- {CreateItem(...), CreateItem(...)} -- {[3]=CreateItem(...), [5]=CreateItem(...):GetEntityIndex()}
prices = {}, -- {500, 800} -- {[3]=500, [5]=800}
stocks = {}, -- {[5]=10}
}
Shop Functions:
-- Same as a Container but with the additions of
shop:BuyItem(playerID, unit, item)
shop:GetPrice(item)
shop:GetStock(item)
shop:SetPrice(item, price)
shop:SetStock(item, stock)
]]
LinkLuaModifier( "modifier_shopkeeper", "libraries/modifiers/modifier_shopkeeper.lua", LUA_MODIFIER_MOTION_NONE )
--"dota_hud_error_not_enough_gold" "Not Enough Gold"
--"dota_hud_error_item_out_of_stock" "Item is out of Stock"
--"dota_hud_error_cant_pick_up_item" "Inventory Full"
--"dota_hud_error_cant_sell_shop_not_in_range" "No Shop In Range"
--"dota_hud_error_target_out_of_range" "Target Out Of Range"
--"dota_hud_error_unit_command_restricted" "Can't Act"
--"DOTA_FantasyTeamCreate_Error_Header" "Error"
--"DOTA_Trading_Response_UnknownError" "Unknown Error"
-- mango can't be activated from outside inventory if it ever touched it
-- dust crash for same reason
-- dagon no particles/effects for same reason
-- soul ring crash for same reason
-- bottle also doesn't activate for same reason
-- travels don't work, TP either probably
-- armlet doesn't activate at all
-- euls has targeting issues
-- aghs probably not for sure
-- treads don't work in equipment
local ApplyPassives = nil
ApplyPassives = function(container, item, entOverride)
local ent = entOverride or container:GetEntity()
if not ent or not ent.AddNewModifier then return end
if container.appliedPassives[item:GetEntityIndex()] then return end
local passives = Containers.itemPassives[item:GetAbilityName()]
if passives then
for _,passive in ipairs(passives) do
-- check for previous buffs from this exact item
local buffs = ent:FindAllModifiersByName(passive)
for _, buff in ipairs(buffs) do
if buff:GetAbility() == item then
Timers:CreateTimer(function()
--print("FOUND, rerunning until removed")
ApplyPassives(container, item, entOverride)
end)
return
end
end
end
container.appliedPassives[item:GetEntityIndex()] = {}
for _,passive in ipairs(passives) do
item:ApplyDataDrivenModifier(ent, ent, passive, {})
buffs = ent:FindAllModifiersByName(passive)
for _, buff in ipairs(buffs) do
if buff:GetAbility() == item then
table.insert(container.appliedPassives[item:GetEntityIndex()], buff)
break
end
end
end
else
passives = item:GetIntrinsicModifierName()
if passives then
local buff = ent:AddNewModifier(ent, item, passives, {})
container.appliedPassives[item:GetEntityIndex()] = {buff}
end
end
end
local GetItem = function(item)
if type(item) == "number" then
return EntIndexToHScript(item)
elseif item and IsValidEntity(item) and item.IsItem and item:IsItem() then
return item
end
end
local unitInventory = {unit = nil, range = 150, allowStash = false, canDragFrom = {}, canDragTo = {}, forceOwner = nil, forcePurchaser = nil}
function unitInventory:AddItem(item, slot)
item = GetItem(item)
local unit = self.unit
local findStack = slot == nil
slot = slot or 0
local size = self:GetSize()
if slot > size then
print("[containers.lua] Request to add item in slot " .. slot .. " -- exceeding dota inventory size " .. size)
return false
end
local full = true
local stack = false
for i=0,size do
local sItem = unit:GetItemInSlot(i)
if not sItem then
full = false
elseif sItem:GetAbilityName() == item:GetAbilityName() and item:IsStackable() then
stack = true
end
end
if full and not stack then return false end
unit:AddItem(item)
Timers:CreateTimer(function()
if not IsValidEntity(item) then return end
unit:DropItemAtPositionImmediate(item, unit:GetAbsOrigin())
local drop = nil
for i=GameRules:NumDroppedItems()-1,0,-1 do
drop = GameRules:GetDroppedItem(i)
if drop:GetContainedItem() == item then
drop:RemoveSelf()
break
end
end
unit:AddItem(item)
if not findStack then
for i=0,5 do
if unit:GetItemInSlot(i) == item then
unit:SwapItems(i,slot)
if self.forceOwner then
item:SetOwner(self.forceOwner)
elseif self.forceOwner == false then
item:SetOwner(nil)
end
if self.forcePurchaser then
item:SetPurchaser(self.forcePurchaser)
elseif self.forceOwner == false then
item:SetPurchaser(nil)
end
end
end
end
end)
if not findStack then
for i=0,5 do
if unit:GetItemInSlot(i) == item then
unit:SwapItems(i,slot)
if self.forceOwner then
item:SetOwner(self.forceOwner)
elseif self.forceOwner == false then
item:SetOwner(nil)
end
if self.forcePurchaser then
item:SetPurchaser(self.forcePurchaser)
elseif self.forceOwner == false then
item:SetPurchaser(nil)
end
return true
end
end
end
return true
end
function unitInventory:ClearSlot(slot)
local item = self.unit:GetItemInSlot(slot)
if item then
self:RemoveItem(item)
end
end
function unitInventory:RemoveItem(item)
item = GetItem(item)
local unit = self.unit
if self:ContainsItem(item) then
unit:DropItemAtPositionImmediate(item, unit:GetAbsOrigin())
local drop = nil
for i=GameRules:NumDroppedItems()-1,0,-1 do
drop = GameRules:GetDroppedItem(i)
if drop:GetContainedItem() == item then
drop:RemoveSelf()
break
end
end
end
end
function unitInventory:ContainsItem(item)
item = GetItem(item)
if not item then return false end
local unit = self.unit
for i=0,11 do
if item == unit:GetItemInSlot(i) then
return true
end
end
return false
end
function unitInventory:GetSize()
if self.allowStash then
return 11
else
return 5
end
end
function unitInventory:GetItemInSlot(slot)
return self.unit:GetItemInSlot(slot)
end
function unitInventory:GetRange()
return self.range
end
function unitInventory:GetEntity()
return self.unit
end
function unitInventory:IsInventory()
return true
end
if not Containers then
Containers = class({})
end
function Containers:start()
if not __ACTIVATE_HOOK then
__ACTIVATE_HOOK = {funcs={}}
setmetatable(__ACTIVATE_HOOK, {
__call = function(t, func)
table.insert(t.funcs, func)
end
})
debug.sethook(function(...)
local info = debug.getinfo(2)
local src = tostring(info.short_src)
local name = tostring(info.name)
if name ~= "__index" then
if string.find(src, "addon_game_mode") then
if GameRules:GetGameModeEntity() then
for _, func in ipairs(__ACTIVATE_HOOK.funcs) do
local status, err = pcall(func)
if not status then
print("__ACTIVATE_HOOK callback error: " .. err)
end
end
debug.sethook(nil, "c")
end
end
end
end, "c")
end
__ACTIVATE_HOOK(function()
local mode = GameRules:GetGameModeEntity()
mode:SetExecuteOrderFilter(Dynamic_Wrap(Containers, 'OrderFilter'), Containers)
Containers.oldFilter = mode.SetExecuteOrderFilter
mode.SetExecuteOrderFilter = function(mode, fun, context)
--print('SetExecuteOrderFilter', fun, context)
Containers.nextFilter = fun
Containers.nextContext = context
end
Containers.initialized = true
end)
self.initialized = false
self.containers = {}
self.nextID = 0
self.closeOnOrders = {}
for i=0,DOTA_MAX_TEAM_PLAYERS do
self.closeOnOrders[i] = {}
end
CustomNetTables:SetTableValue("containers_lua", "use_panorama_inventory", {value=false})
self.nextFilter = nil
self.nextContext = nil
self.disableItemLimit = false
self.itemKV = LoadKeyValues("scripts/npc/items.txt")
self.itemIDs = {}
self.entityShops = {}
self.defaultInventories = {}
self.rangeActions = {}
self.previousSelection = {}
self.entityContainers = {}
for k,v in pairs(LoadKeyValues("scripts/npc/npc_abilities_override.txt")) do
if self.itemKV[k] then
self.itemKV[k] = v
end
end
for k,v in pairs(LoadKeyValues("scripts/npc/npc_items_custom.txt")) do
if not self.itemKV[k] then
self.itemKV[k] = v
end
end
for k,v in pairs(self.itemKV) do
if type(v) == "table" and v.ID then
self.itemIDs[v.ID] = k
end
end
self.itemPassives = {}
for id,itemName in pairs(Containers.itemIDs) do
local kv = Containers.itemKV[itemName]
if kv.BaseClass == "item_datadriven" then
self.itemPassives[itemName] = {}
if kv.Modifiers then
local mods = kv.Modifiers
for modname, mod in pairs(mods) do
if mod.Passive == 1 then
table.insert(self.itemPassives[itemName], modname)
end
end
end
end
end
self.oldUniversal = GameRules.SetUseUniversalShopMode
self.universalShopMode = false
GameRules.SetUseUniversalShopMode = function(gamerules, universal)
Containers.universalShopMode = universal
Containers.oldUniversal(gamerules, universal)
end
if GameRules.FDesc then
GameRules.FDesc["SetUseUniversalShopMode"] = nil
end
CustomGameEventManager:RegisterListener("Containers_EntityShopRange", Dynamic_Wrap(Containers, "Containers_EntityShopRange"))
CustomGameEventManager:RegisterListener("Containers_Select", Dynamic_Wrap(Containers, "Containers_Select"))
CustomGameEventManager:RegisterListener("Containers_HideProxy", Dynamic_Wrap(Containers, "Containers_HideProxy"))
CustomGameEventManager:RegisterListener("Containers_OnLeftClick", Dynamic_Wrap(Containers, "Containers_OnLeftClick"))
CustomGameEventManager:RegisterListener("Containers_OnRightClick", Dynamic_Wrap(Containers, "Containers_OnRightClick"))
CustomGameEventManager:RegisterListener("Containers_OnDragFrom", Dynamic_Wrap(Containers, "Containers_OnDragFrom"))
CustomGameEventManager:RegisterListener("Containers_OnDragWorld", Dynamic_Wrap(Containers, "Containers_OnDragWorld"))
CustomGameEventManager:RegisterListener("Containers_OnCloseClicked", Dynamic_Wrap(Containers, "Containers_OnCloseClicked"))
CustomGameEventManager:RegisterListener("Containers_OnButtonPressed", Dynamic_Wrap(Containers, "Containers_OnButtonPressed"))
CustomGameEventManager:RegisterListener("Containers_OnSell", Dynamic_Wrap(Containers, "Containers_OnSell"))
Timers:CreateTimer(function()
for id,action in pairs(Containers.rangeActions) do
local unit = action.unit
if unit then
if action.entity and not IsValidEntity(action.entity) then
Containers.rangeActions[id] = nil
else
local range = action.range
if not range and action.container then
range = action.container:GetRange()
end
if not range then range = 150 end
local range2 = range * range
local pos = action.position or action.entity:GetAbsOrigin()
local dist = unit:GetAbsOrigin() - pos
if (dist.x * dist.x + dist.y * dist.y) <= range2 then
local status, err = pcall(action.action, action.playerID, action.container, unit, action.entity or action.position, action.fromContainer or action.orderType, action.item)
if not status then print('[containers.lua] RangeAction failure:' .. err) end
Containers.rangeActions[id] = nil
end
end
else
Containers.rangeActions[id] = nil
end
end
return .01
end)
end
local closeOnOrderSkip = {
[DOTA_UNIT_ORDER_PURCHASE_ITEM] = true,
[DOTA_UNIT_ORDER_GLYPH] = true,
[DOTA_UNIT_ORDER_HOLD_POSITION] = true,
[DOTA_UNIT_ORDER_STOP] = true,
[DOTA_UNIT_ORDER_EJECT_ITEM_FROM_STASH] = true,
[DOTA_UNIT_ORDER_DISASSEMBLE_ITEM] = true,
[DOTA_UNIT_ORDER_PING_ABILITY] = true,
[DOTA_UNIT_ORDER_TRAIN_ABILITY] = true,
[DOTA_UNIT_ORDER_CAST_NO_TARGET] = true,
[DOTA_UNIT_ORDER_CAST_TOGGLE] = true,
}
function Containers:AddItemToUnit(unit, item)
if item and unit then
local defInventory = Containers:GetDefaultInventory(unit)
if defInventory then
if not defInventory:AddItem(item) then
CreateItemOnPositionSync(unit:GetAbsOrigin() + RandomVector(10), item)
end
else
local iname = item:GetAbilityName()
local exists = false
local full = true
for i=0,5 do
local it = unit:GetItemInSlot(i)
if not it then
full = false
elseif it:GetAbilityName() == iname then
exists = true
end
end
if not full or (full and item:IsStackable() and exists) then
unit:AddItem(item)
else
CreateItemOnPositionSync(unit:GetAbsOrigin() + RandomVector(10), item)
end
end
end
end
function Containers:SetItemLimit(limit)
SendToServerConsole("dota_max_physical_items_purchase_limit " .. limit)
end
function Containers:SetDisableItemLimit(disable)
if not self.initialized then
print('[containers.lua] FATAL: Containers:Init() has not been initialized!')
return
end
--self.disableItemLimit = disable
end
function Containers:UsePanoramaInventory(useInventory)
CustomNetTables:SetTableValue("containers_lua", "use_panorama_inventory", {value=useInventory})
CustomGameEventManager:Send_ServerToAllClients("cont_use_panorama_inventory", {use=useInventory})
end
function Containers:DisplayError(pid, message)
local player = PlayerResource:GetPlayer(pid)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "cont_create_error_message", {message=message})
end
end
function Containers:EmitSoundOnClient(pid, sound)
local player = PlayerResource:GetPlayer(pid)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "cont_emit_client_sound", {sound=sound})
end
end
function Containers:OrderFilter(order)
--print('Containers:OrderFilter')
--PrintTable(order)
local ret = true
if Containers.nextFilter then
ret = Containers.nextFilter(Containers.nextContext, order)
end
if not ret then
return false
end
local issuerID = order.issuer_player_id_const
local queue = order.queue == 1
if issuerID == -1 then return true end
-- close on order
if not closeOnOrderSkip[order.order_type] then
local oConts = Containers.closeOnOrders[issuerID]
for id,cont in pairs(oConts) do
if IsValidContainer(cont) then
cont:Close(issuerID)
else
oConts[id] = nil
end
end
end
if not queue and order.units["0"] then
Containers.rangeActions[order.units["0"]] = nil
end
local conts = Containers:GetEntityContainers(order.entindex_target)
if order.units["0"] and #conts > 0 then
local container = nil
for _,cont in ipairs(conts) do
if cont._OnEntityOrder then
container = cont
break
end
end
if container then
local unit = EntIndexToHScript(order.units["0"])
local target = EntIndexToHScript(order.entindex_target)
local range = container:GetRange() or 150
local unitpos = unit:GetAbsOrigin()
local diff = unitpos - target:GetAbsOrigin()
local dist = diff:Length2D()
local pos = unitpos
if dist > range * .9 then
pos = target:GetAbsOrigin() + diff:Normalized() * range * .9
end
local origOrder = order.order_type
if target.GetContainedItem then
order.order_type = DOTA_UNIT_ORDER_MOVE_TO_POSITION
order.position_x = pos.x
order.position_y = pos.y
order.position_z = pos.z
else
order.order_type = DOTA_UNIT_ORDER_MOVE_TO_TARGET
end
Containers.rangeActions[order.units["0"]] = {
unit = unit,
entity = target,
range = range,
playerID = issuerID,
container = container,
orderType = origOrder,
action = container._OnEntityOrder,
}
end
end
--DOTA_UNIT_ORDER_GIVE_ITEM
if order.units["0"] and order.order_type == DOTA_UNIT_ORDER_GIVE_ITEM then
local unit = EntIndexToHScript(order.units["0"])
local item = EntIndexToHScript(order.entindex_ability)
local target = EntIndexToHScript(order.entindex_target)
local defInventory = Containers:GetDefaultInventory(target)
if defInventory then
order.order_type = DOTA_UNIT_ORDER_MOVE_TO_TARGET
Containers.rangeActions[order.units["0"]] = {
unit = unit,
entity = target,
range = 180,
playerID = issuerID,
action = function(playerID, container, unit, target)
if IsValidEntity(target) and target:IsAlive() then
unit:DropItemAtPositionImmediate(item, unit:GetAbsOrigin())
local drop = nil
for i=GameRules:NumDroppedItems()-1,0,-1 do
drop = GameRules:GetDroppedItem(i)
if drop:GetContainedItem() == item then
Containers:AddItemToUnit(target, item)
drop:RemoveSelf()
break
end
end
end
unit:Stop()
end,
}
else
return true
end
end
if order.units["0"] and order.order_type == DOTA_UNIT_ORDER_PICKUP_ITEM then
local unit = EntIndexToHScript(order.units["0"])
local physItem = EntIndexToHScript(order.entindex_target)
local unitpos = unit:GetAbsOrigin()
if not physItem then return false end
local diff = unitpos - physItem:GetAbsOrigin()
local dist = diff:Length2D()
local pos = unitpos
if dist > 90 then
pos = physItem:GetAbsOrigin() + diff:Normalized() * 90
end
local defInventory = Containers:GetDefaultInventory(unit)
if defInventory then
order.order_type = DOTA_UNIT_ORDER_MOVE_TO_POSITION
order.position_x = pos.x
order.position_y = pos.y
order.position_z = pos.z
Containers.rangeActions[order.units["0"]] = {
unit = unit,
position = physItem:GetAbsOrigin(),
range = 100,
playerID = issuerID,
action = function(playerID, container, unit, target)
if IsValidEntity(physItem) then
local item = physItem:GetContainedItem()
if item and defInventory:AddItem(item) then
physItem:RemoveSelf()
end
end
end,
}
end
end
if order.units["0"] and order.order_type == DOTA_UNIT_ORDER_PURCHASE_ITEM then
local unit = EntIndexToHScript(order.units["0"])
local itemID = order.entindex_ability
local itemName = Containers.itemIDs[itemID]
local player = PlayerResource:GetPlayer(issuerID)
local ownerID = issuerID --unit:GetMainControllingPlayer()
local owner = PlayerResource:GetSelectedHeroEntity(ownerID)
local defInventory = Containers:GetDefaultInventory(unit)
if defInventory then
local shops = Containers.entityShops[unit:GetEntityIndex()] or {home=false, side=false, secret=false}
if not unit:IsAlive() then
shops = {home=true, side=false, secret=false}
end
if not shops.home and not shops.side and not shops.secret then
CustomGameEventManager:Send_ServerToPlayer(player, "cont_create_error_message", {reason=67})
return false
end
local item = CreateItem(itemName, owner, owner)
local cost = item:GetCost()
if not defInventory:AddItem(item) then
CreateItemOnPositionSync(unit:GetAbsOrigin() + RandomVector(10), item)
end
PlayerResource:SpendGold(ownerID, cost, DOTA_ModifyGold_PurchaseItem)
return false
elseif Containers.disableItemLimit then
if not unit:HasInventory() then
unit = owner
if unit == nil then return false end
end
local itemDefinition = Containers.itemKV[itemName]
local itemSide = itemDefinition["SideShop"] == 1
local itemSecret = itemDefinition["SecretShop"] == 1
if itemDefinition["ItemPurchasable"] == 0 then return false end
local toStash = true
local full = true
for i=0,5 do
if unit:GetItemInSlot(i) == nil then
full = false
break
end
end
local shops = Containers.entityShops[unit:GetEntityIndex()] or {home=false, side=false, secret=false}
if not unit:IsAlive() then
shops = {home=true, side=false, secret=false}
end
local stashPurchasingDisabled = GameRules:GetGameModeEntity():GetStashPurchasingDisabled()
local universalShopMode = Containers.universalShopMode
if universalShopMode then
if not shops.home and not shops.side and not shops.secret then
if stashPurchasingDisabled then
CustomGameEventManager:Send_ServerToPlayer(player, "cont_create_error_message", {reason=67})
return false
end
toStash = true
end
else
if not shops.home and not shops.side and not shops.secret then
-- not in range of any shops
if stashPurchasingDisabled then
CustomGameEventManager:Send_ServerToPlayer(player, "cont_create_error_message", {reason=67})
return false
end
elseif itemSecret and shops.secret then
toStash = false
elseif itemSide and shops.side then
toStash = false
elseif shops.home and not full then
toStash = false
end
end
local item = CreateItem(itemName, owner, owner)
local fullyShareStacking = Containers.itemKV[itemName]["ItemShareability"] == "ITEM_FULLY_SHAREABLE_STACKING"
local dropped = {}
local cost = item:GetCost()
if toStash then
local restore = {}
local stashSlot = 11
for i=6,11 do
local slot = owner:GetItemInSlot(i)
if not slot then
stashSlot = i
break
end
end
for i=0,5 do
local slot = owner:GetItemInSlot(i)
if slot and (fullyShareStacking and slot:GetAbilityName() == itemName
or ((slot:GetAbilityName() == "item_ward_dispenser" or slot:GetAbilityName() == "item_ward_observer" or slot:GetAbilityName() == "item_ward_sentry")) and
(itemName == "item_ward_observer" or itemName == "item_ward_sentry")) then
owner:DropItemAtPositionImmediate(slot, owner:GetAbsOrigin())
for i=GameRules:NumDroppedItems()-1,0,-1 do
local drop = GameRules:GetDroppedItem(i)
if drop:GetContainedItem() == slot then
table.insert(dropped, drop)
break
end
end
elseif slot and (slot:GetOwner() == owner or slot:GetPurchaser() == owner) then
restore[slot:GetEntityIndex()] = {owner=slot:GetOwner(), purchaser=slot:GetPurchaser()}
slot:SetPurchaser(nil)
slot:SetOwner(nil)
end
end
if owner:GetNumItemsInStash() == 6 then
if not unit.HasAnyAvailableInventorySpace and shops.home then
CreateItemOnPositionSync(unit:GetAbsOrigin() + RandomVector(20), item)
else
local slot = DOTA_STASH_SLOT_6
local slotItem = owner:GetItemInSlot(slot)
if slotItem and slotItem:GetAbilityName() == item:GetAbilityName() then
slot = DOTA_STASH_SLOT_5
end
owner:SwapItems(slot,14)
owner:AddItem(item)
for i=0,11 do
if owner:GetItemInSlot(i) == item then
owner:SwapItems(slot,i)
owner:EjectItemFromStash(item)
end
end
owner:SwapItems(14,slot)
end
else
owner:AddItem(item)
for i=0,11 do
if owner:GetItemInSlot(i) == item then
owner:SwapItems(stashSlot,i)
end
end
end
for i=0,5 do
local item = owner:GetItemInSlot(i)
if item and restore[item:GetEntityIndex()] ~= nil then
item:SetPurchaser(restore[item:GetEntityIndex()].purchaser)
item:SetOwner(restore[item:GetEntityIndex()].owner)
end
end
else
if full then
local physItem = CreateItemOnPositionSync(unit:GetAbsOrigin() + RandomVector(5), item)
unit:PickupDroppedItem(physItem)
else
for i=6,11 do
local item = unit:GetItemInSlot(i)
if not shops.home and item and item:GetPurchaser() == owner then
item:SetPurchaser(nil)
end
end
unit:AddItem(item)
for i=6,11 do
local item = unit:GetItemInSlot(i)
if not shops.home and item and item:GetPurchaser() == nil then
item:SetPurchaser(owner)
end
end
end
end
local queue = false
for _,drop in ipairs(dropped) do
ExecuteOrderFromTable({
UnitIndex = owner:GetEntityIndex(),
TargetIndex = drop:GetEntityIndex(),
OrderType = DOTA_UNIT_ORDER_PICKUP_ITEM,
Queue = queue,
})
queue = true
--owner:AddItem(drop:GetContainedItem())
--drop:RemoveSelf()
end
PlayerResource:SpendGold(ownerID, cost, DOTA_ModifyGold_PurchaseItem)
return false
end
end
return ret
end
function Containers:Containers_EntityShopRange(args)
local unit = args.unit
local shop = args.shop
local cs = Containers.entityShops
if not cs[unit] then cs[unit] = {home=false, side=false, secret=false} end
cs[unit].home = bit.band(shop, 1) ~= 0
cs[unit].side = bit.band(shop, 2) ~= 0
cs[unit].secret = bit.band(shop, 4) ~= 0
end
function Containers:Containers_Select(args)
local playerID = args.PlayerID
local prev = Containers.previousSelection[playerID]
local new = args.entity
local newEnt = EntIndexToHScript(new)
local prevConts = Containers:GetEntityContainers(prev)
for _, c in ipairs(prevConts) do
if c._OnDeselect then
local res, err = pcall(c._OnDeselect, playerID, c, prev)
if err then
print('[containers.lua] Error in OnDeselect: ' .. err)
end
end
end
Containers.previousSelection[playerID] = newEnt
local conts = Containers:GetEntityContainers(new)
for _, c in ipairs(conts) do
if c._OnSelect then
local res, err = pcall(c._OnSelect, playerID, c, newEnt)
if err then
print('[containers.lua] Error in OnSelect: ' .. err)
end
end
end
end
function Containers:Containers_HideProxy(args)
local abil = EntIndexToHScript(args.abilID)
if abil and abil.GetAbilityName and (abil:GetAbilityName() == "containers_lua_targeting" or abil:GetAbilityName() == "containers_lua_targeting_tree" )
and abil:GetOwner():GetPlayerOwnerID() == args.PlayerID then
abil:SetHidden(true)
end
end
function Containers:Containers_OnSell(args)
Containers:print('Containers_OnSell')
Containers:PrintTable(args)
local playerID = args.PlayerID
local unit = args.unit == nil and nil or EntIndexToHScript(args.unit)
local contID = args.contID
local itemID = args.itemID
local slot = args.slot
if not playerID then return end
--if unit and unit:GetMainControllingPlayer() ~= playerID then return end
local container = Containers.containers[contID]
if not container then return end
local item = EntIndexToHScript(args.itemID)
if not (item and IsValidEntity(item) and item.IsItem and item:IsItem()) then return end
if item:GetOwner() ~= unit or item:GetPurchaser() ~= unit then return end
local itemInSlot = container:GetItemInSlot(slot)
if itemInSlot ~= item then return end
local range = container:GetRange()
local ent = container:GetEntity()
if range == nil and ent and unit ~= ent then return end
if range and ent and unit and (ent:GetAbsOrigin() - unit:GetAbsOrigin()):Length2D() >= range then
Containers:DisplayError(playerID,"#dota_hud_error_target_out_of_range")
return
end
local shops = Containers.entityShops[unit:GetEntityIndex()] or {home=false, side=false, secret=false}
local player = PlayerResource:GetPlayer(playerID)
if not shops.home and not shops.side and not shops.secret then
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "cont_create_error_message", {reason=67})
end
return
end
local cost = item:GetCost()
if GameRules:GetGameTime() - item:GetPurchaseTime() > 10 then
cost = cost /2
end
container:RemoveItem(item)
item:RemoveSelf()
PlayerResource:ModifyGold(playerID, cost, false, DOTA_ModifyGold_SellItem)
if player then
SendOverheadEventMessage(player, OVERHEAD_ALERT_GOLD, unit, cost, player)
EmitSoundOnClient("General.Sell", player)
end
end
function Containers:Containers_OnLeftClick(args)
Containers:print('Containers_OnLeftClick')
Containers:PrintTable(args)
local playerID = args.PlayerID
local unit = args.unit == nil and nil or EntIndexToHScript(args.unit)
local contID = args.contID
local itemID = args.itemID
local slot = args.slot
if not playerID then return end
--if unit and unit:GetMainControllingPlayer() ~= playerID then return end
local container = Containers.containers[contID]
if not container then return end
local fun = container._OnLeftClick
if fun == false then return end
local item = EntIndexToHScript(args.itemID)
if not (item and IsValidEntity(item) and item.IsItem and item:IsItem()) then return end
local itemInSlot = container:GetItemInSlot(slot)
if itemInSlot ~= item then return end
local range = container:GetRange()
local ent = container:GetEntity()
if range == nil and ent and unit ~= ent then return end
if range and ent and unit and (ent:GetAbsOrigin() - unit:GetAbsOrigin()):Length2D() >= range then
Containers:DisplayError(playerID,"#dota_hud_error_target_out_of_range")
return
end
if type(fun) == "function" then
fun(playerID, container, unit, item, slot)
else
Containers:OnLeftClick(playerID, container, unit, item, slot)
end
end
function Containers:Containers_OnRightClick(args)
Containers:print('Containers_OnRightClick')
Containers:PrintTable(args)
local playerID = args.PlayerID
local unit = args.unit == nil and nil or EntIndexToHScript(args.unit)
local contID = args.contID
local itemID = args.itemID
local slot = args.slot
if not playerID then return end
--if unit and unit:GetMainControllingPlayer() ~= playerID then return end
local container = Containers.containers[contID]
if not container then return end
local fun = container._OnRightClick
if fun == false then return end
local item = EntIndexToHScript(args.itemID)
if not (item and IsValidEntity(item) and item.IsItem and item:IsItem()) then return end
local itemInSlot = container:GetItemInSlot(slot)
if itemInSlot ~= item then return end
local range = container:GetRange()
local ent = container:GetEntity()
if range == nil and ent and unit ~= ent then return end
if range and ent and unit and (ent:GetAbsOrigin() - unit:GetAbsOrigin()):Length2D() >= range then
Containers:DisplayError(playerID,"#dota_hud_error_target_out_of_range")
return
end
if type(fun) == "function" then
fun(playerID, container, unit, item, slot)
else
Containers:OnRightClick(playerID, container, unit, item, slot)
end
end
function Containers:Containers_OnDragFrom(args)
Containers:print('Containers_OnDragFrom')
Containers:PrintTable(args)
local playerID = args.PlayerID
local unit = args.unit == nil and nil or EntIndexToHScript(args.unit)
local contID = args.contID
local itemID = args.itemID
local fromSlot = args.fromSlot
local toContID = args.toContID
local toSlot = args.toSlot
if not playerID then return end
--if unit and unit:GetMainControllingPlayer() ~= playerID then return end
local container = nil
if contID == -1 then
container = unitInventory
container.unit = unit
container.range = 150
if fromSlot > 5 then return end
else
container = Containers.containers[contID]
end
if not container then return end
local toContainer = nil
if toContID == -1 then
toContainer = unitInventory
toContainer.unit = unit
toContainer.range = 150
if toSlot > 5 then return end
else
toContainer = Containers.containers[toContID]
end
if not toContainer then return end
local item = EntIndexToHScript(args.itemID)
if not (item and IsValidEntity(item) and item.IsItem and item:IsItem()) then return end
local itemInSlot = container:GetItemInSlot(fromSlot)
if itemInSlot ~= item then return end
if toSlot > toContainer:GetSize() then return end
local range = container:GetRange()
local ent = container:GetEntity()
if range == nil and ent and unit ~= ent then return end
if range and ent and unit and (ent:GetAbsOrigin() - unit:GetAbsOrigin()):Length2D() >= range then
Containers:DisplayError(playerID,"#dota_hud_error_target_out_of_range")
return
end
if container == toContainer then
if container.canDragWithin[playerID] == false then return end
local fun = container._OnDragWithin
if fun == false then return end
if type(fun) == "function" then
fun(playerID, container, unit, item, fromSlot, toSlot)
else
Containers:OnDragWithin(playerID, container, unit, item, fromSlot, toSlot)
end
else
if container.canDragFrom[playerID] == false or toContainer.canDragTo[playerID] == false then return end
local range = toContainer:GetRange()
local ent = toContainer:GetEntity()
if range and ent and unit and (ent:GetAbsOrigin() - unit:GetAbsOrigin()):Length2D() >= range then
Containers:DisplayError(playerID,"#dota_hud_error_target_out_of_range")
return
end
local fun = container._OnDragFrom
if fun == false then return end
if type(fun) == "function" then
fun(playerID, container, unit, item, fromSlot, toContainer, toSlot)
else
Containers:OnDragFrom(playerID, container, unit, item, fromSlot, toContainer, toSlot)
end
end
end
function Containers:Containers_OnDragWorld(args)
Containers:print('Containers_OnDragWorld')
Containers:PrintTable(args)
local playerID = args.PlayerID
local unit = args.unit == nil and nil or EntIndexToHScript(args.unit)
local contID = args.contID
local itemID = args.itemID
local slot = args.slot
local position = args.position
local entity = nil
if type(args.entity) == "number" then entity = EntIndexToHScript(args.entity) end
if not playerID then return end
--if unit and unit:GetMainControllingPlayer() ~= playerID then return end
local container = nil
if contID == -1 then
container = unitInventory
container.unit = unit
container.range = nil
else
container = Containers.containers[contID]
end
if not container then return end
local fun = container._OnDragWorld
if fun == false then return end
local item = EntIndexToHScript(args.itemID)
if not (item and IsValidEntity(item) and item.IsItem and item:IsItem()) then return end
local itemInSlot = container:GetItemInSlot(slot)
if itemInSlot ~= item then return end
if not position["0"] or not position["1"] or not position["2"] then return end
position = Vector(position["0"], position["1"], position["2"])
if container.canDragFrom[playerID] == false then return end
if not item:IsDroppable() then
Containers:DisplayError(playerID,"#dota_hud_error_item_cant_be_dropped")
return
end
local range = container:GetRange()
local ent = container:GetEntity()
if range == nil and ent and unit ~= ent then return end
if range and ent and unit and (ent:GetAbsOrigin() - unit:GetAbsOrigin()):Length2D() >= range then
Containers:DisplayError(playerID,"#dota_hud_error_target_out_of_range")
return
end
if type(fun) == "function" then
fun(playerID, container, unit, item, slot, position, entity)
else
Containers:OnDragWorld(playerID, container, unit, item, slot, position, entity)
end
end
function Containers:Containers_OnCloseClicked(args)
Containers:print('Containers_OnCloseClicked')
Containers:PrintTable(args)
local playerID = args.PlayerID
local unit = args.unit == nil and nil or EntIndexToHScript(args.unit)
local contID = args.contID
if not playerID then return end
local container = Containers.containers[contID]
if not container then return end
local fun = container._OnCloseClicked
if fun == false then return end
if type(fun) == "function" then
fun(playerID, container, unit)
else
Containers:OnCloseClicked(playerID, container, unit)
end
end
function Containers:Containers_OnButtonPressed(args)
Containers:print('Containers_OnButtonPressed')
Containers:PrintTable(args)
local playerID = args.PlayerID
local unit = args.unit == nil and nil or EntIndexToHScript(args.unit)
local contID = args.contID
local buttonNumber = args.button
if not playerID then return end
--if unit and unit:GetMainControllingPlayer() ~= playerID then return end
local container = Containers.containers[contID]
if not container then return end
local fun = container._OnButtonPressed
if fun == false then return end
if buttonNumber < 1 then return end
local buttonName = container:GetButtonName(buttonNumber)
if not buttonName then return end
local range = container:GetRange()
local ent = container:GetEntity()
if range == nil and ent and unit ~= ent then return end
if range and ent and unit and (ent:GetAbsOrigin() - unit:GetAbsOrigin()):Length2D() >= range then
Containers:DisplayError(playerID,"#dota_hud_error_target_out_of_range")
return
end
if type(fun) == "function" then
fun(playerID, container, unit, buttonNumber, buttonName)
else
Containers:OnButtonPressed(playerID, container, unit, buttonNumber, buttonName)
end
end
function Containers:OnLeftClick(playerID, container, unit, item, slot)
Containers:print("Containers:OnLeftClick", playerID, container, unit, item:GetEntityIndex(), slot)
local hero = PlayerResource:GetSelectedHeroEntity(playerID)
container:ActivateItem(hero, item, playerID)
end
function Containers:OnRightClick(playerID, container, unit, item, slot)
Containers:print("Containers:OnRightClick", playerID, container, unit, item:GetEntityIndex(), slot)
end
function Containers:OnDragWithin(playerID, container, unit, item, fromSlot, toSlot)
Containers:print('Containers:OnDragWithin', playerID, container, unit, item, fromSlot, toSlot)
container:SwapSlots(fromSlot, toSlot, true)
end
function Containers:OnDragFrom(playerID, container, unit, item, fromSlot, toContainer, toSlot)
Containers:print('Containers:OnDragFrom', playerID, container, unit, item, fromSlot, toContainer, toSlot)
local canChange = Containers.itemKV[item:GetAbilityName()].ItemCanChangeContainer
if toContainer._OnDragTo == false or canChange == 0 then return end
local fun = nil
if type(toContainer._OnDragTo) == "function" then
fun = toContainer._OnDragTo
end
if fun then
fun(playerID, container, unit, item, fromSlot, toContainer, toSlot)
else
Containers:OnDragTo(playerID, container, unit, item, fromSlot, toContainer, toSlot)
end
end
function Containers:OnDragTo(playerID, container, unit, item, fromSlot, toContainer, toSlot)
Containers:print('Containers:OnDragTo', playerID, container, unit, item, fromSlot, toContainer, toSlot)
local item2 = toContainer:GetItemInSlot(toSlot)
local addItem = nil
if item2 and IsValidEntity(item2) and (item2:GetAbilityName() ~= item:GetAbilityName() or not item2:IsStackable() or not item:IsStackable()) then
if Containers.itemKV[item2:GetAbilityName()].ItemCanChangeContainer == 0 then
return false
end
toContainer:RemoveItem(item2)
addItem = item2
end
if toContainer:AddItem(item, toSlot) then
container:ClearSlot(fromSlot)
if addItem then
if container:AddItem(addItem, fromSlot) then
return true
else
toContainer:RemoveItem(item)
toContainer:AddItem(item2, toSlot, nil, true)
container:AddItem(item, fromSlot, nil, true)
return false
end
end
return true
elseif addItem then
toContainer:AddItem(item2, toSlot, nil, true)
end
return false
end
function Containers:OnDragWorld(playerID, container, unit, item, slot, position, entity)
Containers:print('Containers:OnDragWorld', playerID, container, unit, item, slot, position, entity)
local unitpos = unit:GetAbsOrigin()
local diff = unitpos - position
local dist = diff:Length2D()
local conts = {}
if IsValidEntity(entity) then
conts = Containers:GetEntityContainers(entity:GetEntityIndex())
end
local toCont = nil
for _,cont in ipairs(conts) do
if cont._OnEntityDrag then
toCont = cont
break
end
end
if IsValidEntity(entity) and entity.GetContainedItem and toCont then
local range = toCont:GetRange() or 150
Containers:SetRangeAction(unit, {
unit = unit,
entity = entity,
range = range,
playerID = playerID,
container = toCont,
fromContainer = container,
item = item,
action = toCont._OnEntityDrag,
})
elseif IsValidEntity(entity) and entity:GetTeam() == unit:GetTeam() and entity.HasInventory and entity:HasInventory() and entity:IsAlive() then
ExecuteOrderFromTable({
UnitIndex= unit:GetEntityIndex(),
OrderType= DOTA_UNIT_ORDER_MOVE_TO_TARGET,
TargetIndex= entity:GetEntityIndex(),
})
Containers.rangeActions[unit:GetEntityIndex()] = {
unit = unit,
entity = entity,
range = 180,
container = container,
playerID = playerID,
action = function(playerID, container, unit, target)
if IsValidEntity(target) and target:IsAlive() and container:ContainsItem(item) then
container:RemoveItem(item)
Containers:AddItemToUnit(target, item)
end
unit:Stop()
end,
}
elseif IsValidEntity(entity) and entity:GetClassname() == "ent_dota_shop" and item:IsSellable() then
ExecuteOrderFromTable({
UnitIndex= unit:GetEntityIndex(),
OrderType= DOTA_UNIT_ORDER_MOVE_TO_TARGET,
TargetIndex= entity:GetEntityIndex(),
})
Containers.rangeActions[unit:GetEntityIndex()] = {
unit = unit,
entity = entity,
range = 425,
container = container,
playerID = playerID,
action = function(playerID, container, unit, target)
if IsValidEntity(target) and container:ContainsItem(item) then
local cost = item:GetCost()
if GameRules:GetGameTime() - item:GetPurchaseTime() > 10 then
cost = cost /2
end
container:RemoveItem(item)
item:RemoveSelf()
PlayerResource:ModifyGold(playerID, cost, false, DOTA_ModifyGold_SellItem)
local player = PlayerResource:GetPlayer(playerID)
if player then
SendOverheadEventMessage(player, OVERHEAD_ALERT_GOLD, unit, cost, player)
EmitSoundOnClient("General.Sell", player)
end
end
unit:Stop()
end,
}
else
local pos = unitpos
if dist > 150 *.9 then
pos = position + diff:Normalized() * 150 * .9
end
--DebugDrawCircle(pos, Vector(255,0,0), 1, 50.0, true, 1)
--unit:MoveToPosition(pos)
ExecuteOrderFromTable({
UnitIndex= unit:GetEntityIndex(),
OrderType= DOTA_UNIT_ORDER_MOVE_TO_POSITION,
Position= pos,
})
Containers.rangeActions[unit:GetEntityIndex()] = {
unit = unit,
--entity = target,
position = position,
range = 150,
container = container,
playerID = playerID,
action = function(playerID, container, unit, target)
if container:ContainsItem(item) then
container:RemoveItem(item)
CreateItemOnPositionSync(position, item)
end
end,
}
end
end
function Containers:OnCloseClicked(playerID, container, unit)
Containers:print('Containers:OnCloseClicked', playerID, container, unit)
container:Close(playerID)
end
function Containers:OnButtonPressed(playerID, container, unit, buttonNumber, buttonName)
print('Button ' .. buttonNumber .. ':\'' .. buttonName .. '\' Pressed by player:' .. playerID .. ' for container ' .. container.id .. '. No OnButtonPressed handler.')
end
function Containers:GetEntityContainers(entity)
if entity and type(entity) ~= "number" and entity.GetEntityIndex and IsValidEntity(entity) then
entity = entity:GetEntityIndex()
end
local tab = {}
for id,cont in pairs(Containers.entityContainers[entity] or {}) do
table.insert(tab, cont)
end
return tab
end
function Containers:SetRangeAction(unit, tab)
if not IsValidEntity(unit) then
return
end
local range = tab.range or 150
if tab.container then range = (tab.container:GetRange() or 150) end
local tpos = tab.position or tab.entity:GetAbsOrigin()
local unitpos = unit:GetAbsOrigin()
local diff = unitpos - tpos
local dist = diff:Length2D()
local pos = unitpos
if dist > range * .9 then
pos = tpos + diff:Normalized() * range * .9
end
tab.unit = unit
if tab.entity and not tab.entity.GetContainedItem then
ExecuteOrderFromTable({
UnitIndex= unit:GetEntityIndex(),
OrderType= DOTA_UNIT_ORDER_MOVE_TO_TARGET,
TargetIndex= tab.entity:GetEntityIndex(),
})
else
ExecuteOrderFromTable({
UnitIndex= unit:GetEntityIndex(),
OrderType= DOTA_UNIT_ORDER_MOVE_TO_POSITION,
Position = pos,
})
end
Containers.rangeActions[unit:GetEntityIndex()] = tab
end
function Containers:SetDefaultInventory(unit, container)
if not self.initialized then
print('[containers.lua] FATAL: Containers:Init() has not been called in the Activate() function chain!')
return
end
self.defaultInventories[unit:GetEntityIndex()] = container
end
function Containers:GetDefaultInventory(unit)
local di = self.defaultInventories[unit:GetEntityIndex()]
if IsValidContainer(di) then
return di
else
self.defaultInventories[unit:GetEntityIndex()] = nil
return nil
end
end
function Containers:CreateShop(cont)
local shop = self:CreateContainer(cont)
local ptID = shop.ptID
local pt = {shop = 1,
}
if cont.prices then
for k,v in pairs(cont.prices) do
local item = k
if type(k) ~= "number" then
item = k:GetEntityIndex()
end
pt['price' .. k] = v
end
end
if cont.stocks then
for k,v in pairs(cont.stocks) do
local item = k
if type(k) ~= "number" then
item = k:GetEntityIndex()
end
pt['stock' .. k] = v
end
end
PlayerTables:SetTableValues(ptID, pt)
function shop:BuyItem(playerID, unit, item)
local cost = self:GetPrice(item)
local stock = self:GetStock(item)
local owner = PlayerResource:GetSelectedHeroEntity(playerID)
local gold = PlayerResource:GetGold(playerID)
if gold >= cost and (stock == nil or stock > 0) then
local newItem = CreateItem(item:GetAbilityName(), owner, owner)
newItem:SetLevel(item:GetLevel())
newItem:SetCurrentCharges(item:GetCurrentCharges())
PlayerResource:SpendGold(playerID, cost, DOTA_ModifyGold_PurchaseItem)
if stock then
self:SetStock(item, stock-1)
end
Containers:EmitSoundOnClient(playerID, "General.Buy")
return newItem
elseif stock ~= nil and stock <= 0 then
Containers:DisplayError(playerID, "#dota_hud_error_item_out_of_stock")
elseif gold < cost then
Containers:DisplayError(playerID, "#dota_hud_error_not_enough_gold")
end
end
function shop:SellItem()
end
function shop:GetPrice(item)
item = GetItem(item)
return PlayerTables:GetTableValue(ptID, "price" .. item:GetEntityIndex()) or item:GetCost()
end
function shop:SetPrice(item, price)
item = GetItem(item)
if price then
PlayerTables:SetTableValue(ptID, "price" .. item:GetEntityIndex(), price)
else
PlayerTables:DeleteTableKey(ptID, "price" .. item:GetEntityIndex())
end
end
function shop:GetStock(item)
item = GetItem(item)
return PlayerTables:GetTableValue(ptID, "stock" .. item:GetEntityIndex())
end
function shop:SetStock(item, stock)
item = GetItem(item)
if stock then
PlayerTables:SetTableValue(ptID, "stock" .. item:GetEntityIndex(), stock)
else
PlayerTables:DeleteTableKey(ptID, "stock" .. item:GetEntityIndex())
end
end
if not cont.canDragWithin then shop.canDragWithin = {} end
shop:AddSkin("ContainerShop")
if not cont.OnDragWorld then shop:OnDragWorld(false) end
if not cont.OnDragWithin then shop:OnDragWithin(false) end
if not cont.OnLeftClick then shop:OnLeftClick(false) end
if not cont.OnDragTo then
shop:OnDragTo(function(playerID, container, unit, item, fromSlot, toContainer, toSlot)
Containers:print('Shop:OnDragTo', playerID, container, unit, item, fromSlot, toContainer, toSlot)
end)
end
if not cont.OnDragFrom then
shop:OnDragFrom(function(playerID, container, unit, item, fromSlot, toContainer, toSlot)
Containers:print('Shop:OnDragFrom', playerID, container, unit, item, fromSlot, toContainer, toSlot)
end)
end
--[[shop:OnLeftClick(function(playerID, container, unit, item, slot)
print("Shop:OnLeftClick", playerID, container, unit, item:GetEntityIndex(), slot)
end)]]
if not cont.OnRightClick then
shop:OnRightClick(function(playerID, container, unit, item, slot)
Containers:print("Shop:OnRightClick", playerID, container, unit, item:GetEntityIndex(), slot)
local defInventory = Containers:GetDefaultInventory(unit)
if not defInventory and not unit:HasInventory() then return end
local item = container:BuyItem(playerID, unit, item)
Containers:AddItemToUnit(unit, item)
end)
end
return shop
end
function Containers:CreateContainer(cont)
if not self.initialized then
print('[containers.lua] FATAL: Containers:Init() has not been called in the Activate() function chain!')
return
end
local pt =
{id = self.nextID,
ptID = ID_BASE .. self.nextID,
--unit = cont.unit
layout = cont.layout or {2,2},
size = 0, -- calculated below
rowStarts = {}, -- calculated below
--slot1 = 1111, -- set up below
--slot2 = 1122, -- set up below
skins = {},
buttons = cont.buttons or {},
headerText = cont.headerText or "Container",
draggable = cont.draggable or true,
position = cont.position or "100px 200px 0px",
equipment = cont.equipment,
layoutFile = cont.layoutFile,
OnLeftClick = type(cont.OnLeftClick) == "function" and true or cont.OnLeftClick,
OnRightClick = type(cont.OnRightClick) == "function" and true or cont.OnRightClick,
OnDragFrom = type(cont.OnDragFrom) == "function" and true or cont.OnDragFrom,
OnDragWorld = false,
OnCloseClicked = type(cont.OnCloseClicked) == "function" and true or cont.OnCloseClicked,
OnButtonPressed = type(cont.OnButtonPressed) == "function" and true or cont.OnButtonPressed,
OnLeftClickJS = cont.OnLeftClickJS,
OnRightClickJS = cont.OnRightClickJS,
OnDoubleClickJS = cont.OnDoubleClickJS,
OnMouseOutJS = cont.OnMouseOutJS,
OnMouseOverJS = cont.OnMouseOverJS,
OnButtonPressedJS=cont.OnButtonPressedJS,
OnCloseClickedJS =cont.OnCloseClickedJS,
}
local c = {id = pt.id,
ptID = pt.ptID,
items = {},
itemNames = {},
subs = {},
opens = {},
range = cont.range,
closeOnOrder = cont.closeOnOrder == nil and false or cont.closeOnOrder,
canDragFrom = {},
canDragTo = {},
canDragWithin = {},
appliedPassives = {},
cleanupTimer = nil,
forceOwner = cont.forceOwner,
forcePurchaser = cont.forcePurchaser,
--entity = nil,
_OnLeftClick = cont.OnLeftClick,
_OnRightClick = cont.OnRightClick,
_OnDragTo = cont.OnDragTo,
_OnDragFrom = cont.OnDragFrom,
_OnDragWithin = cont.OnDragWithin,
_OnDragWorld = cont.OnDragWorld,
_OnCloseClicked = cont.OnCloseClicked,
_OnButtonPressed = cont.OnButtonPressed,
_OnEntityOrder = cont.OnEntityOrder,
_OnEntityDrag = cont.OnEntityDrag,
_OnClose = cont.OnClose,
_OnOpen = cont.OnOpen,
_OnSelect = cont.OnSelect,
_OnDeselect = cont.OnDeselect,
AddItemFilter = cont.AddItemFilter,
}
if cont.OnDragWorld ~= nil and (type(cont.OnDragWorld) == "function" or cont.OnDragWorld == true) then
pt.OnDragWorld = true
end
--if cont.setOwner then c.setOwner = cont.setOwner end
--if cont.setPurchaser then c.setOwner = cont.setPurchaser end
if cont.entity and type(cont.entity) == "number" then
pt.entity = cont.entity
elseif cont.entity and cont.entity.GetEntityIndex then
pt.entity = cont.entity:GetEntityIndex()
end
if pt.entity then
Containers.entityContainers[pt.entity] = Containers.entityContainers[pt.entity] or {}
Containers.entityContainers[pt.entity][c.id] = c
end
for i,row in ipairs(pt.layout) do
table.insert(pt.rowStarts, pt.size+1)
pt.size = pt.size + row
end
if cont.skins then
for k,v in pairs(cont.skins) do
if type(v) == "string" then
pt.skins[v] = true
end
end
end
if cont.items then
for k,v in pairs(cont.items) do
if type(k) == "number" then
local item = v
if type(v) == "number" then
item = EntIndexToHScript(item)
end
if item and IsValidEntity(item) and item.IsItem and item:IsItem() then
local itemid = item:GetEntityIndex()
local itemname = item:GetAbilityName()
pt['slot' .. k] = itemid
c.items[itemid] = k
c.itemNames[itemname] = c.itemNames[itemname] or {}
c.itemNames[itemname][itemid] = k
if cont.equipment and pt.entity then
ApplyPassives(c, item, EntIndexToHScript(pt.entity))
end
end
end
end
end
if cont.equipment then
c.cleanupTimer = Timers:CreateTimer(1, function()
for itemID, mods in pairs(c.appliedPassives) do
if not IsValidEntity(EntIndexToHScript(itemID)) or not c:ContainsItem(itemID) then
for _, mod in ipairs(mods) do
mod:Destroy()
end
c.appliedPassives[itemID] = nil
end
end
return 1
end)
end
if cont.cantDragFrom then
for _,pid in ipairs(cont.cantDragFrom) do
if type(pid) == "number" then
c.canDragFrom[pid] = false
end
end
end
if cont.cantDragTo then
for _,pid in ipairs(cont.cantDragTo) do
if type(pid) == "number" then
c.canDragTo[pid] = false
end
end
end
if cont.pids then
for _,pid in ipairs(cont.pids) do
c.subs[pid] = true
end
end
PlayerTables:CreateTable(c.ptID, pt, c.subs)
function c:ActivateItem(unit, item, playerID)
if item:GetOwner() ~= unit or not item:IsFullyCastable() then
Containers:EmitSoundOnClient(playerID, "General.Cancel")
return
end
local playerID = playerID or unit:GetPlayerOwnerID()
local behavior = item:GetBehavior()
local targetType = item:GetAbilityTargetType()
local toggle = bit.band(behavior, DOTA_ABILITY_BEHAVIOR_TOGGLE) ~= 0
local unrestricted = bit.band(behavior, DOTA_ABILITY_BEHAVIOR_UNRESTRICTED) ~= 0
local rootDisables = bit.band(behavior, DOTA_ABILITY_BEHAVIOR_ROOT_DISABLES) ~= 0
local channelled = bit.band(behavior, DOTA_ABILITY_BEHAVIOR_CHANNELLED) ~= 0
local noTarget = bit.band(behavior, DOTA_ABILITY_BEHAVIOR_NO_TARGET) ~= 0
local treeTarget = bit.band(targetType, DOTA_UNIT_TARGET_TREE) ~= 0
if unit:IsStunned() and not unrestricted then
Containers:DisplayError(playerID, "#dota_hud_error_unit_command_restricted")
return
end
if unit:IsRooted() and rootDisables then
Containers:DisplayError(playerID, "#dota_hud_error_ability_disabled_by_root")
return
end
if noTarget and not channelled then
item:PayGoldCost()
item:PayManaCost()
item:StartCooldown(item:GetCooldown(item:GetLevel()))
if toggle then
item:OnToggle()
else
item:OnSpellStart()
end
else
local abil = unit:FindAbilityByName("containers_lua_targeting")
if treeTarget then
if unit:HasAbility("containers_lua_targeting") then unit:RemoveAbility("containers_lua_targeting") end
abil = unit:FindAbilityByName("containers_lua_targeting_tree")
elseif unit:HasAbility("containers_lua_targeting_tree") then
unit:RemoveAbility("containers_lua_targeting_tree")
end
if not abil then
-- no ability proxy found, add
local abilSlot = -1
for i=15,0,-1 do
local ab = unit:GetAbilityByIndex(i)
if not ab then
abilSlot = i
break
end
end
if abilSlot == -1 then
print("[containers.lua] ERROR: 'containers_lua-targeting' ability not found for unit '" .. unit:GetUnitName() .. '" and all ability slots are full.')
return
end
if treeTarget then
abil = unit:AddAbility("containers_lua_targeting_tree")
--abil = unit:FindAbilityByName("containers_lua_targeting_tree")
else
abil = unit:AddAbility("containers_lua_targeting")
--abil = unit:FindAbilityByName("containers_lua_targeting")
end
abil:SetLevel(1)
end
abil:SetHidden(false)
abil.proxyItem = item
local aoe = nil
local iname = item:GetAbilityName()
if iname == "item_veil_of_discord" then
aoe = 600
elseif Containers.itemKV[iname] then
aoe = Containers.itemKV[iname].AOERadius
end
CustomNetTables:SetTableValue("containers_lua", tostring(abil:GetEntityIndex()), {behavior=behavior, aoe=aoe, range=item:GetCastRange(),
targetType=targetType, targetTeam=item:GetAbilityTargetTeam(), targetFlags=item:GetAbilityTargetFlags(),
channelTime=item:GetChannelTime(), channelCost=item:GetChannelledManaCostPerSecond(item:GetLevel()),
proxyItem=item:GetEntityIndex()})
local player = PlayerResource:GetPlayer(playerID)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "cont_execute_proxy", {unit=unit:GetEntityIndex()})
end
end
end
function c:GetAllOpen()
return self.opens
end
function c:IsOpen(pid)
return self.opens[pid] ~= nil
end
function c:Open(pid)
self.opens[pid] = true
PlayerTables:AddPlayerSubscription(self.ptID, pid)
if self:IsCloseOnOrder() then
Containers.closeOnOrders[pid][self.id] = self
end
local player = PlayerResource:GetPlayer(pid)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "cont_open_container", {id=self.id} )
end
if self._OnOpen then
self._OnOpen(pid, self)
end
end
function c:Close(pid)
if self.opens[pid] == nil then return end
self.opens[pid] = nil
if not self.subs[pid] then
PlayerTables:RemovePlayerSubscription(self.ptID, pid)
end
if self:IsCloseOnOrder() then
Containers.closeOnOrders[pid][self.id] = nil
end
local player = PlayerResource:GetPlayer(pid)
if player then
CustomGameEventManager:Send_ServerToPlayer(player, "cont_close_container", {id=self.id} )
end
if self._OnClose then
self._OnClose(pid, self)
end
end
function c:Delete(deleteContents)
Containers:DeleteContainer(self, deleteContents)
end
function c:AddSubscription(pid)
self.subs[pid] = true
PlayerTables:AddPlayerSubscription(self.ptID, pid)
end
function c:RemoveSubscription(pid)
self.subs[pid] = nil
if not self.opens[pid] then
PlayerTables:RemovePlayerSubscription(self.ptID, pid)
end
end
function c:GetSubscriptions()
return self.subs
end
function c:IsSubscribed(pid)
return self.subs[pid] ~= nil
end
function c:SwapSlots(slot1, slot2, allowCombine)
local item1 = self:GetItemInSlot(slot1)
local item2 = self:GetItemInSlot(slot2)
if item1 and item2 then
return self:SwapItems(item1, item2, allowCombine)
elseif item1 then
local itemid = item1:GetEntityIndex()
local itemname = item1:GetAbilityName()
self.items[itemid] = slot2
self.itemNames[itemname][itemid] = slot2
PlayerTables:SetTableValue(self.ptID, "slot"..slot2, itemid)
PlayerTables:DeleteTableKey(self.ptID, "slot"..slot1)
return true
elseif item2 then
local itemid = item2:GetEntityIndex()
local itemname = item2:GetAbilityName()
self.items[itemid] = slot1
self.itemNames[itemname][itemid] = slot1
PlayerTables:SetTableValue(self.ptID, "slot"..slot1, itemid)
PlayerTables:DeleteTableKey(self.ptID, "slot"..slot2)
return true
end
return false
end
function c:SwapItems(item1, item2, allowCombine)
item1 = GetItem(item1)
item2 = GetItem(item2)
local i1id = item1:GetEntityIndex()
local i1name = item1:GetAbilityName()
local i2id = item2:GetEntityIndex()
local i2name = item2:GetAbilityName()
local i1 = self.items[i1id]
local i2 = self.items[i2id]
if i1 and i2 then
if allowCombine and i1name == i2name and item1:IsStackable() and item2:IsStackable() then
self:RemoveItem(item1)
item2:SetCurrentCharges(item2:GetCurrentCharges() + item1:GetCurrentCharges())
item1:RemoveSelf()
return true
end
self.items[i1id] = i2
self.items[i2id] = i1
self.itemNames[i1name][i1id] = i2
self.itemNames[i2name][i2id] = i1
PlayerTables:SetTableValues(self.ptID, {["slot"..i1]=i2id, ["slot"..i2]=i1id})
return true
end
return false
end
function c:ContainsItem(item)
item = GetItem(item)
if not item then return false end
return self.items[item:GetEntityIndex()] ~= nil
end
function c:GetSlotForItem(item)
item = GetItem(item)
return self.items[item:GetEntityIndex()]
end
function c:GetRowColumnForItem(item)
item = GetItem(item)
local itemid = item:GetEntityIndex()
local slot = self.items[itemid]
if not slot then
return nil, nil
end
local size = self:GetSize()
if slot > size then
return nil, nil
end
local rowStarts = PlayerTables:GetTableValue(self.ptID, "rowStarts")
for row,start in ipairs(rowStarts) do
if start > slot then
local prev = row-1
return prev, (slot - rowStarts[prev] + 1)
end
end
local row = #rowStarts
return row, (slot - rowStarts[row] + 1)
end
function c:GetAllItems()
local items = {}
for slot=1,self:GetSize() do
local item = self:GetItemInSlot(slot)
if item then
table.insert(items, item)
end
end
return items
end
function c:GetItemsByName(name)
local nameTable = self.itemNames[name]
local items = {}
if not nameTable then
return items
end
for id,slot in pairs(nameTable) do
local item = GetItem(id)
if item then
table.insert(items, item)
else
nameTable[id] = nil
end
end
return items
end
function c:GetItemInSlot(slot)
local item = PlayerTables:GetTableValue(self.ptID, "slot" .. slot)
if item then
item = EntIndexToHScript(item)
if item and not IsValidEntity(item) then
PlayerTables:DeleteTableKey(self.ptID, "slot" .. slot)
return nil
elseif item and IsValidEntity(item) and item.IsItem and item:IsItem() then
return item
end
end
return nil
end
function c:GetItemInRowColumn(row, column)
local rowStarts = PlayerTables:GetTableValue(self.ptID, "rowStarts")
if not rowStarts[row] then
return nil
end
local nextRowStart = rowStarts[row+1] or self:GetSize() + 1
local slot = rowStarts[row] + column - 1
if slot >= nextRowStart then
return nil
end
return self:GetItemInSlot(slot)
end
function c:AddItem(item, slot, column, bypassFilter)
item = GetItem(item)
if slot and type(slot) == "number" and column and type(column) == "number" then
local rowStarts = PlayerTables:GetTableValue(self.ptID, "rowStarts")
if not rowStarts[slot] then
print("[containers.lua] Request to add item in row " .. slot .. " -- row not found. ")
return false
end
local nextRowStart = rowStarts[slot+1] or self:GetSize() + 1
local newslot = rowStarts[slot] + column - 1
if newslot >= nextRowStart then
print("[containers.lua] Request to add item in row " .. slot .. ", column " .. column .. " -- column exceeds row length. ")
return false
end
slot = newslot
end
local findStack = slot == nil
slot = slot or 1
local size = self:GetSize()
if slot > size then
print("[containers.lua] Request to add item in slot " .. slot .. " -- exceeding container size " .. size)
return false
end
local func = c.AddItemFilter
if not bypassFilter and c.AddItemFilter then
local status, result = pcall(c.AddItemFilter, c, item, findstack and -1 or slot)
if not status then
print("[containers.lua] AddItemFilter callback error: " .. result)
return false
end
if not result then
return false
end
end
local itemid = item:GetEntityIndex()
local itemname = item:GetAbilityName()
if findStack and item:IsStackable() then
local nameTable = self.itemNames[itemname]
if nameTable then
local lowestSlot = size+1
local lowestItem = nil
for itemid, nameslot in pairs(nameTable) do
if nameslot < lowestSlot then
local item = self:GetItemInSlot(nameslot)
if item then
lowestSlot = nameslot
lowestItem = item
else
nameTable[itemid] = nil
end
end
end
if lowestItem and lowestItem:IsStackable() then
lowestItem:SetCurrentCharges(lowestItem:GetCurrentCharges() + item:GetCurrentCharges())
item:RemoveSelf()
return true
end
end
end
-- check if the slot specified is stackable
if not findStack and item:IsStackable() then
local slotitem = self:GetItemInSlot(slot)
if slotitem and itemname == slotitem:GetAbilityName() and slotitem:IsStackable() then
slotitem:SetCurrentCharges(slotitem:GetCurrentCharges() + item:GetCurrentCharges())
item:RemoveSelf()
return true
end
end
for i=slot,size do
local slotitem = self:GetItemInSlot(i)
if not slotitem then
self.items[itemid] = i
self.itemNames[itemname] = self.itemNames[itemname] or {}
self.itemNames[itemname][itemid] = i
if self.forceOwner then
item:SetOwner(self.forceOwner)
elseif self.forceOwner == false then
item:SetOwner(nil)
end
if self.forcePurchaser then
item:SetPurchaser(self.forcePurchaser)
elseif self.forceOwner == false then
item:SetPurchaser(nil)
end
if self:IsEquipment() then
ApplyPassives(self, item)
end
PlayerTables:SetTableValue(self.ptID, "slot" .. i, itemid)
return true
end
end
return false
end
function c:RemoveItem(item)
item = GetItem(item)
local slot = self.items[item:GetEntityIndex()]
local nameTable = self.itemNames[item:GetAbilityName()]
local itemid = item:GetEntityIndex()
self.items[itemid] = nil
nameTable[itemid] = nil
if self:IsEquipment() then
local mods = self.appliedPassives[itemid]
if mods then
for _, mod in ipairs(mods) do
mod:Destroy()
end
end
self.appliedPassives[itemid] = nil
end
PlayerTables:DeleteTableKey(self.ptID, "slot" .. slot)
end
function c:ClearSlot(slot)
local item = self:GetItemInSlot(slot)
if IsValidEntity(item) then
self:RemoveItem(item)
else
PlayerTables:DeleteTableKey(self.ptID, "slot" .. slot)
end
end
function c:GetContainerIndex()
return self.id
end
function c:GetHeaderText()
local headerText = PlayerTables:GetTableValue(self.ptID, "headerText")
return headerText
end
function c:SetHeaderText(header)
PlayerTables:SetTableValue(self.ptID, "headerText", header)
end
function c:GetSize()
local size = PlayerTables:GetTableValue(self.ptID, "size")
return size
end
function c:GetNumItems()
return #c:GetAllItems()
end
function c:GetLayout()
local layout = PlayerTables:GetTableValue(self.ptID, "layout")
return layout
end
function c:SetLayout(layout, removeOnContract)
local size = 0
local rowStarts = {}
for i,row in ipairs(layout) do
table.insert(rowStarts, size+1)
size = size + row
end
local oldSize = self:GetSize()
local changes = {}
if removeOnContract and size < oldSize then
local deletions = {}
for i=size+1,oldSize do
local item = self:GetItemInSlot(i)
if item then
local itemid = item:GetEntityIndex()
local itemname = item:GetAbilityName()
local nameTable = self.itemNames[item:GetAbilityName()]
self.items[item:GetEntityIndex()] = nil
nameTable[item:GetEntityIndex()] = nil
if self:IsEquipment() then
local mods = self.appliedPassives[itemid]
if mods then
for _, mod in ipairs(mods) do
mod:Destroy()
end
end
self.appliedPassives[itemid] = nil
end
table.insert(deletions, "slot"..i)
end
end
PlayerTables:DeleteTableKeys(self.ptID, deletions)
end
changes.layout = layout
changes.size = size
changes.rowStarts = rowStarts
PlayerTables:SetTableValues(self.ptID, changes)
end
function c:GetRange()
return self.range
end
function c:SetRange(range)
self.range = range
--[[if range then
PlayerTables:SetTableValue(self.ptID, "range", range)
else
PlayerTables:DeleteTableKey(self.ptID, "range")
end]]
end
function c:AddSkin(skin)
local skins = PlayerTables:GetTableValue(self.ptID, "skins")
skins[skin] = true
PlayerTables:SetTableValue(self.ptID, "skins", skins)
end
function c:RemoveSkin(skin)
local skins = PlayerTables:GetTableValue(self.ptID, "skins")
skins[skin] = nil
PlayerTables:SetTableValue(self.ptID, "skins", skins)
end
function c:GetSkins()
local skins = PlayerTables:GetTableValue(self.ptID, "skins")
return skins
end
function c:HasSkin(skin)
local skins = PlayerTables:GetTableValue(self.ptID, "skins")
return skins[skin] ~= nil
end
function c:SetButton(number, name)
local buttons = PlayerTables:GetTableValue(self.ptID, "buttons")
buttons[number] = name
PlayerTables:SetTableValue(self.ptID, "buttons", buttons)
end
function c:RemoveButton(number)
local buttons = PlayerTables:GetTableValue(self.ptID, "buttons")
buttons[number] = nil
PlayerTables:SetTableValue(self.ptID, "buttons", buttons)
end
function c:GetButtons()
local buttons = PlayerTables:GetTableValue(self.ptID, "buttons")
return buttons
end
function c:GetButtonName(number)
local buttons = PlayerTables:GetTableValue(self.ptID, "buttons")
return buttons[number]
end
function c:GetEntity()
local entity = PlayerTables:GetTableValue(self.ptID, "entity")
if entity then
return EntIndexToHScript(entity)
end
return nil
end
function c:SetEntity(entity)
local old = c:GetEntity()
local num = entity
if entity and type(entity) == "number" then
entity = EntIndexToHScript(entity)
elseif entity and entity.GetEntityIndex then
num = entity:GetEntityIndex()
end
if entity then
PlayerTables:SetTableValue(self.ptID, "entity", num)
Containers.entityContainers[num] = Containers.entityContainers[num] or {}
Containers.entityContainers[num][self.id] = self
elseif old ~= nil then
PlayerTables:DeleteTableKey(self.ptID, "entity")
Containers.entityContainers[old:GetEntityIndex()] = Containers.entityContainers[old:GetEntityIndex()] or {}
Containers.entityContainers[old:GetEntityIndex()][self.id] = nil
end
if self:IsEquipment() and old ~= entity then
for itemID, mods in pairs(self.appliedPassives) do
for _, mod in ipairs(mods) do
mod:Destroy()
end
end
self.appliedPassives = {}
local items = self:GetAllItems()
for _, item in ipairs(items) do
ApplyPassives(self, item)
end
end
end
function c:GetCanDragFromPlayers()
return self.canDragFrom
end
function c:CanDragFrom(pid)
return self.canDragFrom[pid] ~= false
end
function c:SetCanDragFrom(pid, canDrag)
self.canDragFrom[pid] = canDrag
end
function c:GetCanDragToPlayers()
return self.canDragTo
end
function c:CanDragTo(pid)
return self.canDragTo[pid] ~= false
end
function c:SetCanDragTo(pid, canDrag)
self.canDragTo[pid] = canDrag
end
function c:GetCanDragWithinPlayers()
return self.canDragWithin
end
function c:CanDragWithin(pid)
return self.canDragWithin[pid] ~= false
end
function c:SetCanDragWithin(pid, canDrag)
self.canDragWithin[pid] = canDrag
end
function c:IsDraggable()
return PlayerTables:GetTableValue(self.ptID, "draggable")
end
function c:SetDraggable(drag)
PlayerTables:SetTableValue(self.ptID, "draggable", drag)
end
function c:IsEquipment()
local eq = PlayerTables:GetTableValue(self.ptID, "equipment")
if eq then
return true
else
return false
end
end
function c:SetEquipment(equip)
local isEq = self:IsEquipment()
if equip and not isEq then
local items = self:GetAllItems()
for _, item in ipairs(items) do
ApplyPassives(self, item)
end
local c = self
self.cleanupTimer = Timers:CreateTimer(1, function()
for itemID, mods in pairs(c.appliedPassives) do
if not IsValidEntity(EntIndexToHScript(itemID)) or not c:ContainsItem(itemID) then
for _, mod in ipairs(mods) do
mod:Destroy()
end
c.appliedPassives[itemID] = nil
end
end
return 1
end)
elseif not equip and isEq then
local items = self:GetAllItems()
for itemID,mods in pairs(self.appliedPassives) do
for _, mod in ipairs(mods) do
mod:Destroy()
end
end
self.appliedPassives = {}
Timers:RemoveTimer(self.cleanupTimer)
end
PlayerTables:SetTableValue(self.ptID, "equipment", equip)
end
function c:GetForceOwner()
return self.forceOwner
end
function c:GetForcePurchaser()
return self.ForcePurchaser
end
function c:SetForceOwner(owner)
self.forceOwner = owner
end
function c:SetForcePurchaser(purchaser)
self.ForcePurchaser = purchaser
end
function c:IsCloseOnOrder()
return self.closeOnOrder
end
function c:SetCloseOnOrder(close)
if close then
for pid, _ in pairs(self.opens) do
Containers.closeOnOrders[pid][self.id] = self
end
else
for pid,v in pairs(Containers.closeOnOrders) do
v[self.id] = nil
end
end
self.closeOnOrder = close
end
function c:OnLeftClick(fun)
if fun == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnLeftClick")
elseif type(fun) == "function" then
PlayerTables:SetTableValue(self.ptID, "OnLeftClick", true)
else
PlayerTables:SetTableValue(self.ptID, "OnLeftClick", fun)
end
self._OnLeftClick = fun
end
function c:OnRightClick(fun)
if fun == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnRightClick")
elseif type(fun) == "function" then
PlayerTables:SetTableValue(self.ptID, "OnRightClick", true)
else
PlayerTables:SetTableValue(self.ptID, "OnRightClick", fun)
end
self._OnRightClick = fun
end
function c:OnDragTo(fun)
self._OnDragTo = fun
end
function c:OnDragWithin(fun)
self._OnDragWithin = fun
end
function c:OnDragFrom(fun)
if fun == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnDragFrom")
elseif type(fun) == "function" then
PlayerTables:SetTableValue(self.ptID, "OnDragFrom", true)
else
PlayerTables:SetTableValue(self.ptID, "OnDragFrom", fun)
end
self._OnDragFrom = fun
end
function c:OnDragWorld(fun)
if fun == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnDragWorld")
elseif type(fun) == "function" then
PlayerTables:SetTableValue(self.ptID, "OnDragWorld", true)
else
PlayerTables:SetTableValue(self.ptID, "OnDragWorld", fun)
end
self._OnDragWorld = fun
end
function c:OnCloseClicked(fun)
if fun == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnCloseClicked")
elseif type(fun) == "function" then
PlayerTables:SetTableValue(self.ptID, "OnCloseClicked", true)
else
PlayerTables:SetTableValue(self.ptID, "OnCloseClicked", fun)
end
self._OnCloseClicked = fun
end
function c:OnButtonPressed(fun)
if fun == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnButtonPressed")
elseif type(fun) == "function" then
PlayerTables:SetTableValue(self.ptID, "OnButtonPressed", true)
else
PlayerTables:SetTableValue(self.ptID, "OnButtonPressed", fun)
end
self._OnButtonPressed = fun
end
function c:OnEntityOrder(fun)
self._OnEntityOrder = fun
end
function c:OnEntityDrag(fun)
self._OnEntityDrag = fun
end
function c:OnClose(fun)
self._OnClose = fun
end
function c:OnOpen(fun)
self._OnOpen = fun
end
function c:OnSelect(fun)
self._OnSelect = fun
end
function c:OnDeselect(fun)
self._OnDeselect = fun
end
function c:OnLeftClickJS(jsCallback)
if jsCallback == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnLeftClickJS")
else
PlayerTables:SetTableValue(self.ptID, "OnLeftClickJS", jsCallback)
end
end
function c:OnRightClickJS(jsCallback)
if jsCallback == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnRightClickJS")
else
PlayerTables:SetTableValue(self.ptID, "OnRightClickJS", jsCallback)
end
end
function c:OnDoubleClickJS(jsCallback)
if jsCallback == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnDoubleClickJS")
else
PlayerTables:SetTableValue(self.ptID, "OnDoubleClickJS", jsCallback)
end
end
function c:OnMouseOutJS(jsCallback)
if jsCallback == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnMouseOutJS")
else
PlayerTables:SetTableValue(self.ptID, "OnMouseOutJS", jsCallback)
end
end
function c:OnMouseOverJS(jsCallback)
if jsCallback == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnMouseOverJS")
else
PlayerTables:SetTableValue(self.ptID, "OnMouseOverJS", jsCallback)
end
end
function c:OnButtonPressedJS(jsCallback)
if jsCallback == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnButtonPressedJS")
else
PlayerTables:SetTableValue(self.ptID, "OnButtonPressedJS", jsCallback)
end
end
function c:OnCloseClickedJS(jsCallback)
if jsCallback == nil then
PlayerTables:DeleteTableKey(self.ptID, "OnCloseClickedJS")
else
PlayerTables:SetTableValue(self.ptID, "OnCloseClickedJS", jsCallback)
end
end
function c:IsInventory()
return false
end
self.containers[self.nextID] = c
self.nextID = self.nextID + 1
return c
end
function Containers:DeleteContainer(c, deleteContents)
if deleteContents ~= false or c:IsEquipment() then
local items = c:GetAllItems()
for _, item in ipairs(items) do
if c:IsEquipment() then
local mods = c.appliedPassives[item:GetEntityIndex()]
Timers:RemoveTimer(c.cleanupTimer)
if mods then
for _, mod in ipairs(mods) do
mod:Destroy()
end
end
end
if deleteContents then
item:RemoveSelf()
end
end
end
PlayerTables:DeleteTable(c.ptID)
self.containers[c.id] = nil
CustomGameEventManager:Send_ServerToAllClients("cont_delete_container", {id=c.id} )
for k,v in pairs(c) do
c[k] = nil
end
end
function Containers:print(...)
if CONTAINERS_DEBUG then
print(unpack({...}))
end
end
function Containers:PrintTable(t)
if CONTAINERS_DEBUG then
PrintTable(t)
end
end
function IsValidContainer(c)
if c and c.GetAllOpen then
return true
else
return false
end
end
if not Containers.containers then Containers:start() end | mit |
ZuoGuocai/Atlas | lib/auditing.lua | 40 | 1694 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
local user = ""
function read_handshake( )
local con = proxy.connection
print("<-- let's send him some information about us")
print(" server-addr : " .. con.server.dst.name)
print(" client-addr : " .. con.client.src.name)
end
function read_auth( )
local con = proxy.connection
print("--> there, look, the client is responding to the server auth packet")
print(" username : " .. con.client.username)
user = con.client.username
end
function read_auth_result( auth )
local state = auth.packet:byte()
if state == proxy.MYSQLD_PACKET_OK then
print("<-- auth ok");
elseif state == proxy.MYSQLD_PACKET_ERR then
print("<-- auth failed");
else
print("<-- auth ... don't know: " .. string.format("%q", auth.packet));
end
end
function read_query( packet )
print("--> '".. user .."' sent us a query")
if packet:byte() == proxy.COM_QUERY then
print(" query: " .. packet:sub(2))
end
end
| gpl-2.0 |
hqren/Atlas | lib/auditing.lua | 40 | 1694 | --[[ $%BEGINLICENSE%$
Copyright (c) 2007, 2009, Oracle and/or its affiliates. All rights reserved.
This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License as
published by the Free Software Foundation; version 2 of the
License.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
02110-1301 USA
$%ENDLICENSE%$ --]]
local user = ""
function read_handshake( )
local con = proxy.connection
print("<-- let's send him some information about us")
print(" server-addr : " .. con.server.dst.name)
print(" client-addr : " .. con.client.src.name)
end
function read_auth( )
local con = proxy.connection
print("--> there, look, the client is responding to the server auth packet")
print(" username : " .. con.client.username)
user = con.client.username
end
function read_auth_result( auth )
local state = auth.packet:byte()
if state == proxy.MYSQLD_PACKET_OK then
print("<-- auth ok");
elseif state == proxy.MYSQLD_PACKET_ERR then
print("<-- auth failed");
else
print("<-- auth ... don't know: " .. string.format("%q", auth.packet));
end
end
function read_query( packet )
print("--> '".. user .."' sent us a query")
if packet:byte() == proxy.COM_QUERY then
print(" query: " .. packet:sub(2))
end
end
| gpl-2.0 |
tempbottle/elliptics | wireshark/elliptics.lua | 11 | 3222 | do
local elliptics_proto = Proto("elliptics", "Elliptics");
local elliptics_command = function(label, fields)
return {
["label"] = label,
["parse"] = function(buffer, off, tree)
return 1
end
}
end
local commands = {
[1] = elliptics_command(
"DNET_CMD_LOOKUP", {}
),
[2] = elliptics_command(
"DNET_CMD_REVERSE_LOOKUP", {}
),
[3] = elliptics_command(
"DNET_CMD_JOIN", {}
),
[4] = elliptics_command(
"DNET_CMD_WRITE", {}
),
[5] = elliptics_command(
"DNET_CMD_READ", {}
),
[6] = elliptics_command(
"DNET_CMD_LIST", {}
),
[7] = elliptics_command(
"DNET_CMD_EXEC", {}
),
[8] = elliptics_command(
"DNET_CMD_ROUTE_LIST", {}
),
[9] = elliptics_command(
"DNET_CMD_STAT", {}
),
[10] = elliptics_command(
"DNET_CMD_NOTIFY", {}
),
[11] = elliptics_command(
"DNET_CMD_DEL", {}
),
[12] = elliptics_command(
"DNET_CMD_STATUS", {}
),
[13] = elliptics_command(
"DNET_CMD_READ_RANGE", {}
),
[14] = elliptics_command(
"DNET_CMD_DEL_RANGE", {}
),
[15] = elliptics_command(
"DNET_CMD_AUTH", {}
),
[16] = elliptics_command(
"DNET_CMD_BULK_READ", {}
),
[17] = elliptics_command(
"DNET_CMD_DEFRAG", {}
),
[18] = elliptics_command(
"DNET_CMD_ITERATOR", {}
)
}
local unknown_command = elliptics_command(
"DNET_CMD_UNKNOWN", {}
)
function elliptics_proto.dissector(buffer, pinfo, tree)
pinfo.cols.protocol = "ELLIPTICS"
local header_size = 104
local buf_len = buffer:len()
local offset = 0
while offset + header_size <= buf_len do
local data_size = buffer(96, 4):le_uint()
local packet_size = header_size + data_size
if buf_len - offset < packet_size then
break
end
local item = tree:add(elliptics_proto, buffer(offset, packet_size), "Elliptics CMD Header")
local dnet_id = item:add(elliptics_proto, buffer(offset + 0, 72), "dnet_id")
dnet_id:add(buffer(offset + 0, 64), "id: " .. tostring(buffer(offset + 0, 64)))
dnet_id:add(buffer(offset + 64, 4), "group_id: " .. buffer(offset + 64, 4):le_uint())
dnet_id:add(buffer(offset + 68, 4), "type: " .. buffer(offset + 68, 4):le_uint())
local cmd_id = buffer(offset + 76, 4):le_uint()
local cmd = commands[cmd_id]
local cmd_label
if cmd == nil then
cmd = unknown_command
end
item:add(buffer(offset + 72, 4), "status: " .. buffer(offset + 72, 4):le_uint())
item:add(buffer(offset + 76, 4), "cmd: " .. cmd.label .. " (" .. cmd_id .. ")")
item:add(buffer(offset + 80, 8), "flags: " .. tostring(buffer(offset + 80, 8)))
item:add(buffer(offset + 88, 8), "trans: " .. tostring(buffer(offset + 88, 8)))
item:add(buffer(offset + 96, 8), "size: " .. buffer(offset + 96, 4):le_uint())
if data_size > 0 then
item:add(buffer(offset + 104, data_size), "data: " .. tostring(buffer(offset + 104, data_size)))
end
offset = offset + packet_size
end
if offset ~= buf_len then
pinfo.desegment_len = DESEGMENT_ONE_MORE_SEGMENT
pinfo.desegment_offset = offset
return DESEGMENT_ONE_MORE_SEGMENT
end
return buf_len
end
local tcp_table = DissectorTable.get("tcp.port")
tcp_table:add(1025, elliptics_proto)
end
| lgpl-3.0 |
nasomi/darkstar | scripts/zones/Mhaura/npcs/Hagain.lua | 17 | 2194 | -----------------------------------
-- Area: Mhaura
-- NPC: Hagain
-- Standard Info NPC
-----------------------------------
package.loaded["scripts/zones/Mhaura/TextIDs"] = nil;
-----------------------------------
require("scripts/zones/Mhaura/TextIDs");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
local hittingTheMarquisate = player:getQuestStatus(WINDURST,HITTING_THE_MARQUISATE);
if (hittingTheMarquisate == QUEST_ACCEPTED and trade:hasItemQty(1091,1) and trade:getItemCount() == 1) then -- Trade Chandelier coal
player:startEvent(0x2715);
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hittingTheMarquisateHagainCS = player:getVar("hittingTheMarquisateHagainCS");
if (hittingTheMarquisateHagainCS == 1) then -- start first part of miniquest thf af3
player:startEvent(0x2713,0,BOMB_INCENSE);
elseif (hittingTheMarquisateHagainCS >= 2 and hittingTheMarquisateHagainCS < 9) then -- dialog during mini quest thf af3
player:startEvent(0x2714,0,BOMB_INCENSE);
elseif (hittingTheMarquisateHagainCS == 9) then
player:startEvent(0x2716); -- after the mini quest
else
player:startEvent(0x2712); -- 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 == 0x2713) then
player:setVar("hittingTheMarquisateHagainCS",2);
player:addKeyItem(BOMB_INCENSE);
player:messageSpecial(KEYITEM_OBTAINED,BOMB_INCENSE);
elseif (csid == 0x2715) then
player:setVar("hittingTheMarquisateHagainCS",9);
player:delKeyItem(BOMB_INCENSE);
player:tradeComplete();
end
end;
| gpl-3.0 |
nasomi/darkstar | scripts/zones/Bastok_Mines/npcs/Gerbaum.lua | 17 | 2169 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Gerbaum
-- Starts & Finishes Repeatable Quest: Minesweeper (100%)
-----------------------------------
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/titles");
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
count = trade:getItemCount();
ZeruhnSoot = trade:hasItemQty(560,3);
if (ZeruhnSoot == true and count == 3) then
MineSweep = player:getQuestStatus(BASTOK,MINESWEEPER);
if (MineSweep >= 1) then
player:tradeComplete();
player:startEvent(0x006d);
end
end
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
MineSweep = player:getQuestStatus(BASTOK,MINESWEEPER);
if (MineSweep == 0) then
player:startEvent(0x006c);
else
rand = math.random(1,2);
if (rand == 1) then
player:startEvent(0x0016);
else
player:startEvent(0x0017);
end
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
MineSweep = player:getQuestStatus(BASTOK,MINESWEEPER);
if (csid == 0x006c) then
if (MineSweep == 0) then
player:addQuest(BASTOK,MINESWEEPER);
end
elseif (csid == 0x006d) then
if (MineSweep == 1) then
player:completeQuest(BASTOK,MINESWEEPER);
player:addFame(BASTOK,BAS_FAME*75);
player:addTitle(ZERUHN_SWEEPER);
else
player:addFame(BASTOK,BAS_FAME*8);
end
player:addGil(GIL_RATE*150);
player:messageSpecial(GIL_OBTAINED,GIL_RATE*150);
end
end;
| gpl-3.0 |
RhenaudTheLukark/CreateYourFrisk | Assets/Mods/Examples/Lua/Encounters/01 - Two monsters.lua | 1 | 1414 | encountertext = "Your path is blocked by two mannequins!" --Modify as necessary. It will only be read out in the action select screen.
wavetimer = 4
arenasize = {155, 130}
nextwaves = {"bullettest_touhou"}
autolinebreak = true
enemies = {"twoMonstersPoseur", "twoMonstersPosette"}
enemypositions = { {-180, 0}, {120, 0} }
-- A custom list with attacks to choose from. Actual selection happens in EnemyDialogueEnding(). Put here in case you want to use it.
possible_attacks = {"bullettest_bouncy", "bullettest_chaserorb", "bullettest_touhou"}
function EncounterStarting()
-- If you want to change the game state immediately, this is the place.
end
function EnemyDialogueStarting()
-- Good location for setting monster dialogue depending on how the battle is going.
end
function EnemyDialogueEnding()
-- Good location to fill the 'nextwaves' table with the attacks you want to have simultaneously.
-- This example line below takes a random attack from 'possible_attacks'.
nextwaves = { possible_attacks[math.random(#possible_attacks)] }
end
function DefenseEnding() --This built-in function fires after the defense round ends.
encountertext = RandomEncounterText() --This built-in function gets a random encounter text from a random enemy.
end
function HandleSpare()
State("ENEMYDIALOGUE")
end
function HandleItem(ItemID)
BattleDialog({"Selected item " .. ItemID .. "."})
end | gpl-3.0 |
nasomi/darkstar | scripts/zones/Garlaige_Citadel/npcs/qm6.lua | 34 | 1385 | -----------------------------------
-- Area: Garlaige Citadel
-- NPC: qm6 (???)
-- Involved in Quest: Hitting the Marquisate (THF AF3)
-- @pos -220.039 -5.500 194.192 200
-----------------------------------
package.loaded["scripts/zones/Garlaige_Citadel/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/zones/Garlaige_Citadel/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
local hittingTheMarquisateHagainCS = player:getVar("hittingTheMarquisateHagainCS");
if (hittingTheMarquisateHagainCS == 2) then
player:messageSpecial(PRESENCE_FROM_CEILING);
player:setVar("hittingTheMarquisateHagainCS",3);
end
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID2: %u",csid);
--printf("RESULT2: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
| gpl-3.0 |
nasomi/darkstar | scripts/globals/items/sandfish.lua | 18 | 1318 | -----------------------------------------
-- ID: 4291
-- Item: sandfish
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity 3
-- Mind -5
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
local result = 0;
if (target:getRace() ~= 7) then
result = 247;
end
if (target:getMod(MOD_EAT_RAW_FISH) == 1) then
result = 0;
end
if (target:hasStatusEffect(EFFECT_FOOD) == true or target:hasStatusEffect(EFFECT_FIELD_SUPPORT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,4291);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, 3);
target:addMod(MOD_MND, -5);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, 3);
target:delMod(MOD_MND, -5);
end;
| gpl-3.0 |
nasomi/darkstar | scripts/commands/hide.lua | 62 | 1164 | ---------------------------------------------------------------------------------------------------
-- func: hide
-- desc: Hides the GM from other players.
---------------------------------------------------------------------------------------------------
cmdprops =
{
permission = 1,
parameters = "s"
};
function onTrigger(player, cmd)
-- Obtain the players hide status..
local isHidden = player:getVar("GMHidden");
if (cmd ~= nil) then
if (cmd == "status") then
player:PrintToPlayer(string.format('Current hide status: %s', tostring(isHidden)));
return;
end
end
-- Toggle the hide status..
if (isHidden == 0) then
isHidden = 1;
else
isHidden = 0;
end
-- If hidden animate us beginning our hide..
if (isHidden == 1) then
player:setVar( "GMHidden", 1 );
player:setGMHidden(true);
player:PrintToPlayer( "You are now GM hidden from other players." );
else
player:setVar( "GMHidden", 0 );
player:setGMHidden(false);
player:PrintToPlayer( "You are no longer GM hidden from other players." );
end
end | gpl-3.0 |
nasomi/darkstar | scripts/zones/Apollyon/mobs/Inhumer.lua | 16 | 1161 | -----------------------------------
-- Area: Apollyon SE
-- NPC: Inhumer
-----------------------------------
package.loaded["scripts/zones/Apollyon/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/limbus");
require("scripts/zones/Apollyon/TextIDs");
-----------------------------------
-- onMobSpawn Action
-----------------------------------
function onMobSpawn(mob)
end;
-----------------------------------
-- onMobEngaged
-----------------------------------
function onMobEngaged(mob,target)
end;
-----------------------------------
-- onMobDeath
-----------------------------------
function onMobDeath(mob,killer)
local mobID = mob:getID();
if (mobID ==16933025) then -- time
GetNPCByID(16932864+246):setPos(343,-1,-296);
GetNPCByID(16932864+246):setStatus(STATUS_NORMAL);
elseif (mobID ==16933028) then -- recover
GetNPCByID(16932864+248):setPos(376,-1,-259);
GetNPCByID(16932864+248):setStatus(STATUS_NORMAL);
elseif (mobID ==16933022) then -- item
GetNPCByID(16932864+247):setPos(307,-1,-309);
GetNPCByID(16932864+247):setStatus(STATUS_NORMAL);
end
end; | gpl-3.0 |
TeamHypersomnia/Augmentations | hypersomnia/content/official/gfx/force_grenade.meta.lua | 2 | 2742 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 469,
light_colors = {
"255 0 0 255",
"103 0 0 255",
"39 0 0 255"
},
radius = {
x = 80,
y = 80
},
standard_deviation = 3
},
generate_desaturation = false
},
offsets = {
gun = {
bullet_spawn = {
x = 0,
y = 0
},
chamber = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
chamber_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
detachable_magazine = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shell_spawn = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
item = {
attachment_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
back_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
beep_offset = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
hand_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder_anchor = {
pos = {
x = 0,
y = 0
},
rotation = 0
}
},
legs = {
foot = {
x = 0,
y = 0
}
},
non_standard_shape = {
convex_partition = {},
original_poly = {}
},
torso = {
back = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
head = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
legs = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
primary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_hand = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
secondary_shoulder = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
shoulder = {
pos = {
x = 0,
y = 0
},
rotation = 0
},
strafe_facing_offset = 0
}
},
usage_as_button = {
bbox_expander = {
x = 0,
y = 0
},
flip = {
horizontally = false,
vertically = false
}
}
} | agpl-3.0 |
djkamran021/BY | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-3.0 |
5620g/pp | libs/serpent.lua | 656 | 7877 | local n, v = "serpent", 0.28 -- (C) 2012-15 Paul Kulchenko; MIT License
local c, d = "Paul Kulchenko", "Lua serializer and pretty printer"
local snum = {[tostring(1/0)]='1/0 --[[math.huge]]',[tostring(-1/0)]='-1/0 --[[-math.huge]]',[tostring(0/0)]='0/0'}
local badtype = {thread = true, userdata = true, cdata = true}
local keyword, globals, G = {}, {}, (_G or _ENV)
for _,k in ipairs({'and', 'break', 'do', 'else', 'elseif', 'end', 'false',
'for', 'function', 'goto', 'if', 'in', 'local', 'nil', 'not', 'or', 'repeat',
'return', 'then', 'true', 'until', 'while'}) do keyword[k] = true end
for k,v in pairs(G) do globals[v] = k end -- build func to name mapping
for _,g in ipairs({'coroutine', 'debug', 'io', 'math', 'string', 'table', 'os'}) do
for k,v in pairs(G[g] or {}) do globals[v] = g..'.'..k end end
local function s(t, opts)
local name, indent, fatal, maxnum = opts.name, opts.indent, opts.fatal, opts.maxnum
local sparse, custom, huge = opts.sparse, opts.custom, not opts.nohuge
local space, maxl = (opts.compact and '' or ' '), (opts.maxlevel or math.huge)
local iname, comm = '_'..(name or ''), opts.comment and (tonumber(opts.comment) or math.huge)
local seen, sref, syms, symn = {}, {'local '..iname..'={}'}, {}, 0
local function gensym(val) return '_'..(tostring(tostring(val)):gsub("[^%w]",""):gsub("(%d%w+)",
-- tostring(val) is needed because __tostring may return a non-string value
function(s) if not syms[s] then symn = symn+1; syms[s] = symn end return tostring(syms[s]) end)) end
local function safestr(s) return type(s) == "number" and tostring(huge and snum[tostring(s)] or s)
or type(s) ~= "string" and tostring(s) -- escape NEWLINE/010 and EOF/026
or ("%q"):format(s):gsub("\010","n"):gsub("\026","\\026") end
local function comment(s,l) return comm and (l or 0) < comm and ' --[['..tostring(s)..']]' or '' end
local function globerr(s,l) return globals[s] and globals[s]..comment(s,l) or not fatal
and safestr(select(2, pcall(tostring, s))) or error("Can't serialize "..tostring(s)) end
local function safename(path, name) -- generates foo.bar, foo[3], or foo['b a r']
local n = name == nil and '' or name
local plain = type(n) == "string" and n:match("^[%l%u_][%w_]*$") and not keyword[n]
local safe = plain and n or '['..safestr(n)..']'
return (path or '')..(plain and path and '.' or '')..safe, safe end
local alphanumsort = type(opts.sortkeys) == 'function' and opts.sortkeys or function(k, o, n) -- k=keys, o=originaltable, n=padding
local maxn, to = tonumber(n) or 12, {number = 'a', string = 'b'}
local function padnum(d) return ("%0"..tostring(maxn).."d"):format(tonumber(d)) end
table.sort(k, function(a,b)
-- sort numeric keys first: k[key] is not nil for numerical keys
return (k[a] ~= nil and 0 or to[type(a)] or 'z')..(tostring(a):gsub("%d+",padnum))
< (k[b] ~= nil and 0 or to[type(b)] or 'z')..(tostring(b):gsub("%d+",padnum)) end) end
local function val2str(t, name, indent, insref, path, plainindex, level)
local ttype, level, mt = type(t), (level or 0), getmetatable(t)
local spath, sname = safename(path, name)
local tag = plainindex and
((type(name) == "number") and '' or name..space..'='..space) or
(name ~= nil and sname..space..'='..space or '')
if seen[t] then -- already seen this element
sref[#sref+1] = spath..space..'='..space..seen[t]
return tag..'nil'..comment('ref', level) end
if type(mt) == 'table' and (mt.__serialize or mt.__tostring) then -- knows how to serialize itself
seen[t] = insref or spath
if mt.__serialize then t = mt.__serialize(t) else t = tostring(t) end
ttype = type(t) end -- new value falls through to be serialized
if ttype == "table" then
if level >= maxl then return tag..'{}'..comment('max', level) end
seen[t] = insref or spath
if next(t) == nil then return tag..'{}'..comment(t, level) end -- table empty
local maxn, o, out = math.min(#t, maxnum or #t), {}, {}
for key = 1, maxn do o[key] = key end
if not maxnum or #o < maxnum then
local n = #o -- n = n + 1; o[n] is much faster than o[#o+1] on large tables
for key in pairs(t) do if o[key] ~= key then n = n + 1; o[n] = key end end end
if maxnum and #o > maxnum then o[maxnum+1] = nil end
if opts.sortkeys and #o > maxn then alphanumsort(o, t, opts.sortkeys) end
local sparse = sparse and #o > maxn -- disable sparsness if only numeric keys (shorter output)
for n, key in ipairs(o) do
local value, ktype, plainindex = t[key], type(key), n <= maxn and not sparse
if opts.valignore and opts.valignore[value] -- skip ignored values; do nothing
or opts.keyallow and not opts.keyallow[key]
or opts.valtypeignore and opts.valtypeignore[type(value)] -- skipping ignored value types
or sparse and value == nil then -- skipping nils; do nothing
elseif ktype == 'table' or ktype == 'function' or badtype[ktype] then
if not seen[key] and not globals[key] then
sref[#sref+1] = 'placeholder'
local sname = safename(iname, gensym(key)) -- iname is table for local variables
sref[#sref] = val2str(key,sname,indent,sname,iname,true) end
sref[#sref+1] = 'placeholder'
local path = seen[t]..'['..tostring(seen[key] or globals[key] or gensym(key))..']'
sref[#sref] = path..space..'='..space..tostring(seen[value] or val2str(value,nil,indent,path))
else
out[#out+1] = val2str(value,key,indent,insref,seen[t],plainindex,level+1)
end
end
local prefix = string.rep(indent or '', level)
local head = indent and '{\n'..prefix..indent or '{'
local body = table.concat(out, ','..(indent and '\n'..prefix..indent or space))
local tail = indent and "\n"..prefix..'}' or '}'
return (custom and custom(tag,head,body,tail) or tag..head..body..tail)..comment(t, level)
elseif badtype[ttype] then
seen[t] = insref or spath
return tag..globerr(t, level)
elseif ttype == 'function' then
seen[t] = insref or spath
local ok, res = pcall(string.dump, t)
local func = ok and ((opts.nocode and "function() --[[..skipped..]] end" or
"((loadstring or load)("..safestr(res)..",'@serialized'))")..comment(t, level))
return tag..(func or globerr(t, level))
else return tag..safestr(t) end -- handle all other types
end
local sepr = indent and "\n" or ";"..space
local body = val2str(t, name, indent) -- this call also populates sref
local tail = #sref>1 and table.concat(sref, sepr)..sepr or ''
local warn = opts.comment and #sref>1 and space.."--[[incomplete output with shared/self-references skipped]]" or ''
return not name and body..warn or "do local "..body..sepr..tail.."return "..name..sepr.."end"
end
local function deserialize(data, opts)
local env = (opts and opts.safe == false) and G
or setmetatable({}, {
__index = function(t,k) return t end,
__call = function(t,...) error("cannot call functions") end
})
local f, res = (loadstring or load)('return '..data, nil, nil, env)
if not f then f, res = (loadstring or load)(data, nil, nil, env) end
if not f then return f, res end
if setfenv then setfenv(f, env) end
return pcall(f)
end
local function merge(a, b) if b then for k,v in pairs(b) do a[k] = v end end; return a; end
return { _NAME = n, _COPYRIGHT = c, _DESCRIPTION = d, _VERSION = v, serialize = s,
load = deserialize,
dump = function(a, opts) return s(a, merge({name = '_', compact = true, sparse = true}, opts)) end,
line = function(a, opts) return s(a, merge({sortkeys = true, comment = true}, opts)) end,
block = function(a, opts) return s(a, merge({indent = ' ', sortkeys = true, comment = true}, opts)) end }
| gpl-2.0 |
maxton/xenia | tools/build/scripts/util.lua | 12 | 1450 | -- Prints a table and all of its contents.
function print_r(t)
local print_r_cache={}
local function sub_print_r(t, indent)
if (print_r_cache[tostring(t)]) then
print(indent.."*"..tostring(t))
else
print_r_cache[tostring(t)]=true
if (type(t)=="table") then
for pos,val in pairs(t) do
if (type(val)=="table") then
print(indent.."["..pos.."] => "..tostring(t).." {")
sub_print_r(val,indent..string.rep(" ",string.len(pos)+8))
print(indent..string.rep(" ",string.len(pos)+6).."}")
elseif (type(val)=="string") then
print(indent.."["..pos..'] => "'..val..'"')
else
print(indent.."["..pos.."] => "..tostring(val))
end
end
else
print(indent..tostring(t))
end
end
end
if (type(t)=="table") then
print(tostring(t).." {")
sub_print_r(t," ")
print("}")
else
sub_print_r(t," ")
end
print()
end
-- Merges two tables and returns the resulting table.
function merge_tables(t1, t2)
local result = {}
for k,v in pairs(t1 or {}) do result[k] = v end
for k,v in pairs(t2 or {}) do result[k] = v end
return result
end
-- Merges to arrays and returns the resulting array.
function merge_arrays(t1, t2)
local result = {}
for k,v in pairs(t1 or {}) do result[#result + 1] = v end
for k,v in pairs(t2 or {}) do result[#result + 1] = v end
return result
end
| bsd-3-clause |
oneoo/alilua-coevent-module | lua-libs/lua-cjson-2.1.0/tests/test.lua | 32 | 17977 | #!/usr/bin/env lua
-- Lua CJSON tests
--
-- Mark Pulford <mark@kyne.com.au>
--
-- Note: The output of this script is easier to read with "less -S"
local json = require "cjson"
local json_safe = require "cjson.safe"
local util = require "cjson.util"
local function gen_raw_octets()
local chars = {}
for i = 0, 255 do chars[i + 1] = string.char(i) end
return table.concat(chars)
end
-- Generate every UTF-16 codepoint, including supplementary codes
local function gen_utf16_escaped()
-- Create raw table escapes
local utf16_escaped = {}
local count = 0
local function append_escape(code)
local esc = ('\\u%04X'):format(code)
table.insert(utf16_escaped, esc)
end
table.insert(utf16_escaped, '"')
for i = 0, 0xD7FF do
append_escape(i)
end
-- Skip 0xD800 - 0xDFFF since they are used to encode supplementary
-- codepoints
for i = 0xE000, 0xFFFF do
append_escape(i)
end
-- Append surrogate pair for each supplementary codepoint
for high = 0xD800, 0xDBFF do
for low = 0xDC00, 0xDFFF do
append_escape(high)
append_escape(low)
end
end
table.insert(utf16_escaped, '"')
return table.concat(utf16_escaped)
end
function load_testdata()
local data = {}
-- Data for 8bit raw <-> escaped octets tests
data.octets_raw = gen_raw_octets()
data.octets_escaped = util.file_load("octets-escaped.dat")
-- Data for \uXXXX -> UTF-8 test
data.utf16_escaped = gen_utf16_escaped()
-- Load matching data for utf16_escaped
local utf8_loaded
utf8_loaded, data.utf8_raw = pcall(util.file_load, "utf8.dat")
if not utf8_loaded then
data.utf8_raw = "Failed to load utf8.dat - please run genutf8.pl"
end
data.table_cycle = {}
data.table_cycle[1] = data.table_cycle
local big = {}
for i = 1, 1100 do
big = { { 10, false, true, json.null }, "string", a = big }
end
data.deeply_nested_data = big
return data
end
function test_decode_cycle(filename)
local obj1 = json.decode(util.file_load(filename))
local obj2 = json.decode(json.encode(obj1))
return util.compare_values(obj1, obj2)
end
-- Set up data used in tests
local Inf = math.huge;
local NaN = math.huge * 0;
local testdata = load_testdata()
local cjson_tests = {
-- Test API variables
{ "Check module name, version",
function () return json._NAME, json._VERSION end, { },
true, { "cjson", "2.1.0" } },
-- Test decoding simple types
{ "Decode string",
json.decode, { '"test string"' }, true, { "test string" } },
{ "Decode numbers",
json.decode, { '[ 0.0, -5e3, -1, 0.3e-3, 1023.2, 0e10 ]' },
true, { { 0.0, -5000, -1, 0.0003, 1023.2, 0 } } },
{ "Decode null",
json.decode, { 'null' }, true, { json.null } },
{ "Decode true",
json.decode, { 'true' }, true, { true } },
{ "Decode false",
json.decode, { 'false' }, true, { false } },
{ "Decode object with numeric keys",
json.decode, { '{ "1": "one", "3": "three" }' },
true, { { ["1"] = "one", ["3"] = "three" } } },
{ "Decode object with string keys",
json.decode, { '{ "a": "a", "b": "b" }' },
true, { { a = "a", b = "b" } } },
{ "Decode array",
json.decode, { '[ "one", null, "three" ]' },
true, { { "one", json.null, "three" } } },
-- Test decoding errors
{ "Decode UTF-16BE [throw error]",
json.decode, { '\0"\0"' },
false, { "JSON parser does not support UTF-16 or UTF-32" } },
{ "Decode UTF-16LE [throw error]",
json.decode, { '"\0"\0' },
false, { "JSON parser does not support UTF-16 or UTF-32" } },
{ "Decode UTF-32BE [throw error]",
json.decode, { '\0\0\0"' },
false, { "JSON parser does not support UTF-16 or UTF-32" } },
{ "Decode UTF-32LE [throw error]",
json.decode, { '"\0\0\0' },
false, { "JSON parser does not support UTF-16 or UTF-32" } },
{ "Decode partial JSON [throw error]",
json.decode, { '{ "unexpected eof": ' },
false, { "Expected value but found T_END at character 21" } },
{ "Decode with extra comma [throw error]",
json.decode, { '{ "extra data": true }, false' },
false, { "Expected the end but found T_COMMA at character 23" } },
{ "Decode invalid escape code [throw error]",
json.decode, { [[ { "bad escape \q code" } ]] },
false, { "Expected object key string but found invalid escape code at character 16" } },
{ "Decode invalid unicode escape [throw error]",
json.decode, { [[ { "bad unicode \u0f6 escape" } ]] },
false, { "Expected object key string but found invalid unicode escape code at character 17" } },
{ "Decode invalid keyword [throw error]",
json.decode, { ' [ "bad barewood", test ] ' },
false, { "Expected value but found invalid token at character 20" } },
{ "Decode invalid number #1 [throw error]",
json.decode, { '[ -+12 ]' },
false, { "Expected value but found invalid number at character 3" } },
{ "Decode invalid number #2 [throw error]",
json.decode, { '-v' },
false, { "Expected value but found invalid number at character 1" } },
{ "Decode invalid number exponent [throw error]",
json.decode, { '[ 0.4eg10 ]' },
false, { "Expected comma or array end but found invalid token at character 6" } },
-- Test decoding nested arrays / objects
{ "Set decode_max_depth(5)",
json.decode_max_depth, { 5 }, true, { 5 } },
{ "Decode array at nested limit",
json.decode, { '[[[[[ "nested" ]]]]]' },
true, { {{{{{ "nested" }}}}} } },
{ "Decode array over nested limit [throw error]",
json.decode, { '[[[[[[ "nested" ]]]]]]' },
false, { "Found too many nested data structures (6) at character 6" } },
{ "Decode object at nested limit",
json.decode, { '{"a":{"b":{"c":{"d":{"e":"nested"}}}}}' },
true, { {a={b={c={d={e="nested"}}}}} } },
{ "Decode object over nested limit [throw error]",
json.decode, { '{"a":{"b":{"c":{"d":{"e":{"f":"nested"}}}}}}' },
false, { "Found too many nested data structures (6) at character 26" } },
{ "Set decode_max_depth(1000)",
json.decode_max_depth, { 1000 }, true, { 1000 } },
{ "Decode deeply nested array [throw error]",
json.decode, { string.rep("[", 1100) .. '1100' .. string.rep("]", 1100)},
false, { "Found too many nested data structures (1001) at character 1001" } },
-- Test encoding nested tables
{ "Set encode_max_depth(5)",
json.encode_max_depth, { 5 }, true, { 5 } },
{ "Encode nested table as array at nested limit",
json.encode, { {{{{{"nested"}}}}} }, true, { '[[[[["nested"]]]]]' } },
{ "Encode nested table as array after nested limit [throw error]",
json.encode, { { {{{{{"nested"}}}}} } },
false, { "Cannot serialise, excessive nesting (6)" } },
{ "Encode nested table as object at nested limit",
json.encode, { {a={b={c={d={e="nested"}}}}} },
true, { '{"a":{"b":{"c":{"d":{"e":"nested"}}}}}' } },
{ "Encode nested table as object over nested limit [throw error]",
json.encode, { {a={b={c={d={e={f="nested"}}}}}} },
false, { "Cannot serialise, excessive nesting (6)" } },
{ "Encode table with cycle [throw error]",
json.encode, { testdata.table_cycle },
false, { "Cannot serialise, excessive nesting (6)" } },
{ "Set encode_max_depth(1000)",
json.encode_max_depth, { 1000 }, true, { 1000 } },
{ "Encode deeply nested data [throw error]",
json.encode, { testdata.deeply_nested_data },
false, { "Cannot serialise, excessive nesting (1001)" } },
-- Test encoding simple types
{ "Encode null",
json.encode, { json.null }, true, { 'null' } },
{ "Encode true",
json.encode, { true }, true, { 'true' } },
{ "Encode false",
json.encode, { false }, true, { 'false' } },
{ "Encode empty object",
json.encode, { { } }, true, { '{}' } },
{ "Encode integer",
json.encode, { 10 }, true, { '10' } },
{ "Encode string",
json.encode, { "hello" }, true, { '"hello"' } },
{ "Encode Lua function [throw error]",
json.encode, { function () end },
false, { "Cannot serialise function: type not supported" } },
-- Test decoding invalid numbers
{ "Set decode_invalid_numbers(true)",
json.decode_invalid_numbers, { true }, true, { true } },
{ "Decode hexadecimal",
json.decode, { '0x6.ffp1' }, true, { 13.9921875 } },
{ "Decode numbers with leading zero",
json.decode, { '[ 0123, 00.33 ]' }, true, { { 123, 0.33 } } },
{ "Decode +-Inf",
json.decode, { '[ +Inf, Inf, -Inf ]' }, true, { { Inf, Inf, -Inf } } },
{ "Decode +-Infinity",
json.decode, { '[ +Infinity, Infinity, -Infinity ]' },
true, { { Inf, Inf, -Inf } } },
{ "Decode +-NaN",
json.decode, { '[ +NaN, NaN, -NaN ]' }, true, { { NaN, NaN, NaN } } },
{ "Decode Infrared (not infinity) [throw error]",
json.decode, { 'Infrared' },
false, { "Expected the end but found invalid token at character 4" } },
{ "Decode Noodle (not NaN) [throw error]",
json.decode, { 'Noodle' },
false, { "Expected value but found invalid token at character 1" } },
{ "Set decode_invalid_numbers(false)",
json.decode_invalid_numbers, { false }, true, { false } },
{ "Decode hexadecimal [throw error]",
json.decode, { '0x6' },
false, { "Expected value but found invalid number at character 1" } },
{ "Decode numbers with leading zero [throw error]",
json.decode, { '[ 0123, 00.33 ]' },
false, { "Expected value but found invalid number at character 3" } },
{ "Decode +-Inf [throw error]",
json.decode, { '[ +Inf, Inf, -Inf ]' },
false, { "Expected value but found invalid token at character 3" } },
{ "Decode +-Infinity [throw error]",
json.decode, { '[ +Infinity, Infinity, -Infinity ]' },
false, { "Expected value but found invalid token at character 3" } },
{ "Decode +-NaN [throw error]",
json.decode, { '[ +NaN, NaN, -NaN ]' },
false, { "Expected value but found invalid token at character 3" } },
{ 'Set decode_invalid_numbers("on")',
json.decode_invalid_numbers, { "on" }, true, { true } },
-- Test encoding invalid numbers
{ "Set encode_invalid_numbers(false)",
json.encode_invalid_numbers, { false }, true, { false } },
{ "Encode NaN [throw error]",
json.encode, { NaN },
false, { "Cannot serialise number: must not be NaN or Inf" } },
{ "Encode Infinity [throw error]",
json.encode, { Inf },
false, { "Cannot serialise number: must not be NaN or Inf" } },
{ "Set encode_invalid_numbers(\"null\")",
json.encode_invalid_numbers, { "null" }, true, { "null" } },
{ "Encode NaN as null",
json.encode, { NaN }, true, { "null" } },
{ "Encode Infinity as null",
json.encode, { Inf }, true, { "null" } },
{ "Set encode_invalid_numbers(true)",
json.encode_invalid_numbers, { true }, true, { true } },
{ "Encode NaN",
json.encode, { NaN }, true, { "nan" } },
{ "Encode Infinity",
json.encode, { Inf }, true, { "inf" } },
{ 'Set encode_invalid_numbers("off")',
json.encode_invalid_numbers, { "off" }, true, { false } },
-- Test encoding tables
{ "Set encode_sparse_array(true, 2, 3)",
json.encode_sparse_array, { true, 2, 3 }, true, { true, 2, 3 } },
{ "Encode sparse table as array #1",
json.encode, { { [3] = "sparse test" } },
true, { '[null,null,"sparse test"]' } },
{ "Encode sparse table as array #2",
json.encode, { { [1] = "one", [4] = "sparse test" } },
true, { '["one",null,null,"sparse test"]' } },
{ "Encode sparse array as object",
json.encode, { { [1] = "one", [5] = "sparse test" } },
true, { '{"1":"one","5":"sparse test"}' } },
{ "Encode table with numeric string key as object",
json.encode, { { ["2"] = "numeric string key test" } },
true, { '{"2":"numeric string key test"}' } },
{ "Set encode_sparse_array(false)",
json.encode_sparse_array, { false }, true, { false, 2, 3 } },
{ "Encode table with incompatible key [throw error]",
json.encode, { { [false] = "wrong" } },
false, { "Cannot serialise boolean: table key must be a number or string" } },
-- Test escaping
{ "Encode all octets (8-bit clean)",
json.encode, { testdata.octets_raw }, true, { testdata.octets_escaped } },
{ "Decode all escaped octets",
json.decode, { testdata.octets_escaped }, true, { testdata.octets_raw } },
{ "Decode single UTF-16 escape",
json.decode, { [["\uF800"]] }, true, { "\239\160\128" } },
{ "Decode all UTF-16 escapes (including surrogate combinations)",
json.decode, { testdata.utf16_escaped }, true, { testdata.utf8_raw } },
{ "Decode swapped surrogate pair [throw error]",
json.decode, { [["\uDC00\uD800"]] },
false, { "Expected value but found invalid unicode escape code at character 2" } },
{ "Decode duplicate high surrogate [throw error]",
json.decode, { [["\uDB00\uDB00"]] },
false, { "Expected value but found invalid unicode escape code at character 2" } },
{ "Decode duplicate low surrogate [throw error]",
json.decode, { [["\uDB00\uDB00"]] },
false, { "Expected value but found invalid unicode escape code at character 2" } },
{ "Decode missing low surrogate [throw error]",
json.decode, { [["\uDB00"]] },
false, { "Expected value but found invalid unicode escape code at character 2" } },
{ "Decode invalid low surrogate [throw error]",
json.decode, { [["\uDB00\uD"]] },
false, { "Expected value but found invalid unicode escape code at character 2" } },
-- Test locale support
--
-- The standard Lua interpreter is ANSI C online doesn't support locales
-- by default. Force a known problematic locale to test strtod()/sprintf().
{ "Set locale to cs_CZ (comma separator)", function ()
os.setlocale("cs_CZ")
json.new()
end },
{ "Encode number under comma locale",
json.encode, { 1.5 }, true, { '1.5' } },
{ "Decode number in array under comma locale",
json.decode, { '[ 10, "test" ]' }, true, { { 10, "test" } } },
{ "Revert locale to POSIX", function ()
os.setlocale("C")
json.new()
end },
-- Test encode_keep_buffer() and enable_number_precision()
{ "Set encode_keep_buffer(false)",
json.encode_keep_buffer, { false }, true, { false } },
{ "Set encode_number_precision(3)",
json.encode_number_precision, { 3 }, true, { 3 } },
{ "Encode number with precision 3",
json.encode, { 1/3 }, true, { "0.333" } },
{ "Set encode_number_precision(14)",
json.encode_number_precision, { 14 }, true, { 14 } },
{ "Set encode_keep_buffer(true)",
json.encode_keep_buffer, { true }, true, { true } },
-- Test config API errors
-- Function is listed as '?' due to pcall
{ "Set encode_number_precision(0) [throw error]",
json.encode_number_precision, { 0 },
false, { "bad argument #1 to '?' (expected integer between 1 and 14)" } },
{ "Set encode_number_precision(\"five\") [throw error]",
json.encode_number_precision, { "five" },
false, { "bad argument #1 to '?' (number expected, got string)" } },
{ "Set encode_keep_buffer(nil, true) [throw error]",
json.encode_keep_buffer, { nil, true },
false, { "bad argument #2 to '?' (found too many arguments)" } },
{ "Set encode_max_depth(\"wrong\") [throw error]",
json.encode_max_depth, { "wrong" },
false, { "bad argument #1 to '?' (number expected, got string)" } },
{ "Set decode_max_depth(0) [throw error]",
json.decode_max_depth, { "0" },
false, { "bad argument #1 to '?' (expected integer between 1 and 2147483647)" } },
{ "Set encode_invalid_numbers(-2) [throw error]",
json.encode_invalid_numbers, { -2 },
false, { "bad argument #1 to '?' (invalid option '-2')" } },
{ "Set decode_invalid_numbers(true, false) [throw error]",
json.decode_invalid_numbers, { true, false },
false, { "bad argument #2 to '?' (found too many arguments)" } },
{ "Set encode_sparse_array(\"not quite on\") [throw error]",
json.encode_sparse_array, { "not quite on" },
false, { "bad argument #1 to '?' (invalid option 'not quite on')" } },
{ "Reset Lua CJSON configuration", function () json = json.new() end },
-- Wrap in a function to ensure the table returned by json.new() is used
{ "Check encode_sparse_array()",
function (...) return json.encode_sparse_array(...) end, { },
true, { false, 2, 10 } },
{ "Encode (safe) simple value",
json_safe.encode, { true },
true, { "true" } },
{ "Encode (safe) argument validation [throw error]",
json_safe.encode, { "arg1", "arg2" },
false, { "bad argument #1 to '?' (expected 1 argument)" } },
{ "Decode (safe) error generation",
json_safe.decode, { "Oops" },
true, { nil, "Expected value but found invalid token at character 1" } },
{ "Decode (safe) error generation after new()",
function(...) return json_safe.new().decode(...) end, { "Oops" },
true, { nil, "Expected value but found invalid token at character 1" } },
}
print(("==> Testing Lua CJSON version %s\n"):format(json._VERSION))
util.run_test_group(cjson_tests)
for _, filename in ipairs(arg) do
util.run_test("Decode cycle " .. filename, test_decode_cycle, { filename },
true, { true })
end
local pass, total = util.run_test_summary()
if pass == total then
print("==> Summary: all tests succeeded")
else
print(("==> Summary: %d/%d tests failed"):format(total - pass, total))
os.exit(1)
end
-- vi:ai et sw=4 ts=4:
| mit |
Sponk/NeoEditor | SDK/LuaApi/OEntity.lua | 1 | 7415 | --- The OEntity class
-- An 'OEntity' instance is an entity object in a scene which can be
-- manipulated. The 'OEntity' class is mostly used to manage meshes in your 3D scene.
--
-- See also: <a href="Object3d.lua.html">Widget</a>
dofile("class.lua")
dofile("Object3d.lua")
--- OEntity(object3d)
-- Create a new OEntity object with the given Object3d
-- as the base. Will return 'nil' if the given object is not of type 'Entity'.
--
-- If you give a path as the base object it will load the new mesh and add it to the current scene.
OEntity = class(Object3d,
function(object, object3d)
if type(object3d) == "string" then
local nativeObject = loadMesh(object3d)
if nativeObject == nil then
print("Error: Could not load '" .. object3d .. "'")
object = nil
return
end
object3d = OEntity(Object3d(nativeObject))
end
if object3d.type ~= "Entity" then
object = nil
print("Error: Base object is not of type 'Entity'!")
return
end
object.type = "Entity"
object.nativeObject = object3d.nativeObject
object.position = getPosition(object.nativeObject)
object.rotation = getRotation(object.nativeObject)
object.scale = getScale(object.nativeObject)
object.path = getMeshFilename(object.nativeObject)
end
)
--- Returns the path to the loaded mesh file.
-- @return The path as a string.
function OEntity:getPath()
return self.path
end
--- Returns the ID of the currently running animation.
-- @return The ID as a number
function OEntity:getCurrentAnimation()
return getCurrentAnimation(self.nativeObject)
end
--- Changes the current animation and starts the new one.
-- @param id The ID of the new animation.
function OEntity:changeAnimation(id)
changeAnimation(self.nativeObject, id)
end
--- Checks if the currently running animation has finished.
-- @return A boolean
function OEntity:isAnimationOver()
return isAnimationOver(self.nativeObject)
end
--- Returns the current animation speed.
-- @return The animation speed as a number.
function OEntity:getAnimationSpeed()
return getAnimationSpeed(self.nativeObject)
end
--- Changes the animation speed.
-- @param speed The new animation speed.
function OEntity:setAnimationSpeed(speed)
setAnimationSpeed(self.nativeObject, speed)
end
--- Returns the current frame of the animation that is being
-- displayed.
-- @return The current frame number
function OEntity:getCurrentFrame()
return getCurrentFrame(self.nativeObject)
end
--- Changes the current frame that is being displayed.
-- @param frame The index of the new frame.
function OEntity:setCurrentFrame(frame)
return setCurrentFrame(self.nativeObject, frame)
end
--- Enables/Disables the shadow for this object.
-- @param enabled A boolean value
function OEntity:enableShadow(enabled)
enableShadow(self.nativeObject, enabled)
end
--- Checks if the entity has a shadow.
-- @return A boolean value
function OEntity:hasShadow()
return isCastingShadow(self.nativeObject)
end
--- Returns the linear damping value
-- @return The linear damping as a number
function OEntity:getLinearDamping()
return getLinearDamping(self.nativeObject)
end
--- Changes the linear damping value
-- @param damping The value as a number
function OEntity:setLinearDamping(damping)
setLinearDamping(self.nativeObject, damping)
end
--- Returns the angular damping
-- @return The angular damping as a number.
function OEntity:getAngularDamping()
return getAngularDamping(self.nativeObject)
end
--- Changes the angular damping
-- @param damping the value as a number
function OEntity:setAngularDamping(damping)
setAngularDamping(self.nativeObject, damping)
end
--- Returns the angular factor
-- @return The angular factor as a number.
function OEntity:getAngularFactor()
return getAngularFactor(self.nativeObject)
end
--- Changes the angular factor
-- @param factor The new factor as a number
function OEntity:setAngularFactor(factor)
setAngularFactor(self.nativeObject, factor)
end
--- Returns the linear factor
-- @return The linear factor as a vec3
function OEntity:getLinearFactor()
return getLinearFactor(self.nativeObject)
end
--- Changes the linear factor
-- @param factor The linear factor as a vec3
function OEntity:setLinearFactor(factor)
setLinearFactor(self.nativeObject, factor)
end
--- Returns the mass of the entity
-- @return The mass as a number
function OEntity:getMass()
return getMass(self.nativeObject)
end
--- Changes the mass of the entity
-- @param mass The new mass as a number
function OEntity:setMass(mass)
setMass(self.nativeObject, mass)
end
--- Changes the friction of the entity
-- @param fric The friction as a number.
function OEntity:setFriction(fric)
setFriction(self.nativeObject, fric)
end
--- Returns the friction value
-- @return The friction value as a number.
function OEntity:getFriction()
return getFriction(self.nativeObject)
end
--- Changes the restitution value
-- @param rest The new restitution value as a number
function OEntity:setRestitution(rest)
setRestitution(self.nativeObject, rest)
end
--- Returns the restitution value
-- @return The restitution value as a number.
function OEntity:getRestitution()
return getRestitution(self.nativeObject)
end
--- Clears the central force
function OEntity:clearForces()
clearForces(self.nativeObject)
end
--- Applies a new central force to the given object.
--
-- The new force will be added to the currently existing central force of the
-- object. The mode parameter is optional and allows you to apply forces relative to the objects
-- current rotation.
--
-- @param force A vec3 containing the force to apply.
-- @param mode A string containing "local". Can be left out.
function OEntity:addCentralForce(force, mode)
addCentralForce(self.nativeObject, force, mode)
end
--- Applies a new torque to the given object.
--
-- The new torque will be added to the currently existing torque of the
-- object. The mode parameter is optional and allows you to apply a torque relative to the objects
-- current rotation.
--
-- @param torque A vec3 containing the torque to apply.
-- @param mode A string containing "local". Can be left out.
function OEntity:addTorque(torque, mode)
addTorque(self.nativeObject, torque, mode)
end
--- Returns the central force
-- @return The central force as a vec3
function OEntity:getCentralForce()
return getCentralForce(self.nativeObject)
end
--- Returns the current torque
-- @return The torque as a vec3
function OEntity:getTorque()
return getTorque(self.nativeObject)
end
--- Checks if the object is colliding with anything.
-- @return A boolean value
function OEntity:isColliding()
return isCollisionTest(self.nativeObject)
end
--- Checks if the object is colliding with the given object.
-- @param object An OEntity object
-- @return A boolean
function OEntity:isCollidingWith(object)
return isCollisionBetween(self.nativeObject, object.nativeObject)
end
--- Returns the number of collisions the object currently has.
-- @return The number of collisions as a number.
function OEntity:getNumCollisions()
return getNumCollisions(self.nativeObject)
end
--- Enables physics for the entity
-- @param value A boolean value
function OEntity:enablePhysics(value)
enablePhysics(self.nativeObject, value)
end
| gpl-2.0 |
devlaith/DEVLAITH | plugins/shrfa.lua | 2 | 7073 | local function run(msg, matches)
if #matches < 2 then
return "بعد هذا الأمر، من خلال تحديد كلمة المسافة أو العبارة التي تريد إدخال الكتابة الجميلة"
end
if string.len(matches[2]) > 44 then
return "الحد الأقصى المسموح به 40 حرفاالأحرف الإنجليزية والأرقام"
end
local font_base = "ء,ئ,ا,ب,ت,ث,ج,ح,خ,د,ذ,ر,ز,س,ش,ص,ض,ط,ظ,ع,غ,ق,ف,ك,ل,م,ن,ه,و,ي,0,9,8,7,6,5,4,3,2,1,.,_"
local font_hash = "ي,و,ه,ن,م,ل,ك,ف,ق,غ,ع,ظ,ط,ض,ص,ش,س,ز,ر,ذ,د,خ,ح,ج,ث,ت,ب,ا,ئ,ء,0,1,2,3,4,5,6,7,8,9,.,_"
local fonts = {
"ء,ئ,ٳ,ٻً,تہ,ثہ,جہ,حہ,خہ,دٍ,ذً,ر,ڒٍ,سہ,شہ,صً,ض,طہ,ظً,عـ,غہ,قـً,فُہ,كُہ,لہ,مـْ,نٍ,ه,ﯝ,يہ,0ً,1,2ً,3ً,4ً,5ً,6ً,7َ,8ً,9ً,.,_",
"ء,ئ,آ̲,ب̲,ت̲,ث̲,ج̲,ح̲,خ̲,د̲,ذ̲,ر̲,ز̲,س̲,ش̲,ص̲,ض,ط̲,ظً̲,ع̲,غ̲,ق̲,ف̲,ك̲,ل̲,م̲,ن̲,ہ̲,ۆ̲,ي̲,0̲,1̲,2̲,3̲,4̲,5̲,6̲,7̲,8̲,9̲,.,_",
"ء,ئ,آ̯͡,ب̯͡,ت̯͡,ث̯͡,ج̯͡,ح̯͡,خ̯͡,د̯͡,ذ̯͡,ر̯͡,ز̯͡,س̯͡,ش̯͡,ص̯͡,ض,ط̯͡,ظ̯͡,ع̯͡,غ̯͡,ق̯͡,ف̯͡,ك̯͡,ل̯͡,م̯͡,ن̯͡,ہ̯͡,ۆ̯͡,ي̯͡,0̯͡,1̯͡,2̯͡,3̯͡,4̯͡,5̯͡,6̯͡,7̯͡,8̯͡,9̯͡,.,_",
"ء,ئ,آ͠,ب͠,ت͠,ث͠,ج͠,ح͠,خ͠,د͠,ذ͠,ر,ز͠,س͠,ش͠,ص͠,ض,ط͠,ظ͠,ع͠,غ͠,ق͠,ف͠,گ͠,ل͠,م͠,ن͠,ه͠,و͠,ي͠,0͠,1͠,2͠,3͠,4͠,5͠,6͠,7͠,8͠,9͠,.,_",
"ء,ئ,آ,ب,ت,ث,جٍ,حٍ,خـ,دِ,ڌ,رٍ,ز,س,شُ,ص,ض,طُ,ظً,عٍ,غ,ق,فَ,گ,لُ,م,ن,ہ,ۆ,يَ,₀,₁,₂,₃,₄,₅,₆,₇,₈,₉,.,_", "ء,ئ,إآ,̜̌ب,تـ,,ثـ,جٍ,و,خ,ﮃ,ذ,رٍ,زً,سًٌُُ,شُ,ص,ض,طُ,ظً,۶,غ,ق,فَ,گ,لُ,مـ,ن,ه̷̸̐,ۈ,يَ,0,⇂,Շ,Ɛ,h,ʢ,9,L,8,6,.,_",
"ء,ئ,آ,ب,ت,ث,جٍ,حٍ,خـ,دِ,ڌ,رٍ,ز,س,شُ,ص,ض,طُ,ظً,عٍ,غ,ق,فَ,گ,لُ,م,ن,ہ,ۆ,يَ,₀,₁,₂,₃,₄,₅,₆,₇,₈,₉,.,_",
"ء,ئ,ٵ̷ ,ب̷,ت̷,ث̷,ج̷,ح̷,خ̷,د̷ِ,ذ̷,ر̷,ز̷,س̷,ش̷ُ,ص̷,ض,ط̷ُ,ظ̷ً,ع̷ٍ,غ̷,ق̷,ف̷َ,گ̷,ل̷,م̷,ن̷,ہ̷,ۆ̷,ي̷,0̷,1̷,2̷,3̷,4̷,5̷,6̷,7̷,8̷,9̷,.,_",
"ء,ئ,آإ,بـ♥̨̥̬̩,تـ♥̨̥̬̩,ثـ♥̨̥̬̩,جـ♥̨̥̬̩,حـ♥̨̥̬̩,خ,د,ذ,ر,ز,س,ش,ص,ض,ط♥̨̥̬̩,ظ♥̨̥̬̩,ع,غ♥̨̥̬̩,قـ♥̨̥̬̩,ف,گ♥̨̥̬̩,ل,مـ♥̨̥̬̩,ن,هـ♥̨̥̬̩,و,ي,⁰,¹,²,³,⁴,⁵,⁶,⁷,⁸,⁹,.,_",
"ء,ئ,آ,بُ,تْ,ثُ,ج,ح,ځ,ڊ,ڏ,ر,ڒٍ,ڛ,شُ,صً,ض,طُ,ظً,عٌ,غٍ,قٌ,فُ,ڪ,لُ,مْ,نْ,ﮩ,وُ,يُ,0,1,2,3,4,5,6,7,8,9,.,_",
"ء,ئ,آ,بَ,ت,ث,جٍ,حٍ,خـ,دِ,ذَ,رٍ,زْ,س,شُ,ص,ض,طُ,ظً,عٍ,غ,قٌ,فُ,ڪ,لُِ,م,ن,هـ,وُ,ي,0̲̣̣̥,1̣̣̝̇̇,2̲̣̣̣̥,3̍̍̍̊,4̩̥,5̲̣̥,6̥̥̲̣̥,7̣̣̣̝̇̇̇,8̣̝̇,9̲̣̣̥,.,_",
"ء,ئ,آ,ب,ت,ث,جٍ,حٍ,خـ,دِ,ڌ,رٍ,ز,س,شُ,ص,ض,طُ,ظً,عٍ,غ,ق,فَ,گ,لُ,م,ن,ہ,ۆ,يَ,₀,₁,₂,₃,₄,₅,₆,₇,₈,₉,.,_",
"ء,ئ,ٵ̷ ,ب̷,ت̷,ث̷,ج̷,ح̷,خ̷,د̷ِ,ذ̷,ر̷,ز̷,س̷,ش̷ُ,ص̷,ض,ط̷ُ,ظ̷ً,ع̷ٍ,غ̷,ق̷,ف̷َ,گ̷,ل̷,م̷,ن̷,ہ̷,ۆ̷,ي̷,0̷,1̷,2̷,3̷,4̷,5̷,6̷,7̷,8̷,9̷,.,_",
"ء,ئ,آ͠,ب͠,ت͠,ث͠,ج͠,ح͠,خ͠,د͠,ذ͠,ر,ز͠,س͠,ش͠,ص͠,ض,ط͠,ظ͠,ع͠,غ͠,ق͠,ف͠,گ͠,ل͠,م͠,ن͠,ه͠,و͠,ي͠,0͠,1͠,2͠,3͠,4͠,5͠,6͠,7͠,8͠,9͠,.,_",
"ء,ئ,آ̯͡,ب̯͡,ت̯͡,ث̯͡,ج̯͡,ح̯͡,خ̯͡,د̯͡,ذ̯͡,ر̯͡,ز̯͡,س̯͡,ش̯͡,ص̯͡,ض,ط̯͡,ظ̯͡,ع̯͡,غ̯͡,ق̯͡,ف̯͡,ك̯͡,ل̯͡,م̯͡,ن̯͡,ہ̯͡,ۆ̯͡,ي̯͡,0̯͡,1̯͡,2̯͡,3̯͡,4̯͡,5̯͡,6̯͡,7̯͡,8̯͡,9̯͡,.,_",
"ء,ئ,آإ,بـ♥̨̥̬̩,تـ♥̨̥̬̩,ثـ♥̨̥̬̩,جـ♥̨̥̬̩,حـ♥̨̥̬̩,خ,د,ذ,ر,ز,س,ش,ص,ض,ط♥̨̥̬̩,ظ♥̨̥̬̩,ع,غ♥̨̥̬̩,قـ♥̨̥̬̩,ف,گ♥̨̥̬̩,ل,مـ♥̨̥̬̩,ن,هـ♥̨̥̬̩,و,ي,⁰,¹,²,³,⁴,⁵,⁶,⁷,⁸,⁹,̴.̴,̴_̴",
}
-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
local result = {}
i=0
for k=1,#fonts do
i=i+1
local tar_font = fonts[i]:split(",")
local text = matches[2]
local text = text:gsub("ء",tar_font[1])
local text = text:gsub("ئ",tar_font[2])
local text = text:gsub("ا",tar_font[3])
local text = text:gsub("ب",tar_font[4])
local text = text:gsub("ت",tar_font[5])
local text = text:gsub("ث",tar_font[6])
local text = text:gsub("ج",tar_font[7])
local text = text:gsub("ح",tar_font[8])
local text = text:gsub("خ",tar_font[9])
local text = text:gsub("د",tar_font[10])
local text = text:gsub("ذ",tar_font[11])
local text = text:gsub("ر",tar_font[12])
local text = text:gsub("ز",tar_font[13])
local text = text:gsub("س",tar_font[14])
local text = text:gsub("ش",tar_font[15])
local text = text:gsub("ص",tar_font[16])
local text = text:gsub("ض",tar_font[17])
local text = text:gsub("ط",tar_font[18])
local text = text:gsub("ظ",tar_font[19])
local text = text:gsub("ع",tar_font[20])
local text = text:gsub("غ",tar_font[21])
local text = text:gsub("ق",tar_font[22])
local text = text:gsub("ف",tar_font[23])
local text = text:gsub("ك",tar_font[24])
local text = text:gsub("ل",tar_font[25])
local text = text:gsub("م",tar_font[26])
local text = text:gsub("ن",tar_font[27])
local text = text:gsub("ه",tar_font[28])
local text = text:gsub("و",tar_font[29])
local text = text:gsub("ي",tar_font[30])
local text = text:gsub("0",tar_font[31])
local text = text:gsub("9",tar_font[32])
local text = text:gsub("8",tar_font[33])
local text = text:gsub("7",tar_font[34])
local text = text:gsub("6",tar_font[35])
local text = text:gsub("5",tar_font[36])
local text = text:gsub("4",tar_font[37])
local text = text:gsub("3",tar_font[38])
local text = text:gsub("2",tar_font[39])
local text = text:gsub("1",tar_font[40])
table.insert(result, text)
end
local result_text = "زخرفة 💠 : "..matches[2].."\nتصميم 💠 "..tostring(#fonts).." خط :\n______________________________\n"
a=0
for v=1,#result do
a=a+1
result_text = result_text..a.."- "..result[a].."\n\n"
end
return result_text.."______________________________\n💠 #DEVLAITH @II07II"
end
return {
description = "Fantasy Writer",
usagehtm = '<tr><td align="center">decoration متن</td><td align="right">مع هذا البرنامج المساعد يمكن النصوص الخاصة بك مع مجموعة متنوعة من الخطوط والتصميم الجميل. أحرف الحد الأقصى المسموح به هو 20 ويمكن فقط استخدام الأحرف الإنجليزية والأرقام</td></tr>',
usage = {"decoration [text] : زخرفه النص",},
patterns = {
"^(زخرفه) (.*)",
"^(زخرفه)$",
},
run = run
}
| gpl-2.0 |
hhsaez/crimild | examples/ParticleShowcase/assets/prefabs/sprinklers.lua | 1 | 1661 | function sprinklers( x, y, z )
local MAX_PARTICLES = 500
return {
type = 'crimild::Group',
components = {
{
type = 'crimild::ParticleSystemComponent',
particles = {
type = 'crimild::ParticleData',
maxParticles = MAX_PARTICLES,
computeInWorldSpace = true,
},
emitRate = 0.25 * MAX_PARTICLES,
generators = {
{
type = 'crimild::BoxPositionParticleGenerator',
origin = { 0.0, 0.0, 0.0 },
size = { 0.5, 0.5, 0.5 },
},
{
type = 'crimild::RandomVector3fParticleGenerator',
attrib = 'velocity',
minValue = { -3.0, 5.0, -3.0 },
maxValue = { 3.0, 8.0, 3.0 },
},
{
type = 'crimild::DefaultVector3fParticleGenerator',
attrib = 'acceleration',
value = { 0.0, 0.0, 0.0 },
},
{
type = 'crimild::ColorParticleGenerator',
minStartColor = { 0.0, 0.0, 0.7, 1.0 },
maxStartColor = { 1.0, 1.0, 1.0, 1.0 },
minEndColor = { 0.0, 0.0, 0.25, 0.0 },
maxEndColor = { 0.0, 0.0, 0.7, 0.0 },
},
{
type = 'crimild::RandomReal32ParticleGenerator',
attrib = 'uniformScale',
minValue = 10.0,
maxValue = 20.0,
},
{
type = 'crimild::TimeParticleGenerator',
minTime = 1.0,
maxTime = 1.5,
},
},
updaters = {
{
type = 'crimild::EulerParticleUpdater',
globalAcceleration = { 0.0, -10.0, 0.0 },
},
{
type = 'crimild::TimeParticleUpdater',
},
},
renderers = {
{
type = 'crimild::PointSpriteParticleRenderer',
},
},
},
},
transformation = {
translate = { x, y, z },
},
}
end
| bsd-3-clause |
soheil22222222/ub | plugins/antiSpam.lua | 4 | 5374 | --An empty table for solving multiple kicking problem(thanks to @MehdiHS )
kicktable = {}
do
local TIME_CHECK = 2 -- seconds
-- 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
-- Save stats on Redis
if msg.to.type == 'channel' then
-- User is on channel
local hash = 'channel:'..msg.to.id..':users'
redis:sadd(hash, msg.from.id)
end
if msg.to.type == 'user' then
-- User is on chat
local hash = 'PM:'..msg.from.id
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 on 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
local chat = msg.to.id
local whitelist = "whitelist"
local is_whitelisted = redis:sismember(whitelist, user)
-- Ignore mods,owner and admins
if is_momod(msg) then
return msg
end
if is_whitelisted == true then
return msg
end
local receiver = get_receiver(msg)
if msg.to.type == 'user' then
local max_msg = 7 * 1
print(msgs)
if msgs >= max_msg then
print("Pass2")
send_large_msg("user#id"..msg.from.id, "User ["..msg.from.id.."] blocked for spam.")
savelog(msg.from.id.." PM", "User ["..msg.from.id.."] blocked for spam.")
block_user("user#id"..msg.from.id,ok_cb,false)--Block user if spammed in private
end
end
if kicktable[user] == true then
return
end
delete_msg(msg.id, ok_cb, false)
kick_user(user, chat)
local username = msg.from.username
local print_name = user_print_name(msg.from):gsub("", "")
local name_log = print_name:gsub("_", "")
if msg.to.type == 'chat' or msg.to.type == 'channel' then
if username then
savelog(msg.to.id, name_log.." @"..username.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "Spamming is not allowed here\n@"..username.."["..msg.from.id.."]\nKicking Spammer!")
else
savelog(msg.to.id, name_log.." ["..msg.from.id.."] kicked for #spam")
send_large_msg(receiver , "Spamming is not allowed here\nName:"..name_log.."["..msg.from.id.."]\nKicking Spammer!")
end
end
-- 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)
if msg.from.username ~= nil then
username = msg.from.username
else
username = "---"
end
local print_name = user_print_name(msg.from):gsub("", "")
local name = print_name:gsub("_", "")
--Send this to that chat
send_large_msg("chat#id"..msg.to.id, "> User [ "..name.." ]"..msg.from.id.." Banned for all @BlackPlus Groups/SuperGroups!(spamming)")
send_large_msg("channel#id"..msg.to.id, "> User [ "..name.." ]"..msg.from.id.." Banned for all @BlackPlus Groups/SuperGroups!(#Spamming)")
local GBan_log = 'GBan_log'
local GBan_log = data[tostring(GBan_log)]
for k,v in pairs(GBan_log) do
log_SuperGroup = v
gban_text = "> User [ "..name.." ] ( @"..username.." )"..msg.from.id.." Banned for all @BlackPlus Groups/SuperGroups! ( "..msg.to.print_name.." ) [ "..msg.to.id.." ] (#Spamming)"
--send it to log group/channel
send_large_msg(log_SuperGroup, gban_text)
end
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 |
5620g/pp | libs/lua-redis.lua | 580 | 35599 | local redis = {
_VERSION = 'redis-lua 2.0.4',
_DESCRIPTION = 'A Lua client library for the redis key value storage system.',
_COPYRIGHT = 'Copyright (C) 2009-2012 Daniele Alessandri',
}
-- The following line is used for backwards compatibility in order to keep the `Redis`
-- global module name. Using `Redis` is now deprecated so you should explicitly assign
-- the module to a local variable when requiring it: `local redis = require('redis')`.
Redis = redis
local unpack = _G.unpack or table.unpack
local network, request, response = {}, {}, {}
local defaults = {
host = '127.0.0.1',
port = 6379,
tcp_nodelay = true,
path = nil
}
local function merge_defaults(parameters)
if parameters == nil then
parameters = {}
end
for k, v in pairs(defaults) do
if parameters[k] == nil then
parameters[k] = defaults[k]
end
end
return parameters
end
local function parse_boolean(v)
if v == '1' or v == 'true' or v == 'TRUE' then
return true
elseif v == '0' or v == 'false' or v == 'FALSE' then
return false
else
return nil
end
end
local function toboolean(value) return value == 1 end
local function sort_request(client, command, key, params)
--[[ params = {
by = 'weight_*',
get = 'object_*',
limit = { 0, 10 },
sort = 'desc',
alpha = true,
} ]]
local query = { key }
if params then
if params.by then
table.insert(query, 'BY')
table.insert(query, params.by)
end
if type(params.limit) == 'table' then
-- TODO: check for lower and upper limits
table.insert(query, 'LIMIT')
table.insert(query, params.limit[1])
table.insert(query, params.limit[2])
end
if params.get then
if (type(params.get) == 'table') then
for _, getarg in pairs(params.get) do
table.insert(query, 'GET')
table.insert(query, getarg)
end
else
table.insert(query, 'GET')
table.insert(query, params.get)
end
end
if params.sort then
table.insert(query, params.sort)
end
if params.alpha == true then
table.insert(query, 'ALPHA')
end
if params.store then
table.insert(query, 'STORE')
table.insert(query, params.store)
end
end
request.multibulk(client, command, query)
end
local function zset_range_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_byscore_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.limit then
table.insert(opts, 'LIMIT')
table.insert(opts, options.limit.offset or options.limit[1])
table.insert(opts, options.limit.count or options.limit[2])
end
if options.withscores then
table.insert(opts, 'WITHSCORES')
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function zset_range_reply(reply, command, ...)
local args = {...}
local opts = args[4]
if opts and (opts.withscores or string.lower(tostring(opts)) == 'withscores') then
local new_reply = { }
for i = 1, #reply, 2 do
table.insert(new_reply, { reply[i], reply[i + 1] })
end
return new_reply
else
return reply
end
end
local function zset_store_request(client, command, ...)
local args, opts = {...}, { }
if #args >= 1 and type(args[#args]) == 'table' then
local options = table.remove(args, #args)
if options.weights and type(options.weights) == 'table' then
table.insert(opts, 'WEIGHTS')
for _, weight in ipairs(options.weights) do
table.insert(opts, weight)
end
end
if options.aggregate then
table.insert(opts, 'AGGREGATE')
table.insert(opts, options.aggregate)
end
end
for _, v in pairs(opts) do table.insert(args, v) end
request.multibulk(client, command, args)
end
local function mset_filter_args(client, command, ...)
local args, arguments = {...}, {}
if (#args == 1 and type(args[1]) == 'table') then
for k,v in pairs(args[1]) do
table.insert(arguments, k)
table.insert(arguments, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
local function hash_multi_request_builder(builder_callback)
return function(client, command, ...)
local args, arguments = {...}, { }
if #args == 2 then
table.insert(arguments, args[1])
for k, v in pairs(args[2]) do
builder_callback(arguments, k, v)
end
else
arguments = args
end
request.multibulk(client, command, arguments)
end
end
local function parse_info(response)
local info = {}
local current = info
response:gsub('([^\r\n]*)\r\n', function(kv)
if kv == '' then return end
local section = kv:match('^# (%w+)$')
if section then
current = {}
info[section:lower()] = current
return
end
local k,v = kv:match(('([^:]*):([^:]*)'):rep(1))
if k:match('db%d+') then
current[k] = {}
v:gsub(',', function(dbkv)
local dbk,dbv = kv:match('([^:]*)=([^:]*)')
current[k][dbk] = dbv
end)
else
current[k] = v
end
end)
return info
end
local function load_methods(proto, commands)
local client = setmetatable ({}, getmetatable(proto))
for cmd, fn in pairs(commands) do
if type(fn) ~= 'function' then
redis.error('invalid type for command ' .. cmd .. '(must be a function)')
end
client[cmd] = fn
end
for i, v in pairs(proto) do
client[i] = v
end
return client
end
local function create_client(proto, client_socket, commands)
local client = load_methods(proto, commands)
client.error = redis.error
client.network = {
socket = client_socket,
read = network.read,
write = network.write,
}
client.requests = {
multibulk = request.multibulk,
}
return client
end
-- ############################################################################
function network.write(client, buffer)
local _, err = client.network.socket:send(buffer)
if err then client.error(err) end
end
function network.read(client, len)
if len == nil then len = '*l' end
local line, err = client.network.socket:receive(len)
if not err then return line else client.error('connection error: ' .. err) end
end
-- ############################################################################
function response.read(client)
local payload = client.network.read(client)
local prefix, data = payload:sub(1, -#payload), payload:sub(2)
-- status reply
if prefix == '+' then
if data == 'OK' then
return true
elseif data == 'QUEUED' then
return { queued = true }
else
return data
end
-- error reply
elseif prefix == '-' then
return client.error('redis error: ' .. data)
-- integer reply
elseif prefix == ':' then
local number = tonumber(data)
if not number then
if res == 'nil' then
return nil
end
client.error('cannot parse '..res..' as a numeric response.')
end
return number
-- bulk reply
elseif prefix == '$' then
local length = tonumber(data)
if not length then
client.error('cannot parse ' .. length .. ' as data length')
end
if length == -1 then
return nil
end
local nextchunk = client.network.read(client, length + 2)
return nextchunk:sub(1, -3)
-- multibulk reply
elseif prefix == '*' then
local count = tonumber(data)
if count == -1 then
return nil
end
local list = {}
if count > 0 then
local reader = response.read
for i = 1, count do
list[i] = reader(client)
end
end
return list
-- unknown type of reply
else
return client.error('unknown response prefix: ' .. prefix)
end
end
-- ############################################################################
function request.raw(client, buffer)
local bufferType = type(buffer)
if bufferType == 'table' then
client.network.write(client, table.concat(buffer))
elseif bufferType == 'string' then
client.network.write(client, buffer)
else
client.error('argument error: ' .. bufferType)
end
end
function request.multibulk(client, command, ...)
local args = {...}
local argsn = #args
local buffer = { true, true }
if argsn == 1 and type(args[1]) == 'table' then
argsn, args = #args[1], args[1]
end
buffer[1] = '*' .. tostring(argsn + 1) .. "\r\n"
buffer[2] = '$' .. #command .. "\r\n" .. command .. "\r\n"
local table_insert = table.insert
for _, argument in pairs(args) do
local s_argument = tostring(argument)
table_insert(buffer, '$' .. #s_argument .. "\r\n" .. s_argument .. "\r\n")
end
client.network.write(client, table.concat(buffer))
end
-- ############################################################################
local function custom(command, send, parse)
command = string.upper(command)
return function(client, ...)
send(client, command, ...)
local reply = response.read(client)
if type(reply) == 'table' and reply.queued then
reply.parser = parse
return reply
else
if parse then
return parse(reply, command, ...)
end
return reply
end
end
end
local function command(command, opts)
if opts == nil or type(opts) == 'function' then
return custom(command, request.multibulk, opts)
else
return custom(command, opts.request or request.multibulk, opts.response)
end
end
local define_command_impl = function(target, name, opts)
local opts = opts or {}
target[string.lower(name)] = custom(
opts.command or string.upper(name),
opts.request or request.multibulk,
opts.response or nil
)
end
local undefine_command_impl = function(target, name)
target[string.lower(name)] = nil
end
-- ############################################################################
local client_prototype = {}
client_prototype.raw_cmd = function(client, buffer)
request.raw(client, buffer .. "\r\n")
return response.read(client)
end
-- obsolete
client_prototype.define_command = function(client, name, opts)
define_command_impl(client, name, opts)
end
-- obsolete
client_prototype.undefine_command = function(client, name)
undefine_command_impl(client, name)
end
client_prototype.quit = function(client)
request.multibulk(client, 'QUIT')
client.network.socket:shutdown()
return true
end
client_prototype.shutdown = function(client)
request.multibulk(client, 'SHUTDOWN')
client.network.socket:shutdown()
end
-- Command pipelining
client_prototype.pipeline = function(client, block)
local requests, replies, parsers = {}, {}, {}
local table_insert = table.insert
local socket_write, socket_read = client.network.write, client.network.read
client.network.write = function(_, buffer)
table_insert(requests, buffer)
end
-- TODO: this hack is necessary to temporarily reuse the current
-- request -> response handling implementation of redis-lua
-- without further changes in the code, but it will surely
-- disappear when the new command-definition infrastructure
-- will finally be in place.
client.network.read = function() return '+QUEUED' end
local pipeline = setmetatable({}, {
__index = function(env, name)
local cmd = client[name]
if not cmd then
client.error('unknown redis command: ' .. name, 2)
end
return function(self, ...)
local reply = cmd(client, ...)
table_insert(parsers, #requests, reply.parser)
return reply
end
end
})
local success, retval = pcall(block, pipeline)
client.network.write, client.network.read = socket_write, socket_read
if not success then client.error(retval, 0) end
client.network.write(client, table.concat(requests, ''))
for i = 1, #requests do
local reply, parser = response.read(client), parsers[i]
if parser then
reply = parser(reply)
end
table_insert(replies, i, reply)
end
return replies, #requests
end
-- Publish/Subscribe
do
local channels = function(channels)
if type(channels) == 'string' then
channels = { channels }
end
return channels
end
local subscribe = function(client, ...)
request.multibulk(client, 'subscribe', ...)
end
local psubscribe = function(client, ...)
request.multibulk(client, 'psubscribe', ...)
end
local unsubscribe = function(client, ...)
request.multibulk(client, 'unsubscribe')
end
local punsubscribe = function(client, ...)
request.multibulk(client, 'punsubscribe')
end
local consumer_loop = function(client)
local aborting, subscriptions = false, 0
local abort = function()
if not aborting then
unsubscribe(client)
punsubscribe(client)
aborting = true
end
end
return coroutine.wrap(function()
while true do
local message
local response = response.read(client)
if response[1] == 'pmessage' then
message = {
kind = response[1],
pattern = response[2],
channel = response[3],
payload = response[4],
}
else
message = {
kind = response[1],
channel = response[2],
payload = response[3],
}
end
if string.match(message.kind, '^p?subscribe$') then
subscriptions = subscriptions + 1
end
if string.match(message.kind, '^p?unsubscribe$') then
subscriptions = subscriptions - 1
end
if aborting and subscriptions == 0 then
break
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.pubsub = function(client, subscriptions)
if type(subscriptions) == 'table' then
if subscriptions.subscribe then
subscribe(client, channels(subscriptions.subscribe))
end
if subscriptions.psubscribe then
psubscribe(client, channels(subscriptions.psubscribe))
end
end
return consumer_loop(client)
end
end
-- Redis transactions (MULTI/EXEC)
do
local function identity(...) return ... end
local emptytable = {}
local function initialize_transaction(client, options, block, queued_parsers)
local table_insert = table.insert
local coro = coroutine.create(block)
if options.watch then
local watch_keys = {}
for _, key in pairs(options.watch) do
table_insert(watch_keys, key)
end
if #watch_keys > 0 then
client:watch(unpack(watch_keys))
end
end
local transaction_client = setmetatable({}, {__index=client})
transaction_client.exec = function(...)
client.error('cannot use EXEC inside a transaction block')
end
transaction_client.multi = function(...)
coroutine.yield()
end
transaction_client.commands_queued = function()
return #queued_parsers
end
assert(coroutine.resume(coro, transaction_client))
transaction_client.multi = nil
transaction_client.discard = function(...)
local reply = client:discard()
for i, v in pairs(queued_parsers) do
queued_parsers[i]=nil
end
coro = initialize_transaction(client, options, block, queued_parsers)
return reply
end
transaction_client.watch = function(...)
client.error('WATCH inside MULTI is not allowed')
end
setmetatable(transaction_client, { __index = function(t, k)
local cmd = client[k]
if type(cmd) == "function" then
local function queuey(self, ...)
local reply = cmd(client, ...)
assert((reply or emptytable).queued == true, 'a QUEUED reply was expected')
table_insert(queued_parsers, reply.parser or identity)
return reply
end
t[k]=queuey
return queuey
else
return cmd
end
end
})
client:multi()
return coro
end
local function transaction(client, options, coroutine_block, attempts)
local queued_parsers, replies = {}, {}
local retry = tonumber(attempts) or tonumber(options.retry) or 2
local coro = initialize_transaction(client, options, coroutine_block, queued_parsers)
local success, retval
if coroutine.status(coro) == 'suspended' then
success, retval = coroutine.resume(coro)
else
-- do not fail if the coroutine has not been resumed (missing t:multi() with CAS)
success, retval = true, 'empty transaction'
end
if #queued_parsers == 0 or not success then
client:discard()
assert(success, retval)
return replies, 0
end
local raw_replies = client:exec()
if not raw_replies then
if (retry or 0) <= 0 then
client.error("MULTI/EXEC transaction aborted by the server")
else
--we're not quite done yet
return transaction(client, options, coroutine_block, retry - 1)
end
end
local table_insert = table.insert
for i, parser in pairs(queued_parsers) do
table_insert(replies, i, parser(raw_replies[i]))
end
return replies, #queued_parsers
end
client_prototype.transaction = function(client, arg1, arg2)
local options, block
if not arg2 then
options, block = {}, arg1
elseif arg1 then --and arg2, implicitly
options, block = type(arg1)=="table" and arg1 or { arg1 }, arg2
else
client.error("Invalid parameters for redis transaction.")
end
if not options.watch then
watch_keys = { }
for i, v in pairs(options) do
if tonumber(i) then
table.insert(watch_keys, v)
options[i] = nil
end
end
options.watch = watch_keys
elseif not (type(options.watch) == 'table') then
options.watch = { options.watch }
end
if not options.cas then
local tx_block = block
block = function(client, ...)
client:multi()
return tx_block(client, ...) --can't wrap this in pcall because we're in a coroutine.
end
end
return transaction(client, options, block)
end
end
-- MONITOR context
do
local monitor_loop = function(client)
local monitoring = true
-- Tricky since the payload format changed starting from Redis 2.6.
local pattern = '^(%d+%.%d+)( ?.- ?) ?"(%a+)" ?(.-)$'
local abort = function()
monitoring = false
end
return coroutine.wrap(function()
client:monitor()
while monitoring do
local message, matched
local response = response.read(client)
local ok = response:gsub(pattern, function(time, info, cmd, args)
message = {
timestamp = tonumber(time),
client = info:match('%d+.%d+.%d+.%d+:%d+'),
database = tonumber(info:match('%d+')) or 0,
command = cmd,
arguments = args:match('.+'),
}
matched = true
end)
if not matched then
client.error('Unable to match MONITOR payload: '..response)
end
coroutine.yield(message, abort)
end
end)
end
client_prototype.monitor_messages = function(client)
return monitor_loop(client)
end
end
-- ############################################################################
local function connect_tcp(socket, parameters)
local host, port = parameters.host, tonumber(parameters.port)
local ok, err = socket:connect(host, port)
if not ok then
redis.error('could not connect to '..host..':'..port..' ['..err..']')
end
socket:setoption('tcp-nodelay', parameters.tcp_nodelay)
return socket
end
local function connect_unix(socket, parameters)
local ok, err = socket:connect(parameters.path)
if not ok then
redis.error('could not connect to '..parameters.path..' ['..err..']')
end
return socket
end
local function create_connection(parameters)
if parameters.socket then
return parameters.socket
end
local perform_connection, socket
if parameters.scheme == 'unix' then
perform_connection, socket = connect_unix, require('socket.unix')
assert(socket, 'your build of LuaSocket does not support UNIX domain sockets')
else
if parameters.scheme then
local scheme = parameters.scheme
assert(scheme == 'redis' or scheme == 'tcp', 'invalid scheme: '..scheme)
end
perform_connection, socket = connect_tcp, require('socket').tcp
end
return perform_connection(socket(), parameters)
end
-- ############################################################################
function redis.error(message, level)
error(message, (level or 1) + 1)
end
function redis.connect(...)
local args, parameters = {...}, nil
if #args == 1 then
if type(args[1]) == 'table' then
parameters = args[1]
else
local uri = require('socket.url')
parameters = uri.parse(select(1, ...))
if parameters.scheme then
if parameters.query then
for k, v in parameters.query:gmatch('([-_%w]+)=([-_%w]+)') do
if k == 'tcp_nodelay' or k == 'tcp-nodelay' then
parameters.tcp_nodelay = parse_boolean(v)
end
end
end
else
parameters.host = parameters.path
end
end
elseif #args > 1 then
local host, port = unpack(args)
parameters = { host = host, port = port }
end
local commands = redis.commands or {}
if type(commands) ~= 'table' then
redis.error('invalid type for the commands table')
end
local socket = create_connection(merge_defaults(parameters))
local client = create_client(client_prototype, socket, commands)
return client
end
function redis.command(cmd, opts)
return command(cmd, opts)
end
-- obsolete
function redis.define_command(name, opts)
define_command_impl(redis.commands, name, opts)
end
-- obsolete
function redis.undefine_command(name)
undefine_command_impl(redis.commands, name)
end
-- ############################################################################
-- Commands defined in this table do not take the precedence over
-- methods defined in the client prototype table.
redis.commands = {
-- commands operating on the key space
exists = command('EXISTS', {
response = toboolean
}),
del = command('DEL'),
type = command('TYPE'),
rename = command('RENAME'),
renamenx = command('RENAMENX', {
response = toboolean
}),
expire = command('EXPIRE', {
response = toboolean
}),
pexpire = command('PEXPIRE', { -- >= 2.6
response = toboolean
}),
expireat = command('EXPIREAT', {
response = toboolean
}),
pexpireat = command('PEXPIREAT', { -- >= 2.6
response = toboolean
}),
ttl = command('TTL'),
pttl = command('PTTL'), -- >= 2.6
move = command('MOVE', {
response = toboolean
}),
dbsize = command('DBSIZE'),
persist = command('PERSIST', { -- >= 2.2
response = toboolean
}),
keys = command('KEYS', {
response = function(response)
if type(response) == 'string' then
-- backwards compatibility path for Redis < 2.0
local keys = {}
response:gsub('[^%s]+', function(key)
table.insert(keys, key)
end)
response = keys
end
return response
end
}),
randomkey = command('RANDOMKEY', {
response = function(response)
if response == '' then
return nil
else
return response
end
end
}),
sort = command('SORT', {
request = sort_request,
}),
-- commands operating on string values
set = command('SET'),
setnx = command('SETNX', {
response = toboolean
}),
setex = command('SETEX'), -- >= 2.0
psetex = command('PSETEX'), -- >= 2.6
mset = command('MSET', {
request = mset_filter_args
}),
msetnx = command('MSETNX', {
request = mset_filter_args,
response = toboolean
}),
get = command('GET'),
mget = command('MGET'),
getset = command('GETSET'),
incr = command('INCR'),
incrby = command('INCRBY'),
incrbyfloat = command('INCRBYFLOAT', { -- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
decr = command('DECR'),
decrby = command('DECRBY'),
append = command('APPEND'), -- >= 2.0
substr = command('SUBSTR'), -- >= 2.0
strlen = command('STRLEN'), -- >= 2.2
setrange = command('SETRANGE'), -- >= 2.2
getrange = command('GETRANGE'), -- >= 2.2
setbit = command('SETBIT'), -- >= 2.2
getbit = command('GETBIT'), -- >= 2.2
-- commands operating on lists
rpush = command('RPUSH'),
lpush = command('LPUSH'),
llen = command('LLEN'),
lrange = command('LRANGE'),
ltrim = command('LTRIM'),
lindex = command('LINDEX'),
lset = command('LSET'),
lrem = command('LREM'),
lpop = command('LPOP'),
rpop = command('RPOP'),
rpoplpush = command('RPOPLPUSH'),
blpop = command('BLPOP'), -- >= 2.0
brpop = command('BRPOP'), -- >= 2.0
rpushx = command('RPUSHX'), -- >= 2.2
lpushx = command('LPUSHX'), -- >= 2.2
linsert = command('LINSERT'), -- >= 2.2
brpoplpush = command('BRPOPLPUSH'), -- >= 2.2
-- commands operating on sets
sadd = command('SADD'),
srem = command('SREM'),
spop = command('SPOP'),
smove = command('SMOVE', {
response = toboolean
}),
scard = command('SCARD'),
sismember = command('SISMEMBER', {
response = toboolean
}),
sinter = command('SINTER'),
sinterstore = command('SINTERSTORE'),
sunion = command('SUNION'),
sunionstore = command('SUNIONSTORE'),
sdiff = command('SDIFF'),
sdiffstore = command('SDIFFSTORE'),
smembers = command('SMEMBERS'),
srandmember = command('SRANDMEMBER'),
-- commands operating on sorted sets
zadd = command('ZADD'),
zincrby = command('ZINCRBY'),
zrem = command('ZREM'),
zrange = command('ZRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrevrange = command('ZREVRANGE', {
request = zset_range_request,
response = zset_range_reply,
}),
zrangebyscore = command('ZRANGEBYSCORE', {
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zrevrangebyscore = command('ZREVRANGEBYSCORE', { -- >= 2.2
request = zset_range_byscore_request,
response = zset_range_reply,
}),
zunionstore = command('ZUNIONSTORE', { -- >= 2.0
request = zset_store_request
}),
zinterstore = command('ZINTERSTORE', { -- >= 2.0
request = zset_store_request
}),
zcount = command('ZCOUNT'),
zcard = command('ZCARD'),
zscore = command('ZSCORE'),
zremrangebyscore = command('ZREMRANGEBYSCORE'),
zrank = command('ZRANK'), -- >= 2.0
zrevrank = command('ZREVRANK'), -- >= 2.0
zremrangebyrank = command('ZREMRANGEBYRANK'), -- >= 2.0
-- commands operating on hashes
hset = command('HSET', { -- >= 2.0
response = toboolean
}),
hsetnx = command('HSETNX', { -- >= 2.0
response = toboolean
}),
hmset = command('HMSET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, k)
table.insert(args, v)
end),
}),
hincrby = command('HINCRBY'), -- >= 2.0
hincrbyfloat = command('HINCRBYFLOAT', {-- >= 2.6
response = function(reply, command, ...)
return tonumber(reply)
end,
}),
hget = command('HGET'), -- >= 2.0
hmget = command('HMGET', { -- >= 2.0
request = hash_multi_request_builder(function(args, k, v)
table.insert(args, v)
end),
}),
hdel = command('HDEL'), -- >= 2.0
hexists = command('HEXISTS', { -- >= 2.0
response = toboolean
}),
hlen = command('HLEN'), -- >= 2.0
hkeys = command('HKEYS'), -- >= 2.0
hvals = command('HVALS'), -- >= 2.0
hgetall = command('HGETALL', { -- >= 2.0
response = function(reply, command, ...)
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
}),
-- connection related commands
ping = command('PING', {
response = function(response) return response == 'PONG' end
}),
echo = command('ECHO'),
auth = command('AUTH'),
select = command('SELECT'),
-- transactions
multi = command('MULTI'), -- >= 2.0
exec = command('EXEC'), -- >= 2.0
discard = command('DISCARD'), -- >= 2.0
watch = command('WATCH'), -- >= 2.2
unwatch = command('UNWATCH'), -- >= 2.2
-- publish - subscribe
subscribe = command('SUBSCRIBE'), -- >= 2.0
unsubscribe = command('UNSUBSCRIBE'), -- >= 2.0
psubscribe = command('PSUBSCRIBE'), -- >= 2.0
punsubscribe = command('PUNSUBSCRIBE'), -- >= 2.0
publish = command('PUBLISH'), -- >= 2.0
-- redis scripting
eval = command('EVAL'), -- >= 2.6
evalsha = command('EVALSHA'), -- >= 2.6
script = command('SCRIPT'), -- >= 2.6
-- remote server control commands
bgrewriteaof = command('BGREWRITEAOF'),
config = command('CONFIG', { -- >= 2.0
response = function(reply, command, ...)
if (type(reply) == 'table') then
local new_reply = { }
for i = 1, #reply, 2 do new_reply[reply[i]] = reply[i + 1] end
return new_reply
end
return reply
end
}),
client = command('CLIENT'), -- >= 2.4
slaveof = command('SLAVEOF'),
save = command('SAVE'),
bgsave = command('BGSAVE'),
lastsave = command('LASTSAVE'),
flushdb = command('FLUSHDB'),
flushall = command('FLUSHALL'),
monitor = command('MONITOR'),
time = command('TIME'), -- >= 2.6
slowlog = command('SLOWLOG', { -- >= 2.2.13
response = function(reply, command, ...)
if (type(reply) == 'table') then
local structured = { }
for index, entry in ipairs(reply) do
structured[index] = {
id = tonumber(entry[1]),
timestamp = tonumber(entry[2]),
duration = tonumber(entry[3]),
command = entry[4],
}
end
return structured
end
return reply
end
}),
info = command('INFO', {
response = parse_info,
}),
}
-- ############################################################################
return redis
| gpl-2.0 |
jiuaiwo1314/skynet | lualib/http/httpd.lua | 101 | 3708 | local internal = require "http.internal"
local table = table
local string = string
local type = type
local httpd = {}
local http_status_msg = {
[100] = "Continue",
[101] = "Switching Protocols",
[200] = "OK",
[201] = "Created",
[202] = "Accepted",
[203] = "Non-Authoritative Information",
[204] = "No Content",
[205] = "Reset Content",
[206] = "Partial Content",
[300] = "Multiple Choices",
[301] = "Moved Permanently",
[302] = "Found",
[303] = "See Other",
[304] = "Not Modified",
[305] = "Use Proxy",
[307] = "Temporary Redirect",
[400] = "Bad Request",
[401] = "Unauthorized",
[402] = "Payment Required",
[403] = "Forbidden",
[404] = "Not Found",
[405] = "Method Not Allowed",
[406] = "Not Acceptable",
[407] = "Proxy Authentication Required",
[408] = "Request Time-out",
[409] = "Conflict",
[410] = "Gone",
[411] = "Length Required",
[412] = "Precondition Failed",
[413] = "Request Entity Too Large",
[414] = "Request-URI Too Large",
[415] = "Unsupported Media Type",
[416] = "Requested range not satisfiable",
[417] = "Expectation Failed",
[500] = "Internal Server Error",
[501] = "Not Implemented",
[502] = "Bad Gateway",
[503] = "Service Unavailable",
[504] = "Gateway Time-out",
[505] = "HTTP Version not supported",
}
local function readall(readbytes, bodylimit)
local tmpline = {}
local body = internal.recvheader(readbytes, tmpline, "")
if not body then
return 413 -- Request Entity Too Large
end
local request = assert(tmpline[1])
local method, url, httpver = request:match "^(%a+)%s+(.-)%s+HTTP/([%d%.]+)$"
assert(method and url and httpver)
httpver = assert(tonumber(httpver))
if httpver < 1.0 or httpver > 1.1 then
return 505 -- HTTP Version not supported
end
local header = internal.parseheader(tmpline,2,{})
if not header then
return 400 -- Bad request
end
local length = header["content-length"]
if length then
length = tonumber(length)
end
local mode = header["transfer-encoding"]
if mode then
if mode ~= "identity" and mode ~= "chunked" then
return 501 -- Not Implemented
end
end
if mode == "chunked" then
body, header = internal.recvchunkedbody(readbytes, bodylimit, header, body)
if not body then
return 413
end
else
-- identity mode
if length then
if bodylimit and length > bodylimit then
return 413
end
if #body >= length then
body = body:sub(1,length)
else
local padding = readbytes(length - #body)
body = body .. padding
end
end
end
return 200, url, method, header, body
end
function httpd.read_request(...)
local ok, code, url, method, header, body = pcall(readall, ...)
if ok then
return code, url, method, header, body
else
return nil, code
end
end
local function writeall(writefunc, statuscode, bodyfunc, header)
local statusline = string.format("HTTP/1.1 %03d %s\r\n", statuscode, http_status_msg[statuscode] or "")
writefunc(statusline)
if header then
for k,v in pairs(header) do
if type(v) == "table" then
for _,v in ipairs(v) do
writefunc(string.format("%s: %s\r\n", k,v))
end
else
writefunc(string.format("%s: %s\r\n", k,v))
end
end
end
local t = type(bodyfunc)
if t == "string" then
writefunc(string.format("content-length: %d\r\n\r\n", #bodyfunc))
writefunc(bodyfunc)
elseif t == "function" then
writefunc("transfer-encoding: chunked\r\n")
while true do
local s = bodyfunc()
if s then
if s ~= "" then
writefunc(string.format("\r\n%x\r\n", #s))
writefunc(s)
end
else
writefunc("\r\n0\r\n\r\n")
break
end
end
else
assert(t == "nil")
writefunc("\r\n")
end
end
function httpd.write_response(...)
return pcall(writeall, ...)
end
return httpd
| mit |
amirb8/TELEHONES- | plugins/all.lua | 1321 | 4661 | do
data = load_data(_config.moderation.data)
local function get_msgs_user_chat(user_id, chat_id)
local user_info = {}
local uhash = 'user:'..user_id
local user = redis:hgetall(uhash)
local um_hash = 'msgs:'..user_id..':'..chat_id
user_info.msgs = tonumber(redis:get(um_hash) or 0)
user_info.name = user_print_name(user)..' ['..user_id..']'
return user_info
end
local function chat_stats(chat_id)
local hash = 'chat:'..chat_id..':users'
local users = redis:smembers(hash)
local users_info = {}
for i = 1, #users do
local user_id = users[i]
local user_info = get_msgs_user_chat(user_id, chat_id)
table.insert(users_info, user_info)
end
table.sort(users_info, function(a, b)
if a.msgs and b.msgs then
return a.msgs > b.msgs
end
end)
local text = 'Chat stats:\n'
for k,user in pairs(users_info) do
text = text..user.name..' = '..user.msgs..'\n'
end
return text
end
local function get_group_type(target)
local data = load_data(_config.moderation.data)
local group_type = data[tostring(target)]['group_type']
if not group_type or group_type == nil then
return 'No group type available.'
end
return group_type
end
local function show_group_settings(target)
local data = load_data(_config.moderation.data)
if data[tostring(target)] then
if data[tostring(target)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(target)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Lock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function get_description(target)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
if not data[tostring(target)][data_cat] then
return 'No description available.'
end
local about = data[tostring(target)][data_cat]
return about
end
local function get_rules(target)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
if not data[tostring(target)][data_cat] then
return 'No rules available.'
end
local rules = data[tostring(target)][data_cat]
return rules
end
local function modlist(target)
local data = load_data(_config.moderation.data)
local groups = 'groups'
if not data[tostring(groups)] or not data[tostring(groups)][tostring(target)] then
return 'Group is not added or is Realm.'
end
if next(data[tostring(target)]['moderators']) == nil then
return 'No moderator in this group.'
end
local i = 1
local message = '\nList of moderators :\n'
for k,v in pairs(data[tostring(target)]['moderators']) do
message = message ..i..' - @'..v..' [' ..k.. '] \n'
i = i + 1
end
return message
end
local function get_link(target)
local data = load_data(_config.moderation.data)
local group_link = data[tostring(target)]['settings']['set_link']
if not group_link or group_link == nil then
return "No link"
end
return "Group link:\n"..group_link
end
local function all(target, receiver)
local text = "All the things I know about this group\n\n"
local group_type = get_group_type(target)
text = text.."Group Type: \n"..group_type
local settings = show_group_settings(target)
text = text.."\n\nGroup settings: \n"..settings
local rules = get_rules(target)
text = text.."\n\nRules: \n"..rules
local description = get_description(target)
text = text.."\n\nAbout: \n"..description
local modlist = modlist(target)
text = text.."\n\nMods: \n"..modlist
local link = get_link(target)
text = text.."\n\nLink: \n"..link
local stats = chat_stats(target)
text = text.."\n\n"..stats
local ban_list = ban_list(target)
text = text.."\n\n"..ban_list
local file = io.open("./groups/all/"..target.."all.txt", "w")
file:write(text)
file:flush()
file:close()
send_document(receiver,"./groups/all/"..target.."all.txt", ok_cb, false)
return
end
function run(msg, matches)
if matches[1] == "all" and matches[2] and is_owner2(msg.from.id, matches[2]) then
local receiver = get_receiver(msg)
local target = matches[2]
return all(target, receiver)
end
if not is_owner(msg) then
return
end
if matches[1] == "all" and not matches[2] then
local receiver = get_receiver(msg)
if not is_owner(msg) then
return
end
return all(msg.to.id, receiver)
end
end
return {
patterns = {
"^[!/](all)$",
"^[!/](all) (%d+)$"
},
run = run
}
end
| gpl-2.0 |
gitTerebi/OpenRA | mods/d2k/maps/atreides-01b/atreides01b.lua | 18 | 4800 |
HarkonnenReinforcements = { }
HarkonnenReinforcements["Easy"] =
{
{ "rifle", "rifle" }
}
HarkonnenReinforcements["Normal"] =
{
{ "rifle", "rifle" },
{ "rifle", "rifle", "rifle" },
{ "rifle", "trike" },
}
HarkonnenReinforcements["Hard"] =
{
{ "rifle", "rifle" },
{ "trike", "trike" },
{ "rifle", "rifle", "rifle" },
{ "rifle", "trike" },
{ "trike", "trike" }
}
HarkonnenEntryWaypoints = { HarkonnenWaypoint1.Location, HarkonnenWaypoint2.Location, HarkonnenWaypoint3.Location, HarkonnenWaypoint4.Location }
HarkonnenAttackDelay = DateTime.Seconds(30)
HarkonnenAttackWaves = { }
HarkonnenAttackWaves["Easy"] = 1
HarkonnenAttackWaves["Normal"] = 5
HarkonnenAttackWaves["Hard"] = 12
ToHarvest = { }
ToHarvest["Easy"] = 2500
ToHarvest["Normal"] = 3000
ToHarvest["Hard"] = 3500
AtreidesReinforcements = { "rifle", "rifle", "rifle", "rifle" }
AtreidesEntryPath = { AtreidesWaypoint.Location, AtreidesRally.Location }
Messages =
{
"Build a concrete foundation before placing your buildings.",
"Build a Wind Trap for power.",
"Build a Refinery to collect Spice.",
"Build a Silo to store additional Spice."
}
IdleHunt = function(actor)
if not actor.IsDead then
Trigger.OnIdle(actor, actor.Hunt)
end
end
Tick = function()
if HarkonnenArrived and harkonnen.HasNoRequiredUnits() then
player.MarkCompletedObjective(KillHarkonnen)
end
if player.Resources > ToHarvest[Map.Difficulty] - 1 then
player.MarkCompletedObjective(GatherSpice)
end
-- player has no Wind Trap
if (player.PowerProvided <= 20 or player.PowerState ~= "Normal") and DateTime.GameTime % DateTime.Seconds(32) == 0 then
HasPower = false
Media.DisplayMessage(Messages[2], "Mentat")
else
HasPower = true
end
-- player has no Refinery and no Silos
if HasPower and player.ResourceCapacity == 0 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[3], "Mentat")
end
if HasPower and player.Resources > player.ResourceCapacity * 0.8 and DateTime.GameTime % DateTime.Seconds(32) == 0 then
Media.DisplayMessage(Messages[4], "Mentat")
end
UserInterface.SetMissionText("Harvested resources: " .. player.Resources .. "/" .. ToHarvest[Map.Difficulty], player.Color)
end
WorldLoaded = function()
player = Player.GetPlayer("Atreides")
harkonnen = Player.GetPlayer("Harkonnen")
InitObjectives()
Trigger.OnRemovedFromWorld(AtreidesConyard, function()
local refs = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(actor)
return actor.Type == "refinery"
end)
if #refs == 0 then
harkonnen.MarkCompletedObjective(KillAtreides)
else
Trigger.OnAllRemovedFromWorld(refs, function()
harkonnen.MarkCompletedObjective(KillAtreides)
end)
end
end)
Media.DisplayMessage(Messages[1], "Mentat")
Trigger.AfterDelay(DateTime.Seconds(25), function()
Media.PlaySpeechNotification(player, "Reinforce")
Reinforcements.Reinforce(player, AtreidesReinforcements, AtreidesEntryPath)
end)
WavesLeft = HarkonnenAttackWaves[Map.Difficulty]
SendReinforcements()
end
SendReinforcements = function()
local units = HarkonnenReinforcements[Map.Difficulty]
local delay = Utils.RandomInteger(HarkonnenAttackDelay - DateTime.Seconds(2), HarkonnenAttackDelay)
HarkonnenAttackDelay = HarkonnenAttackDelay - (#units * 3 - 3 - WavesLeft) * DateTime.Seconds(1)
if HarkonnenAttackDelay < 0 then HarkonnenAttackDelay = 0 end
Trigger.AfterDelay(delay, function()
Reinforcements.Reinforce(harkonnen, Utils.Random(units), { Utils.Random(HarkonnenEntryWaypoints) }, 10, IdleHunt)
WavesLeft = WavesLeft - 1
if WavesLeft == 0 then
Trigger.AfterDelay(DateTime.Seconds(1), function() HarkonnenArrived = true end)
else
SendReinforcements()
end
end)
end
InitObjectives = function()
Trigger.OnObjectiveAdded(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
KillAtreides = harkonnen.AddPrimaryObjective("Kill all Atreides units.")
GatherSpice = player.AddPrimaryObjective("Harvest " .. tostring(ToHarvest[Map.Difficulty]) .. " Solaris worth of Spice.")
KillHarkonnen = player.AddSecondaryObjective("Eliminate all Harkonnen units and reinforcements\nin the area.")
Trigger.OnObjectiveCompleted(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(player, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerLost(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Lose")
end)
end)
Trigger.OnPlayerWon(player, function()
Trigger.AfterDelay(DateTime.Seconds(1), function()
Media.PlaySpeechNotification(player, "Win")
end)
end)
end
| gpl-3.0 |
marcosalm/RIOT | dist/tools/wireshark_dissector/riot.lua | 21 | 2130 | -- RIOT native support for Wireshark
-- A Lua implementation for dissection of RIOT native packets in wireshark
-- @Version: 0.0.1
-- @Author: Martine Lenders
-- @E-Mail: mlenders@inf.fu-berlin.de
do
--Protocol name "RIOT"
local p_riot = Proto("RIOT", "RIOT native packet")
--Protocol Fields
local f_length = ProtoField.uint16("RIOT.length", "Length", base.DEC, nil)
local f_dst = ProtoField.uint16("RIOT.dst", "Destination", base.DEC, nil)
local f_src = ProtoField.uint16("RIOT.src", "Source", base.DEC, nil)
local f_pad = ProtoField.bytes("RIOT.pad", "Padding")
p_riot.fields = { f_length, f_dst, f_src }
local data_dis = Dissector.get("data")
-- local next_dis = Dissector.get("6lowpan") -- for 6LoWPAN
local next_dis = Dissector.get("wpan") -- for IEEE 802.15.4
function riot_dissector(buf, pkt, root)
local buf_len = buf:len()
local riot_tree = root:add(p_riot, buf)
if buf_len < 6 then return false end
local packet_len = buf(0,2):uint()
local dst = buf(2,2):uint()
local src = buf(4,2):uint()
if packet_len >= 46 and buf_len - 6 ~= packet_len then return false end
riot_tree:append_text(", Dst: ")
riot_tree:append_text(dst)
riot_tree:append_text(", Src: ")
riot_tree:append_text(src)
riot_tree:append_text(", Length: ")
riot_tree:append_text(packet_len)
riot_tree:add(f_length, buf(0, 2))
riot_tree:add(f_dst, buf(2, 2))
riot_tree:add(f_src, buf(4, 2))
-- to show the padding for small packets uncomment the
-- following line and append "f_pad" to p_riot.fields above.
-- riot_tree:add(f_pad, buf(packet_len + 6))
next_dis:call(buf(6, packet_len):tvb(), pkt, root)
return true
end
function p_riot.dissector(buf, pkt, root)
if not riot_dissector(buf, pkt, root) then
data_dis:call(buf, pkt, root)
end
end
local eth_encap_table = DissectorTable.get("ethertype")
--handle ethernet type 0x1234
eth_encap_table:add(0x1234, p_riot)
end
| lgpl-2.1 |
tudelft/chdkptp | lua/gui_sched.lua | 5 | 2389 | --[[
Copyright (C) 2010-2014 <reyalp (at) gmail dot com>
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License version 2 as
published by the Free Software Foundation.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
]]
--[[
module for gui timer/scheduler
]]
local m={
now=ustime.new(),
pending={},
repeating={},
}
function m.ensure_timer_running()
if not m.timer then
error('gui_sched timer not initialized')
end
if m.timer.run ~= 'YES' then
m.timer.run = 'YES'
end
end
--[[
call scheduled function after time ms
]]
function m.run_after(time,fn,data)
local t=ustime.new()
t:addms(time)
table.insert(m.pending,{time=t,fn=fn,data=data})
m.ensure_timer_running()
end
function m.run_repeat(time,fn,data)
t = {
last=ustime.new(),
time=time,
fn=fn,
data=data,
}
t.cancel=function(self)
m.repeating[t]=nil
end
m.repeating[t] = t
m.ensure_timer_running()
return t
end
m.tick=errutil.wrap(function()
m.now:get()
local num_pending = 0
for k,v in pairs(m.pending) do
-- printf('check %f %f\n',v.time:float(),m.now:float())
if v.time:float() < m.now:float() then
-- printf('run\n')
m.pending[k]=nil
v:fn()
else
num_pending = num_pending + 1
end
end
local num_repeating = 0
for k,v in pairs(m.repeating) do
if v.last:diffms(now) > v.time then
v.last:get() -- TODO might want to check for run time > interval to avoid pile-up
-- could update after run
v:fn()
end
num_repeating = num_repeating + 1
end
-- stop running timer if no jobs
if num_pending == 0 and num_repeating == 0 then
m.timer.run = "NO"
end
end)
function m.init_timer(time)
if not time then
time = 50
end
if m.timer then
iup.Destroy(m.timer)
end
m.timer = iup.timer{
time = tostring(time),
action_cb = m.tick,
run = "NO", -- first scheduled action will start
-- note for some reason, creating with YES fails occasionally, setting after seems OK
}
end
return m
| gpl-2.0 |
DigitalVeer/Lua-Research | Tables/Matrix.lua | 2 | 1309 | --[[
Gives a way for transposing a matrix and printing it to a readable form for humans
]]--
local Matrix = { }
function Matrix.new(m, n, contents)
assert(m*n == #contents)
local ourMatrix = { }
function ourMatrix:transpose()
local twoDTransform = {}
for row = 1,m do
local temp = {}
for col = 1,n do
local currentIndex = n*(row-1) + col;
table.insert(temp,contents[currentIndex])
end
table.insert(twoDTransform,temp)
temp = {}
end
local function transpose(inputMatrix)
local newMatrix = {}
for i = 1, #inputMatrix[1] do
newMatrix[i] = {}
for v = 1, #inputMatrix do
newMatrix[i][v] = inputMatrix[v][i]
end
end
return newMatrix
end
local transposed = transpose(twoDTransform)
local final = {}
for _,v in pairs(transposed) do
for i,k in pairs(v) do
table.insert(final,k)
end
end
contents = final;
local temp = m;
m = n;
n = temp;
end
function ourMatrix:print()
local str = "";
for row = 1,m do
str = str.."["
for col = 1, n do
local currentIndex = n*(row-1) + col
str = str .. (col ~= n and contents[currentIndex] .. " " or contents[currentIndex].."")
end
str = str.."]"
str=str.."\n"
end
print(str)
end
return ourMatrix
end
| mit |
korialuo/xServer | common/rdsagent.lua | 1 | 1350 | local skynet = require "skynet"
local socket = require "skynet.socket"
local rds_ip, rds_port, listen_ip, listen_port = ...
local listen_socket
local rds_sock_pool = {}
local cli_sock_pool = {}
local function cli_loop(clisock)
local rdssock = rds_sock_pool[clisock]
if rdssock == nil then return end
socket.start(clisock)
local data = socket.read(clisock)
while data do
socket.lwrite(rdssock, data)
data = socket.read(clisock)
end
socket.close(rdssock)
cli_sock_pool[rdssock] = nil
rds_sock_pool[clisock] = nil
end
local function rds_loop(rdssock)
local clisock = cli_sock_pool[rdssock]
if clisock == nil then return end
local data = socket.read(rdssock)
while data do
socket.lwrite(clisock, data)
data = socket.read(rdssock)
end
socket.close(clisock)
cli_sock_pool[rdssock] = nil
rds_sock_pool[clisock] = nil
end
local function accept(clisock, ip)
local rdssock = socket.open(rds_ip, tonumber(rds_port))
rds_sock_pool[clisock] = rdssock
cli_sock_pool[rdssock] = clisock
skynet.fork(cli_loop, clisock)
skynet.fork(rds_loop, rdssock)
end
skynet.start(function()
listen_socket = socket.listen(listen_ip, tonumber(listen_port))
socket.start(listen_socket, accept)
end)
| mit |
teleblue/telele | bot/WaderTGbot.lua | 1 | 15424 | package.path = package.path .. ';.luarocks/share/lua/5.2/?.lua'
..';.luarocks/share/lua/5.2/?/init.lua'
package.cpath = package.cpath .. ';.luarocks/lib/lua/5.2/?.so'
require("./bot/utils")
local f = assert(io.popen('/usr/bin/git describe --tags', 'r'))
VERSION = assert(f:read('*a'))
f:close()
-- This function is called when tg receive a msg
function on_msg_receive (msg)
if not started then
return
end
msg = backward_msg_format(msg)
local receiver = get_receiver(msg)
print(receiver)
--vardump(msg)
--vardump(msg)
msg = pre_process_service_msg(msg)
if msg_valid(msg) then
msg = pre_process_msg(msg)
if msg then
match_plugins(msg)
if redis:get("bot:markread") then
if redis:get("bot:markread") == "on" then
mark_read(receiver, ok_cb, false)
end
end
end
end
end
function ok_cb(extra, success, result)
end
function on_binlog_replay_end()
started = true
postpone (cron_plugins, false, 60*5.0)
-- See plugins/isup.lua as an example for cron
_config = load_config()
-- load plugins
plugins = {}
load_plugins()
end
function msg_valid(msg)
-- Don't process outgoing messages
if msg.out then
print('\27[36mNot valid: msg from us\27[39m')
return false
end
-- Before bot was started
if msg.date < os.time() - 5 then
print('\27[36mNot valid: old msg\27[39m')
return false
end
if msg.unread == 0 then
print('\27[36mNot valid: readed\27[39m')
return false
end
if not msg.to.id then
print('\27[36mNot valid: To id not provided\27[39m')
return false
end
if not msg.from.id then
print('\27[36mNot valid: From id not provided\27[39m')
return false
end
if msg.from.id == our_id then
print('\27[36mNot valid: Msg from our id\27[39m')
return false
end
if msg.to.type == 'encr_chat' then
print('\27[36mNot valid: Encrypted chat\27[39m')
return false
end
if msg.from.id == 777000 then
--send_large_msg(*group id*, msg.text) *login code will be sent to GroupID*
return false
end
return true
end
--
function pre_process_service_msg(msg)
if msg.service then
local action = msg.action or {type=""}
-- Double ! to discriminate of normal actions
msg.text = "!!tgservice " .. action.type
-- wipe the data to allow the bot to read service messages
if msg.out then
msg.out = false
end
if msg.from.id == our_id then
msg.from.id = 0
end
end
return msg
end
-- Apply plugin.pre_process function
function pre_process_msg(msg)
for name,plugin in pairs(plugins) do
if plugin.pre_process and msg then
print('Preprocess', name)
msg = plugin.pre_process(msg)
end
end
return msg
end
-- Go over enabled plugins patterns.
function match_plugins(msg)
for name, plugin in pairs(plugins) do
match_plugin(plugin, name, msg)
end
end
-- Check if plugin is on _config.disabled_plugin_on_chat table
local function is_plugin_disabled_on_chat(plugin_name, receiver)
local disabled_chats = _config.disabled_plugin_on_chat
-- Table exists and chat has disabled plugins
if disabled_chats and disabled_chats[receiver] then
-- Checks if plugin is disabled on this chat
for disabled_plugin,disabled in pairs(disabled_chats[receiver]) do
if disabled_plugin == plugin_name and disabled then
local warning = 'Plugin '..disabled_plugin..' is disabled on this chat'
print(warning)
send_msg(receiver, warning, ok_cb, false)
return true
end
end
end
return false
end
function match_plugin(plugin, plugin_name, msg)
local receiver = get_receiver(msg)
-- Go over patterns. If one matches it's enough.
for k, pattern in pairs(plugin.patterns) do
local matches = match_pattern(pattern, msg.text)
if matches then
print("msg matches: ", pattern)
if is_plugin_disabled_on_chat(plugin_name, receiver) then
return nil
end
-- Function exists
if plugin.run then
-- If plugin is for privileged users only
if not warns_user_not_allowed(plugin, msg) then
local result = plugin.run(msg, matches)
if result then
send_large_msg(receiver, result)
end
end
end
-- One patterns matches
return
end
end
end
-- DEPRECATED, use send_large_msg(destination, text)
function _send_msg(destination, text)
send_large_msg(destination, text)
end
-- Save the content of _config to config.lua
function save_config( )
serialize_to_file(_config, './data/config.lua')
print ('saved config into ./data/config.lua')
end
-- Returns the config from config.lua file.
-- If file doesn't exist, create it.
function load_config( )
local f = io.open('./data/config.lua', "r")
-- If config.lua doesn't exist
if not f then
print ("Created new config file: data/config.lua")
create_config()
else
f:close()
end
local config = loadfile ("./data/config.lua")()
for v,user in pairs(config.sudo_users) do
print("Sudo user: " .. user)
end
return config
end
-- Create a basic config.json file and saves it.
function create_config( )
-- A simple config with basic plugins and ourselves as privileged user
config = {
enabled_plugins = {
"admin",
"onservice",
"inrealm",
"ingroup",
"inpm",
"banhammer",
"stats",
"anti_spam",
"owners",
"arabic_lock",
"set",
"get",
"broadcast",
"invite",
"all",
"me",
"leave_ban",
"supergroup",
"whitelist",
"msg_checks",
"plugins",
"badword",
"bot-lock",
"clash_of_clan",
"cleaner",
"infull",
"instagram",
"linkpv",
"lock-forward",
"photo2sticker",
"sticker2photo",
"text2photo",
"text2sticker",
"server",
"voice",
"wai"
},
sudo_users = {80882965,1050510048,0,0,0,tonumber(our_id)},--Sudo users
moderation = {data = 'data/moderation.json'},
about_text = [[WaderTG v4
An advanced administration bot based on TG-CLI written in Lua
Admins
@persianfa
Our channels
@teleumbrella_team
thankyou for all admins bot WaderTG
]],
help_text_realm = [[
Realm Commands:
!creategroup [Name]
Create a group
!createrealm [Name]
Create a realm
!setname [Name]
Set realm name
!setabout [group|sgroup] [GroupID] [Text]
Set a group's about text
!setrules [GroupID] [Text]
Set a group's rules
!lock [GroupID] [setting]
Lock a group's setting
!unlock [GroupID] [setting]
Unock a group's setting
!settings [group|sgroup] [GroupID]
Set settings for GroupID
!wholist
Get a list of members in group/realm
!who
Get a file of members in group/realm
!type
Get group type
!kill chat [GroupID]
Kick all memebers and delete group
!kill realm [RealmID]
Kick all members and delete realm
!addadmin [id|username]
Promote an admin by id OR username *Sudo only
!removeadmin [id|username]
Demote an admin by id OR username *Sudo only
!list groups
Get a list of all groups
!list realms
Get a list of all realms
!support
Promote user to support
!-support
Demote user from support
!log
Get a logfile of current group or realm
!broadcast [text]
!broadcast Hello !
Send text to all groups
Only sudo users can run this command
!bc [group_id] [text]
!bc 123456789 Hello !
This command will send text to [group_id]
**You can use "#", "!", or "/" to begin all commands
*Only admins and sudo can add bots in group
*Only admins and sudo can use kick,ban,unban,newlink,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only admins and sudo can use res, setowner, commands
channel:@WaderTGTeam
]],
help_text = [[
Commands list :
!kick [username|id]
You can also do it by reply
!ban [ username|id]
You can also do it by reply
!unban [id]
You can also do it by reply
!who
Members list
!modlist
Moderators list
!promote [username]
Promote someone
!demote [username]
Demote someone
!kickme
Will kick user
!about
Group description
!setphoto
Set and locks group photo
!setname [name]
Set group name
!rules
Group rules
!id
return group id or user id
!help
Returns help text
!lock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict]
Lock group settings
*rtl: Kick user if Right To Left Char. is in name*
!unlock [links|flood|spam|Arabic|member|rtl|sticker|contacts|strict]
Unlock group settings
*rtl: Kick user if Right To Left Char. is in name*
!mute [all|audio|gifs|photo|video]
mute group message types
*If "muted" message type: user is kicked if message type is posted
!unmute [all|audio|gifs|photo|video]
Unmute group message types
*If "unmuted" message type: user is not kicked if message type is posted
!set rules <text>
Set <text> as rules
!set about <text>
Set <text> as about
!settings
Returns group settings
!muteslist
Returns mutes for chat
!muteuser [username]
Mute a user in chat
*user is kicked if they talk
*only owners can mute | mods and owners can unmute
!mutelist
Returns list of muted users in chat
!newlink
create/revoke your group link
!link
returns group link
!owner
returns group owner id
!setowner [id]
Will set id as owner
!setflood [value]
Set [value] as flood sensitivity
!stats
Simple message statistics
!save [value] <text>
Save <text> as [value]
!get [value]
Returns text of [value]
!clean [modlist|rules|about]
Will clear [modlist|rules|about] and set it to nil
!res [username]
returns user id
"!res @username"
!log
Returns group logs
!banlist
will return group ban list
**You can use "#", "!", or "/" to begin all commands
*Only owner and mods can add bots in group
*Only moderators and owner can use kick,ban,unban,newlink,link,setphoto,setname,lock,unlock,set rules,set about and settings commands
*Only owner can use res,setowner,promote,demote and log commands
channel:@teleumbrella_team
]],
help_text_super =[[
WaderTG SuperGroup Commands :
=========================
#info
About the SuperGroup info
=========================
#infull
About the you infull
=========================
#admins
SuperGroup admins list
=========================
#setadmin
Set SuperGroup admins
=========================
#owner
Show owner of SuperGroup
=========================
#setowner
Set the SuperGroup owner
=========================
#modlist
Show moderators list
=========================
#bots
List bots in SuperGroup
=========================
#bot[lock,unlock]
Bot[lock,unlock] the SuperGroup
=========================
#who
List all users in SuperGroup
=========================
#block
kick a user from SuperGroup
+Added user to blocked list+
=========================
#ban
Ban user from the SuperGroup
+Only with[id+user]+
=========================
#unban
Unban user from the SuperGroup
+Only with[id+user]+
=========================
#id
SuperGroup ID or user ID
+For user ID:#id @username or reply by: #id+
=========================
#id from
Get ID of user massage is forwarded from
=========================
#kickme
Kick you from SuperGroup
=========================
#promote[@username+id]
Promote a SuperGroup moderator
=========================
#demote[@username+id]
Demote a SuperGroup moderator
=========================
#setname [group name]
Set the chat name
=========================
#setphoto
Set the chat photo
+Then photo and send the+
=========================
#setrules[rules]
Set the chat rules
=========================
#setabout
Set the chat about
=========================
#save [value] <text>
Set extra info for chat
=========================
#get[value]
Retrieves extra info for chat by value
=========================
#newlink
Create group link
=========================
#link
Group the link
=========================
#linkpv
Send SuperGroup link private
=========================
#rules
Chat the rules
=========================
#lock[links+flood+spam+arabic+member+rtl+sticker+contacts+strict+tgservice+forward]
Lock SuperGroup settings
=========================
#unlock[links+flood+spam+arabic+member+rtl+sticker+contacts+strict+tgservice+forward]
Unlock SuperGroup settings
=========================
#mute[all+audio+gifs+photo+video+text+service]
Mute SuperGroup massage types
=========================
#unmute[all+audio+gifs+photo+video+text+service]
Unmute SuperGroup massage types
=========================
#setflood[value]
Set[value] as flood sensitivity
=========================
#settins
SuperGroup settings
=========================
#muteslist
SuperGroup mutes
=========================
#muteuser[@username+id]
Mute a user in SuperGroup
+#muteuser[@username+id]remove mutelist+
=========================
#mutelist
SuperGroup muted user list
=========================
#banlist
SuperGroup ban list
=========================
#clean[rules+about+modlist+mutelist]
Cleaned
=========================
#del
Deletes a massage by reply
=========================
#public[yes+no]
Set SuperGroup visibility in pm #chats or #chatlist commands
=========================
#res[@username]
Returns user name and id by @username
=========================
#log
Returns SuperGroup logs
=========================
#addword[text]
Added the badword
+If the desired word is cleared+
=========================
#badwords
SuperGroup badword list
=========================
#rw[text]
clear[text]from list badword
=========================
#clearbadwords
Cleaned badword list
=========================
#clantag[tag]
Specifications clan a door clsh of clan
=========================
#music[truk name]
Find songs to
=========================
#me
Returns your specifications
=========================
#tophoto
Become stickers to photos
=========================
#tosticker
Turn photos into stikers
=========================
#conv[text]
Text to photos
=========================
#sticker[text]
Text-to-stickers
=========================
#wai
To show office user
=========================
#voice[text]
Text-to-voice
=========================
*Only from markes "!" , "/" , "#" use*
Channel:@teleumbrella_team
]],
}
serialize_to_file(config, './data/config.lua')
print('saved config into ./data/config.lua')
end
function on_our_id (id)
our_id = id
end
function on_user_update (user, what)
--vardump (user)
end
function on_chat_update (chat, what)
--vardump (chat)
end
function on_secret_chat_update (schat, what)
--vardump (schat)
end
function on_get_difference_end ()
end
-- Enable plugins in config.json
function load_plugins()
for k, v in pairs(_config.enabled_plugins) do
print("Loading plugin", v)
local ok, err = pcall(function()
local t = loadfile("plugins/"..v..'.lua')()
plugins[v] = t
end)
if not ok then
print('\27[31mError loading plugin '..v..'\27[39m')
print(tostring(io.popen("lua plugins/"..v..".lua"):read('*all')))
print('\27[31m'..err..'\27[39m')
end
end
end
-- custom add
function load_data(filename)
local f = io.open(filename)
if not f then
return {}
end
local s = f:read('*all')
f:close()
local data = JSON.decode(s)
return data
end
function save_data(filename, data)
local s = JSON.encode(data)
local f = io.open(filename, 'w')
f:write(s)
f:close()
end
-- Call and postpone execution for cron plugins
function cron_plugins()
for name, plugin in pairs(plugins) do
-- Only plugins with cron function
if plugin.cron ~= nil then
plugin.cron()
end
end
-- Called again in 2 mins
postpone (cron_plugins, false, 120)
end
-- Start and load values
our_id = 0
now = os.time()
math.randomseed(now)
started = false
| gpl-2.0 |
telespeed/telespeed | plugins/owners.lua | 68 | 12477 |
local function lock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'yes' then
return 'Group name is already locked'
else
data[tostring(target)]['settings']['lock_name'] = 'yes'
save_data(_config.moderation.data, data)
rename_chat('chat#id'..target, group_name_set, ok_cb, false)
return 'Group name has been locked'
end
end
local function unlock_group_namemod(msg, data, target)
local group_name_set = data[tostring(target)]['settings']['set_name']
local group_name_lock = data[tostring(target)]['settings']['lock_name']
if group_name_lock == 'no' then
return 'Group name is already unlocked'
else
data[tostring(target)]['settings']['lock_name'] = 'no'
save_data(_config.moderation.data, data)
return 'Group name has been unlocked'
end
end
local function lock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'yes' then
return 'Group flood is locked'
else
data[tostring(target)]['settings']['flood'] = 'yes'
save_data(_config.moderation.data, data)
return 'Group flood has been locked'
end
end
local function unlock_group_floodmod(msg, data, target)
local group_flood_lock = data[tostring(target)]['settings']['flood']
if group_flood_lock == 'no' then
return 'Group flood is not locked'
else
data[tostring(target)]['settings']['flood'] = 'no'
save_data(_config.moderation.data, data)
return 'Group flood has been unlocked'
end
end
local function lock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'yes' then
return 'Group members are already locked'
else
data[tostring(target)]['settings']['lock_member'] = 'yes'
save_data(_config.moderation.data, data)
end
return 'Group members has been locked'
end
local function unlock_group_membermod(msg, data, target)
local group_member_lock = data[tostring(target)]['settings']['lock_member']
if group_member_lock == 'no' then
return 'Group members are not locked'
else
data[tostring(target)]['settings']['lock_member'] = 'no'
save_data(_config.moderation.data, data)
return 'Group members has been unlocked'
end
end
local function unlock_group_photomod(msg, data, target)
local group_photo_lock = data[tostring(target)]['settings']['lock_photo']
if group_photo_lock == 'no' then
return 'Group photo is not locked'
else
data[tostring(target)]['settings']['lock_photo'] = 'no'
save_data(_config.moderation.data, data)
return 'Group photo has been unlocked'
end
end
local function show_group_settingsmod(msg, data, target)
local data = load_data(_config.moderation.data)
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings']['flood_msg_max'] then
NUM_MSG_MAX = tonumber(data[tostring(msg.to.id)]['settings']['flood_msg_max'])
print('custom'..NUM_MSG_MAX)
else
NUM_MSG_MAX = 5
end
end
local settings = data[tostring(target)]['settings']
local text = "Group settings:\nLock group name : "..settings.lock_name.."\nLock group photo : "..settings.lock_photo.."\nLock group member : "..settings.lock_member.."\nflood sensitivity : "..NUM_MSG_MAX
return text
end
local function set_rules(target, rules)
local data = load_data(_config.moderation.data)
local data_cat = 'rules'
data[tostring(target)][data_cat] = rules
save_data(_config.moderation.data, data)
return 'Set group rules to:\n'..rules
end
local function set_description(target, about)
local data = load_data(_config.moderation.data)
local data_cat = 'description'
data[tostring(target)][data_cat] = about
save_data(_config.moderation.data, data)
return 'Set group description to:\n'..about
end
local function run(msg, matches)
if msg.to.type ~= 'chat' then
local chat_id = matches[1]
local receiver = get_receiver(msg)
local data = load_data(_config.moderation.data)
if matches[2] == 'ban' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't ban yourself"
end
ban_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] banned user ".. matches[3])
return 'User '..user_id..' banned'
end
if matches[2] == 'unban' then
if tonumber(matches[3]) == tonumber(our_id) then return false end
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't unban yourself"
end
local hash = 'banned:'..matches[1]..':'..user_id
redis:del(hash)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unbanned user ".. matches[3])
return 'User '..user_id..' unbanned'
end
if matches[2] == 'kick' then
local chat_id = matches[1]
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) == tonumber(our_id) then return false end
local user_id = matches[3]
if tonumber(matches[3]) == tonumber(msg.from.id) then
return "You can't kick yourself"
end
kick_user(matches[3], matches[1])
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] kicked user ".. matches[3])
return 'User '..user_id..' kicked'
end
if matches[2] == 'clean' then
if matches[3] == 'modlist' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
for k,v in pairs(data[tostring(matches[1])]['moderators']) do
data[tostring(matches[1])]['moderators'][tostring(k)] = nil
save_data(_config.moderation.data, data)
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned modlist")
end
if matches[3] == 'rules' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'rules'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned rules")
end
if matches[3] == 'about' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local data_cat = 'description'
data[tostring(matches[1])][data_cat] = nil
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] cleaned about")
end
end
if matches[2] == "setflood" then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
if tonumber(matches[3]) < 5 or tonumber(matches[3]) > 20 then
return "Wrong number,range is [5-20]"
end
local flood_max = matches[3]
data[tostring(matches[1])]['settings']['flood_msg_max'] = flood_max
save_data(_config.moderation.data, data)
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] set flood to ["..matches[3].."]")
return 'Group flood has been set to '..matches[3]
end
if matches[2] == 'lock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked name ")
return lock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] locked member ")
return lock_group_membermod(msg, data, target)
end
end
if matches[2] == 'unlock' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local target = matches[1]
if matches[3] == 'name' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked name ")
return unlock_group_namemod(msg, data, target)
end
if matches[3] == 'member' then
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] unlocked member ")
return unlock_group_membermod(msg, data, target)
end
end
if matches[2] == 'new' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local function callback (extra , success, result)
local receiver = 'chat#'..matches[1]
vardump(result)
data[tostring(matches[1])]['settings']['set_link'] = result
save_data(_config.moderation.data, data)
return
end
local receiver = 'chat#'..matches[1]
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] revoked group link ")
export_chat_link(receiver, callback, true)
return "Created a new new link ! \n owner can get it by /owners "..matches[1].." get link"
end
end
if matches[2] == 'get' then
if matches[3] == 'link' then
if not is_owner2(msg.from.id, chat_id) then
return "You are not the owner of this group"
end
local group_link = data[tostring(matches[1])]['settings']['set_link']
if not group_link then
return "Create a link using /newlink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "Group link:\n"..group_link
end
end
if matches[1] == 'changeabout' and matches[2] and is_owner2(msg.from.id, matches[2]) then
local target = matches[2]
local about = matches[3]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group description to ["..matches[3].."]")
return set_description(target, about)
end
if matches[1] == 'changerules' and is_owner2(msg.from.id, matches[2]) then
local rules = matches[3]
local target = matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], name.." ["..msg.from.id.."] has changed group rules to ["..matches[3].."]")
return set_rules(target, rules)
end
if matches[1] == 'changename' and is_owner2(msg.from.id, matches[2]) then
local new_name = string.gsub(matches[3], '_', ' ')
data[tostring(matches[2])]['settings']['set_name'] = new_name
save_data(_config.moderation.data, data)
local group_name_set = data[tostring(matches[2])]['settings']['set_name']
local to_rename = 'chat#id'..matches[2]
local name = user_print_name(msg.from)
savelog(matches[2], "Group {} name changed to [ "..new_name.." ] by "..name.." ["..msg.from.id.."]")
rename_chat(to_rename, group_name_set, ok_cb, false)
end
if matches[1] == 'loggroup' and matches[2] and is_owner2(msg.from.id, matches[2]) then
savelog(matches[2], "------")
send_document("user#id".. msg.from.id,"./groups/"..matches[2].."log.txt", ok_cb, false)
end
end
end
return {
patterns = {
"^[!/]owners (%d+) ([^%s]+) (.*)$",
"^[!/]owners (%d+) ([^%s]+)$",
"^[!/](changeabout) (%d+) (.*)$",
"^[!/](changerules) (%d+) (.*)$",
"^[!/](changename) (%d+) (.*)$",
"^[!/](loggroup) (%d+)$"
},
run = run
}
| gpl-2.0 |
artynet/luci | applications/luci-app-statistics/luasrc/statistics/i18n.lua | 5 | 1894 | -- Copyright 2008 Freifunk Leipzig / Jo-Philipp Wich <jow@openwrt.org>
-- Licensed to the public under the Apache License 2.0.
module("luci.statistics.i18n", package.seeall)
local util = require("luci.util")
local i18n = require("luci.i18n")
Instance = util.class()
function Instance.__init__( self, graph )
self.i18n = i18n
self.graph = graph
end
function Instance._subst( self, str, val )
str = str:gsub( "%%H", self.graph.opts.host or "" )
str = str:gsub( "%%pn", val.plugin or "" )
str = str:gsub( "%%pi", val.pinst or "" )
str = str:gsub( "%%dt", val.dtype or "" )
str = str:gsub( "%%di", val.dinst or "" )
str = str:gsub( "%%ds", val.dsrc or "" )
return str
end
function Instance.title( self, plugin, pinst, dtype, dinst, user_title )
local title = user_title or
"p=%s/pi=%s/dt=%s/di=%s" % {
plugin,
(pinst and #pinst > 0) and pinst or "(nil)",
(dtype and #dtype > 0) and dtype or "(nil)",
(dinst and #dinst > 0) and dinst or "(nil)"
}
return self:_subst( title, {
plugin = plugin,
pinst = pinst,
dtype = dtype,
dinst = dinst
} )
end
function Instance.label( self, plugin, pinst, dtype, dinst, user_label )
local label = user_label or
"dt=%s/di=%s" % {
(dtype and #dtype > 0) and dtype or "(nil)",
(dinst and #dinst > 0) and dinst or "(nil)"
}
return self:_subst( label, {
plugin = plugin,
pinst = pinst,
dtype = dtype,
dinst = dinst
} )
end
function Instance.ds( self, source )
local label = source.title or
"dt=%s/di=%s/ds=%s" % {
(source.type and #source.type > 0) and source.type or "(nil)",
(source.instance and #source.instance > 0) and source.instance or "(nil)",
(source.ds and #source.ds > 0) and source.ds or "(nil)"
}
return self:_subst( label, {
dtype = source.type,
dinst = source.instance,
dsrc = source.ds
} ):gsub(":", "\\:")
end
| apache-2.0 |
akh00/kong | spec/02-integration/05-proxy/05-ssl_spec.lua | 2 | 8586 | local ssl_fixtures = require "spec.fixtures.ssl"
local cache = require "kong.tools.database_cache"
local helpers = require "spec.helpers"
local cjson = require "cjson"
local function get_cert(server_name)
local _, _, stdout = assert(helpers.execute(
string.format("echo 'GET /' | openssl s_client -connect 0.0.0.0:%d -servername %s",
helpers.test_conf.proxy_ssl_port, server_name)
))
return stdout
end
describe("SSL", function()
local admin_client, client, https_client
setup(function()
helpers.dao:truncate_tables()
assert(helpers.dao.apis:insert {
name = "global-cert",
hosts = { "global.com" },
upstream_url = "http://httpbin.org"
})
assert(helpers.dao.apis:insert {
name = "api-1",
hosts = { "example.com", "ssl1.com" },
upstream_url = "http://httpbin.org",
https_only = true,
http_if_terminated = true,
})
assert(helpers.dao.apis:insert {
name = "api-2",
hosts = { "ssl2.com" },
upstream_url = "http://httpbin.org",
https_only = true,
http_if_terminated = false,
})
assert(helpers.dao.apis:insert {
name = "api-3",
hosts = { "ssl3.com" },
upstream_url = "https://localhost:10001",
preserve_host = true,
})
assert(helpers.dao.apis:insert {
name = "api-4",
hosts = { "no-sni.com" },
upstream_url = "https://localhost:10001",
preserve_host = false,
})
assert(helpers.dao.apis:insert {
name = "api-5",
hosts = { "nil-sni.com" },
upstream_url = "https://127.0.0.1:10001",
preserve_host = false,
})
assert(helpers.start_kong {
nginx_conf = "spec/fixtures/custom_nginx.template",
})
admin_client = helpers.admin_client()
client = helpers.proxy_client()
https_client = helpers.proxy_ssl_client()
assert(admin_client:send {
method = "POST",
path = "/certificates",
body = {
cert = ssl_fixtures.cert,
key = ssl_fixtures.key,
snis = "example.com,ssl1.com",
},
headers = { ["Content-Type"] = "application/json" },
})
end)
teardown(function()
helpers.stop_kong()
end)
describe("global SSL", function()
it("fallbacks on the default proxy SSL certificate when SNI is not provided by client", function()
local res = assert(https_client:send {
method = "GET",
path = "/status/200",
headers = {
Host = "global.com"
}
})
assert.res_status(200, res)
end)
end)
describe("handshake", function()
it("sets the default fallback SSL certificate if no SNI match", function()
local cert = get_cert("test.com")
assert.matches("CN=localhost", cert, nil, true)
end)
it("sets the configured SSL certificate if SNI match", function()
local cert = get_cert("ssl1.com")
assert.matches("CN=ssl1.com", cert, nil, true)
cert = get_cert("example.com")
assert.matches("CN=ssl1.com", cert, nil, true)
end)
end)
describe("https_only", function()
it("blocks request without HTTPS", function()
local res = assert(client:send {
method = "GET",
path = "/",
headers = {
["Host"] = "example.com",
}
})
local body = assert.res_status(426, res)
local json = cjson.decode(body)
assert.same({ message = "Please use HTTPS protocol" }, json)
assert.contains("Upgrade", res.headers.connection)
assert.equal("TLS/1.2, HTTP/1.1", res.headers.upgrade)
end)
it("blocks request with HTTPS in x-forwarded-proto but no http_if_already_terminated", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
Host = "ssl2.com",
["x-forwarded-proto"] = "https"
}
})
assert.res_status(426, res)
end)
it("allows requests with x-forwarded-proto and http_if_terminated", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
Host = "example.com",
["x-forwarded-proto"] = "https",
}
})
assert.res_status(200, res)
end)
it("blocks with invalid x-forwarded-proto but http_if_terminated", function()
local res = assert(client:send {
method = "GET",
path = "/status/200",
headers = {
Host = "example.com",
["x-forwarded-proto"] = "httpsa"
}
})
assert.res_status(426, res)
end)
end)
describe("proxy_ssl_name", function()
local https_client_sni
before_each(function()
assert(helpers.kong_exec("restart --conf " .. helpers.test_conf_path ..
" --nginx-conf spec/fixtures/custom_nginx.template"))
https_client_sni = helpers.proxy_ssl_client()
end)
after_each(function()
https_client_sni:close()
end)
describe("properly sets the upstream SNI with preserve_host", function()
it("true", function()
local res = assert(https_client_sni:send {
method = "GET",
path = "/ssl-inspect",
headers = {
Host = "ssl3.com"
}
})
local body = assert.res_status(200, res)
assert.equal("ssl3.com", body)
end)
it("false", function()
local res = assert(https_client_sni:send {
method = "GET",
path = "/ssl-inspect",
headers = {
Host = "no-sni.com"
}
})
local body = assert.res_status(200, res)
assert.equal("localhost", body)
end)
it("false and IP-based upstream_url", function()
local res = assert(https_client_sni:send {
method = "GET",
path = "/ssl-inspect",
headers = {
Host = "nil-sni.com"
}
})
local body = assert.res_status(200, res)
assert.equal("no SNI", body)
end)
end)
end)
end)
describe("SSL certificates and SNIs invalidations", function()
local admin_client
local CACHE_KEY = cache.certificate_key("ssl1.com")
before_each(function()
helpers.dao:truncate_tables()
assert(helpers.dao.apis:insert {
name = "api-1",
hosts = { "ssl1.com" },
upstream_url = "http://httpbin.org",
})
local certificate = assert(helpers.dao.ssl_certificates:insert {
cert = ssl_fixtures.cert,
key = ssl_fixtures.key,
})
assert(helpers.dao.ssl_servers_names:insert {
ssl_certificate_id = certificate.id,
name = "ssl1.com",
})
assert(helpers.start_kong())
admin_client = helpers.admin_client()
end)
after_each(function()
helpers.stop_kong()
end)
it("DELETE", function()
local cert = get_cert("ssl1.com")
assert.matches("CN=ssl1.com", cert, nil, true)
-- check cache is populated
local res = assert(admin_client:send {
method = "GET",
path = "/cache/" .. CACHE_KEY,
})
assert.res_status(200, res)
-- delete the SSL certificate
res = assert(admin_client:send {
method = "DELETE",
path = "/certificates/ssl1.com",
})
assert.res_status(204, res)
-- ensure cache is invalidated
helpers.wait_until(function()
local res = assert(admin_client:send {
method = "GET",
path = "/cache/" .. CACHE_KEY,
})
res:read_body()
return res.status == 404
end, 5)
end)
it("UPDATE", function()
local cert = get_cert("ssl1.com")
assert.matches("CN=ssl1.com", cert, nil, true)
-- check cache is populated
local res = assert(admin_client:send {
method = "GET",
path = "/cache/" .. CACHE_KEY,
})
assert.res_status(200, res)
-- update the SSL certificate
res = assert(admin_client:send {
method = "PATCH",
path = "/certificates/ssl1.com",
body = {
cert = helpers.file.read(helpers.test_conf.ssl_cert),
key = helpers.file.read(helpers.test_conf.ssl_cert_key),
},
headers = { ["Content-Type"] = "application/json" },
})
assert.res_status(200, res)
-- ensure cache is invalidated
helpers.wait_until(function()
local res = assert(admin_client:send {
method = "GET",
path = "/cache/" .. CACHE_KEY,
})
res:read_body()
return res.status == 404
end, 5)
cert = get_cert("ssl1.com")
assert.not_matches("CN=ssl1.com", cert, nil, true)
end)
end)
| apache-2.0 |
gitTerebi/OpenRA | mods/cnc/maps/gdi05b/gdi05b.lua | 19 | 5853 | AllToHuntTrigger =
{
Silo1, Proc1, Silo2, Silo3, Silo4, Afld1, Hand1, Nuke1, Nuke2, Nuke3, Fact1
}
AtkRoute1 = { waypoint4.Location, waypoint5.Location, waypoint6.Location, waypoint7.Location, waypoint8.Location }
AtkRoute2 = { waypoint0.Location, waypoint1.Location, waypoint2.Location, waypoint3.Location }
AutoCreateTeams =
{
{ { ['e1'] = 1, ['e3'] = 3 }, AtkRoute2 },
{ { ['e1'] = 3, ['e3'] = 1 }, AtkRoute2 },
{ { ['e3'] = 4 } , AtkRoute1 },
{ { ['e1'] = 4 } , AtkRoute1 },
{ { ['bggy'] = 1 } , AtkRoute1 },
{ { ['bggy'] = 1 } , AtkRoute2 },
{ { ['ltnk'] = 1 } , AtkRoute1 },
{ { ['ltnk'] = 1 } , AtkRoute2 }
}
RepairThreshold = 0.6
Atk1Delay = DateTime.Seconds(40)
Atk2Delay = DateTime.Seconds(60)
Atk3Delay = DateTime.Seconds(70)
Atk4Delay = DateTime.Seconds(90)
AutoAtkStartDelay = DateTime.Seconds(115)
AutoAtkMinDelay = DateTime.Seconds(45)
AutoAtkMaxDelay = DateTime.Seconds(90)
Atk5CellTriggers =
{
CPos.New(17,55), CPos.New(16,55), CPos.New(15,55), CPos.New(50,54), CPos.New(49,54),
CPos.New(48,54), CPos.New(16,54), CPos.New(15,54), CPos.New(14,54), CPos.New(50,53),
CPos.New(49,53), CPos.New(48,53), CPos.New(50,52), CPos.New(49,52)
}
GdiBase = { GdiNuke1, GdiProc1, GdiWeap1, GdiNuke2, GdiPyle1, GdiSilo1, GdiSilo2, GdiHarv }
GdiUnits = { "e2", "e2", "e2", "e2", "e1", "e1", "e1", "e1", "mtnk", "mtnk", "jeep", "jeep", "apc" }
NodSams = { Sam1, Sam2, Sam3, Sam4 }
AllToHunt = function()
local list = nod.GetGroundAttackers()
Utils.Do(list, function(unit)
unit.Hunt()
end)
end
MoveThenHunt = function(actors, path)
Utils.Do(actors, function(actor)
actor.Patrol(path, false)
IdleHunt(actor)
end)
end
AutoCreateTeam = function()
local team = Utils.Random(AutoCreateTeams)
for type, count in pairs(team[1]) do
MoveThenHunt(Utils.Take(count, nod.GetActorsByType(type)), team[2])
end
Trigger.AfterDelay(Utils.RandomInteger(AutoAtkMinDelay, AutoAtkMaxDelay), AutoCreateTeam)
end
DiscoverGdiBase = function(actor, discoverer)
if baseDiscovered or not discoverer == gdi then
return
end
Utils.Do(GdiBase, function(actor)
actor.Owner = gdi
end)
GdiHarv.FindResources()
baseDiscovered = true
gdiObjective3 = gdi.AddPrimaryObjective("Eliminate all Nod forces in the area.")
gdi.MarkCompletedObjective(gdiObjective1)
end
Atk1TriggerFunction = function()
MoveThenHunt(Utils.Take(2, nod.GetActorsByType('e1')), AtkRoute1)
MoveThenHunt(Utils.Take(3, nod.GetActorsByType('e3')), AtkRoute1)
end
Atk2TriggerFunction = function()
MoveThenHunt(Utils.Take(3, nod.GetActorsByType('e1')), AtkRoute2)
MoveThenHunt(Utils.Take(3, nod.GetActorsByType('e3')), AtkRoute2)
end
Atk3TriggerFunction = function()
MoveThenHunt(Utils.Take(1, nod.GetActorsByType('bggy')), AtkRoute1)
end
Atk4TriggerFunction = function()
MoveThenHunt(Utils.Take(1, nod.GetActorsByType('bggy')), AtkRoute2)
end
Atk5TriggerFunction = function()
MoveThenHunt(Utils.Take(1, nod.GetActorsByType('ltnk')), AtkRoute2)
end
StartProduction = function(type)
if Hand1.IsInWorld and Hand1.Owner == nod then
Hand1.Build(type)
Trigger.AfterDelay(DateTime.Seconds(30), function() StartProduction(type) end)
end
end
InsertGdiUnits = function()
Media.PlaySpeechNotification(gdi, "Reinforce")
Reinforcements.Reinforce(gdi, GdiUnits, { UnitsEntry.Location, UnitsRally.Location }, 15)
end
IdleHunt = function(unit)
if not unit.IsDead then
Trigger.OnIdle(unit, unit.Hunt)
end
end
WorldLoaded = function()
gdi = Player.GetPlayer("GDI")
gdiBase = Player.GetPlayer("AbandonedBase")
nod = Player.GetPlayer("Nod")
Trigger.OnObjectiveAdded(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "New " .. string.lower(p.GetObjectiveType(id)) .. " objective")
end)
Trigger.OnObjectiveCompleted(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective completed")
end)
Trigger.OnObjectiveFailed(gdi, function(p, id)
Media.DisplayMessage(p.GetObjectiveDescription(id), "Objective failed")
end)
Trigger.OnPlayerWon(gdi, function()
Media.PlaySpeechNotification(gdi, "Win")
end)
Trigger.OnPlayerLost(gdi, function()
Media.PlaySpeechNotification(gdi, "Lose")
end)
Utils.Do(Map.NamedActors, function(actor)
if actor.Owner == nod and actor.HasProperty("StartBuildingRepairs") then
Trigger.OnDamaged(actor, function(building)
if building.Owner == nod and building.Health < RepairThreshold * building.MaxHealth then
building.StartBuildingRepairs()
end
end)
end
end)
gdiObjective1 = gdi.AddPrimaryObjective("Find the GDI base.")
gdiObjective2 = gdi.AddSecondaryObjective("Destroy all SAM sites to receive air support.")
nodObjective = nod.AddPrimaryObjective("Destroy all GDI troops.")
Trigger.AfterDelay(Atk1Delay, Atk1TriggerFunction)
Trigger.AfterDelay(Atk2Delay, Atk2TriggerFunction)
Trigger.AfterDelay(Atk3Delay, Atk3TriggerFunction)
Trigger.AfterDelay(Atk4Delay, Atk4TriggerFunction)
Trigger.OnEnteredFootprint(Atk5CellTriggers, function(a, id)
if a.Owner == gdi then
Atk5TriggerFunction()
Trigger.RemoveFootprintTrigger(id)
end
end)
Trigger.AfterDelay(AutoAtkStartDelay, AutoCreateTeam)
Trigger.OnAllRemovedFromWorld(AllToHuntTrigger, AllToHunt)
Trigger.AfterDelay(DateTime.Seconds(40), function() StartProduction({ "e1" }) end)
Trigger.OnPlayerDiscovered(gdiBase, DiscoverGdiBase)
Trigger.OnAllKilled(NodSams, function()
gdi.MarkCompletedObjective(gdiObjective2)
Actor.Create("airstrike.proxy", true, { Owner = gdi })
end)
Camera.Position = UnitsRally.CenterPosition
InsertGdiUnits()
end
Tick = function()
if gdi.HasNoRequiredUnits() then
if DateTime.GameTime > 2 then
nod.MarkCompletedObjective(nodObjective)
end
end
if baseDiscovered and nod.HasNoRequiredUnits() then
gdi.MarkCompletedObjective(gdiObjective3)
end
end
| gpl-3.0 |
gitTerebi/OpenRA | mods/ra/maps/allies-05a/AI.lua | 34 | 6702 |
IdlingUnits = { }
AttackGroupSize = 6
Barracks = { Barracks2, Barracks3 }
Rallypoints = { VehicleRallypoint1, VehicleRallypoint2, VehicleRallypoint3, VehicleRallypoint4, VehicleRallypoint5 }
WaterLZs = { WaterLZ1, WaterLZ2 }
Airfields = { Airfield1, Airfield2 }
Yaks = { }
SovietInfantryTypes = { "e1", "e1", "e2", "e4" }
SovietVehicleTypes = { "3tnk", "3tnk", "3tnk", "v2rl", "v2rl", "apc" }
SovietAircraftType = { "yak" }
HoldProduction = true
BuildVehicles = true
TrainInfantry = true
IdleHunt = function(unit) if not unit.IsDead then Trigger.OnIdle(unit, unit.Hunt) end end
SetupAttackGroup = function()
local units = { }
for i = 0, AttackGroupSize, 1 do
if #IdlingUnits == 0 then
return units
end
local number = Utils.RandomInteger(1, #IdlingUnits)
if IdlingUnits[number] and not IdlingUnits[number].IsDead then
units[i] = IdlingUnits[number]
table.remove(IdlingUnits, number)
end
end
return units
end
SendAttack = function()
if Attacking then
return
end
Attacking = true
HoldProduction = true
local units = { }
if SendWaterTransports and Utils.RandomInteger(0,2) == 1 then
units = WaterAttack()
Utils.Do(units, function(unit)
Trigger.OnAddedToWorld(unit, function()
Trigger.OnIdle(unit, unit.Hunt)
end)
end)
Trigger.AfterDelay(DateTime.Seconds(20), function()
Attacking = false
HoldProduction = false
end)
else
units = SetupAttackGroup()
Utils.Do(units, function(unit)
IdleHunt(unit)
end)
Trigger.AfterDelay(DateTime.Minutes(1), function() Attacking = false end)
Trigger.AfterDelay(DateTime.Minutes(2), function() HoldProduction = false end)
end
end
WaterAttack = function()
local types = { }
for i = 1, 5, 1 do
types[i] = Utils.Random(SovietInfantryTypes)
end
return Reinforcements.ReinforceWithTransport(ussr, InsertionTransport, types, { WaterTransportSpawn.Location, Utils.Random(WaterLZs).Location }, { WaterTransportSpawn.Location })[2]
end
ProtectHarvester = function(unit)
Trigger.OnDamaged(unit, function(self, attacker)
-- TODO: Send the Harvester to the service depo
if AttackOnGoing then
return
end
AttackOnGoing = true
local Guards = SetupAttackGroup()
Utils.Do(Guards, function(unit)
if not self.IsDead then
unit.AttackMove(self.Location)
end
IdleHunt(unit)
end)
Trigger.OnAllRemovedFromWorld(Guards, function() AttackOnGoing = false end)
end)
Trigger.OnKilled(unit, function() HarvesterKilled = true end)
end
InitAIUnits = function()
IdlingUnits = Map.ActorsInBox(MainBaseTopLeft.CenterPosition, Map.BottomRight, function(self) return self.Owner == ussr and self.HasProperty("Hunt") end)
local buildings = Map.ActorsInBox(MainBaseTopLeft.CenterPosition, Map.BottomRight, function(self) return self.Owner == ussr and self.HasProperty("StartBuildingRepairs") end)
Utils.Do(buildings, function(actor)
Trigger.OnDamaged(actor, function(building)
if building.Owner == ussr and building.Health < building.MaxHealth * 3/4 then
building.StartBuildingRepairs()
end
end)
end)
end
InitAIEconomy = function()
ussr.Cash = 6000
if not Harvester.IsDead then
Harvester.FindResources()
ProtectHarvester(Harvester)
end
end
InitProductionBuildings = function()
if not Warfactory2.IsDead then
Warfactory2.IsPrimaryBuilding = true
Trigger.OnKilled(Warfactory2, function() BuildVehicles = false end)
else
BuildVehicles = false
end
if not Barracks2.IsDead then
Barracks2.IsPrimaryBuilding = true
Trigger.OnKilled(Barracks2, function()
if not Barracks3.IsDead then
Barracks3.IsPrimaryBuilding = true
else
TrainInfantry = false
end
end)
elseif not Barracks3.IsDead then
Barracks3.IsPrimaryBuilding = true
else
TrainInfantry = false
end
if not Barracks3.IsDead then
Trigger.OnKilled(Barracks3, function()
if Barracks2.IsDead then
TrainInfantry = false
end
end)
end
if Map.Difficulty ~= "Easy" then
if not Airfield1.IsDead then
Trigger.OnKilled(Airfield1, function()
if Airfield2.IsDead then
AirAttacks = false
else
Airfield2.IsPrimaryBuilding = true
Trigger.OnKilled(Airfield2, function() AirAttacks = false end)
end
end)
Airfield1.IsPrimaryBuilding = true
AirAttacks = true
elseif not Airfield2.IsDead then
Trigger.OnKilled(Airfield2, function() AirAttacks = false end)
Airfield2.IsPrimaryBuilding = true
AirAttacks = true
end
end
end
ProduceInfantry = function()
if not TrainInfantry then
return
end
if HoldProduction then
Trigger.AfterDelay(DateTime.Minutes(1), ProduceInfantry)
return
end
local delay = Utils.RandomInteger(DateTime.Seconds(3), DateTime.Seconds(9))
local toBuild = { Utils.Random(SovietInfantryTypes) }
ussr.Build(toBuild, function(unit)
IdlingUnits[#IdlingUnits + 1] = unit[1]
Trigger.AfterDelay(delay, ProduceInfantry)
if #IdlingUnits >= (AttackGroupSize * 2.5) then
SendAttack()
end
end)
end
ProduceVehicles = function()
if not BuildVehicles then
return
end
if HoldProduction then
Trigger.AfterDelay(DateTime.Minutes(1), ProduceVehicles)
return
end
local delay = Utils.RandomInteger(DateTime.Seconds(5), DateTime.Seconds(9))
if HarvesterKilled then
HarvesterKilled = false
ussr.Build({ "harv" }, function(harv)
harv[1].FindResources()
ProtectHarvester(harv[1])
Trigger.AfterDelay(delay, ProduceVehicles)
end)
return
end
Warfactory2.RallyPoint = Utils.Random(Rallypoints).Location
local toBuild = { Utils.Random(SovietVehicleTypes) }
ussr.Build(toBuild, function(unit)
IdlingUnits[#IdlingUnits + 1] = unit[1]
Trigger.AfterDelay(delay, ProduceVehicles)
if #IdlingUnits >= (AttackGroupSize * 2.5) then
SendAttack()
end
end)
end
ProduceAircraft = function()
if not AirAttacks then
return
end
ussr.Build(SovietAircraftType, function(units)
Yaks[#Yaks + 1] = units[1]
if #Yaks == 2 then
Trigger.OnKilled(units[1], ProduceAircraft)
else
Trigger.AfterDelay(DateTime.Minutes(1), ProduceAircraft)
end
local target = nil
Trigger.OnIdle(units[1], function()
if not target or target.IsDead or (not target.IsInWorld) then
local enemies = Map.ActorsInBox(Map.TopLeft, Map.BottomRight, function(self) return self.Owner == greece and self.HasProperty("Health") end)
if #enemies > 0 then
target = Utils.Random(enemies)
units[1].Attack(target)
end
else
units[1].Attack(target)
end
end)
end)
end
ActivateAI = function()
InitAIUnits()
InitAIEconomy()
InitProductionBuildings()
Trigger.AfterDelay(DateTime.Minutes(5), function()
ProduceInfantry()
ProduceVehicles()
if AirAttacks then
Trigger.AfterDelay(DateTime.Minutes(3), ProduceAircraft)
end
end)
end
| gpl-3.0 |
pchote/OpenRA | mods/cnc/maps/gdi06/gdi06.lua | 2 | 4952 | --[[
Copyright 2007-2021 The OpenRA Developers (see AUTHORS)
This file is part of OpenRA, which is free software. It is made
available to you 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. For more
information, see COPYING.
]]
IslandSamSites = { SAM01, SAM02 }
NodBase = { PowerPlant1, PowerPlant2, PowerPlant3, PowerPlant4, PowerPlant5, Refinery, HandOfNod, Silo1, Silo2, Silo3, Silo4, ConYard, CommCenter }
FlameSquad = { FlameGuy1, FlameGuy2, FlameGuy3 }
FlameSquadRoute = { waypoint4.Location, waypoint12.Location, waypoint4.Location, waypoint6.Location }
FootPatrol1Squad = { MiniGunner1, MiniGunner2, RocketSoldier1 }
FootPatrol1Route =
{
waypoint4.Location,
waypoint12.Location,
waypoint13.Location,
waypoint3.Location,
waypoint2.Location,
waypoint7.Location,
waypoint6.Location
}
FootPatrol2Squad = { MiniGunner3, MiniGunner4 }
FootPatrol2Route =
{
waypoint14.Location,
waypoint16.Location
}
FootPatrol3Squad = { MiniGunner5, MiniGunner6 }
FootPatrol3Route =
{
waypoint15.Location,
waypoint17.Location
}
FootPatrol4Route =
{
waypoint4.Location,
waypoint5.Location
}
FootPatrol5Squad = { RocketSoldier2, RocketSoldier3, RocketSoldier4 }
FootPatrol5Route =
{
waypoint4.Location,
waypoint12.Location,
waypoint13.Location,
waypoint8.Location,
waypoint9.Location,
}
Buggy1Route =
{
waypoint6.Location,
waypoint7.Location,
waypoint2.Location,
waypoint8.Location,
waypoint9.Location,
waypoint8.Location,
waypoint2.Location,
waypoint7.Location
}
Buggy2Route =
{
waypoint6.Location,
waypoint10.Location,
waypoint11.Location,
waypoint10.Location
}
HuntTriggerActivator = { SAM03, SAM04, SAM05, SAM06, LightTank1, LightTank2, LightTank3, Buggy1, Buggy2, Turret1, Turret2 }
AttackCellTriggerActivator = { CPos.New(57,26), CPos.New(56,26), CPos.New(57,25), CPos.New(56,25), CPos.New(57,24), CPos.New(56,24), CPos.New(57,23), CPos.New(56,23), CPos.New(57,22), CPos.New(56,22), CPos.New(57,21), CPos.New(56,21) }
AttackUnits = { LightTank2, LightTank3 }
KillCounter = 0
WorldLoaded = function()
GDI = Player.GetPlayer("GDI")
Nod = Player.GetPlayer("Nod")
InitObjectives(GDI)
if Difficulty == "easy" then
CommandoType = "rmbo.easy"
KillCounterHuntThreshold = 30
elseif Difficulty == "hard" then
CommandoType = "rmbo.hard"
KillCounterHuntThreshold = 15
else
CommandoType = "rmbo"
KillCounterHuntThreshold = 20
end
DestroyObjective = GDI.AddObjective("Destroy the Nod ********.")
Trigger.OnKilled(Airfield, function()
GDI.MarkCompletedObjective(DestroyObjective)
end)
Utils.Do(NodBase, function(structure)
Trigger.OnKilled(structure, function()
GDI.MarkCompletedObjective(DestroyObjective)
end)
end)
Trigger.OnAllKilled(IslandSamSites, function()
TransportFlare = Actor.Create('flare', true, { Owner = GDI, Location = Flare.Location })
Reinforcements.ReinforceWithTransport(GDI, 'tran', nil, { lstStart.Location, TransportRally.Location })
end)
Trigger.OnKilled(CivFleeTrigger, function()
if not Civilian.IsDead then
Civilian.Move(CivHideOut.Location)
end
end)
Trigger.OnKilled(AttackTrigger2, function()
Utils.Do(FlameSquad, function(unit)
if not unit.IsDead then
unit.Patrol(FlameSquadRoute, false)
end
end)
end)
Trigger.OnEnteredFootprint(AttackCellTriggerActivator, function(a, id)
if a.Owner == GDI then
Utils.Do(AttackUnits, function(unit)
if not unit.IsDead then
unit.AttackMove(waypoint10.Location)
end
end)
Trigger.RemoveFootprintTrigger(id)
end
end)
Utils.Do(HuntTriggerActivator, function(unit)
Trigger.OnDamaged(unit, function()
Utils.Do(Nod.GetGroundAttackers(), IdleHunt)
end)
end)
Trigger.AfterDelay(5, function()
Utils.Do(Nod.GetGroundAttackers(), function(unit)
Trigger.OnKilled(unit, function()
KillCounter = KillCounter + 1
if KillCounter >= KillCounterHuntThreshold then
Utils.Do(Nod.GetGroundAttackers(), IdleHunt)
end
end)
end)
end)
Utils.Do(FootPatrol1Squad, function(unit)
unit.Patrol(FootPatrol1Route, true)
end)
Utils.Do(FootPatrol2Squad, function(unit)
unit.Patrol(FootPatrol2Route, true, 50)
end)
Utils.Do(FootPatrol3Squad, function(unit)
unit.Patrol(FootPatrol3Route, true, 50)
end)
Utils.Do(FootPatrol5Squad, function(unit)
unit.Patrol(FootPatrol5Route, true, 50)
end)
AttackTrigger2.Patrol(FootPatrol4Route, true, 25)
LightTank1.Move(waypoint6.Location)
Buggy1.Patrol(Buggy1Route, true, 25)
Buggy2.Patrol(Buggy2Route, true, 25)
Camera.Position = UnitsRally.CenterPosition
Media.PlaySpeechNotification(GDI, "Reinforce")
ReinforceWithLandingCraft(GDI, { CommandoType }, lstStart.Location, lstEnd.Location, UnitsRally.Location)
end
Tick = function()
if DateTime.GameTime > DateTime.Seconds(5) and GDI.HasNoRequiredUnits() then
GDI.MarkFailedObjective(DestroyObjective)
end
end
| gpl-3.0 |
theonlywild/erfaan | plugins/meme.lua | 637 | 5791 | local helpers = require "OAuth.helpers"
local _file_memes = './data/memes.lua'
local _cache = {}
local function post_petition(url, arguments)
local response_body = {}
local request_constructor = {
url = url,
method = "POST",
sink = ltn12.sink.table(response_body),
headers = {},
redirect = false
}
local source = arguments
if type(arguments) == "table" then
local source = helpers.url_encode_arguments(arguments)
end
request_constructor.headers["Content-Type"] = "application/x-www-form-urlencoded"
request_constructor.headers["Content-Length"] = tostring(#source)
request_constructor.source = ltn12.source.string(source)
local ok, response_code, response_headers, response_status_line = http.request(request_constructor)
if not ok then
return nil
end
response_body = json:decode(table.concat(response_body))
return response_body
end
local function upload_memes(memes)
local base = "http://hastebin.com/"
local pet = post_petition(base .. "documents", memes)
if pet == nil then
return '', ''
end
local key = pet.key
return base .. key, base .. 'raw/' .. key
end
local function analyze_meme_list()
local function get_m(res, n)
local r = "<option.*>(.*)</option>.*"
local start = string.find(res, "<option.*>", n)
if start == nil then
return nil, nil
end
local final = string.find(res, "</option>", n) + #"</option>"
local sub = string.sub(res, start, final)
local f = string.match(sub, r)
return f, final
end
local res, code = http.request('http://apimeme.com/')
local r = "<option.*>(.*)</option>.*"
local n = 0
local f, n = get_m(res, n)
local ult = {}
while f ~= nil do
print(f)
table.insert(ult, f)
f, n = get_m(res, n)
end
return ult
end
local function get_memes()
local memes = analyze_meme_list()
return {
last_time = os.time(),
memes = memes
}
end
local function load_data()
local data = load_from_file(_file_memes)
if not next(data) or data.memes == {} or os.time() - data.last_time > 86400 then
data = get_memes()
-- Upload only if changed?
link, rawlink = upload_memes(table.concat(data.memes, '\n'))
data.link = link
data.rawlink = rawlink
serialize_to_file(data, _file_memes)
end
return data
end
local function match_n_word(list1, list2)
local n = 0
for k,v in pairs(list1) do
for k2, v2 in pairs(list2) do
if v2:find(v) then
n = n + 1
end
end
end
return n
end
local function match_meme(name)
local _memes = load_data()
local name = name:lower():split(' ')
local max = 0
local id = nil
for k,v in pairs(_memes.memes) do
local n = match_n_word(name, v:lower():split(' '))
if n > 0 and n > max then
max = n
id = v
end
end
return id
end
local function generate_meme(id, textup, textdown)
local base = "http://apimeme.com/meme"
local arguments = {
meme=id,
top=textup,
bottom=textdown
}
return base .. "?" .. helpers.url_encode_arguments(arguments)
end
local function get_all_memes_names()
local _memes = load_data()
local text = 'Last time: ' .. _memes.last_time .. '\n-----------\n'
for k, v in pairs(_memes.memes) do
text = text .. '- ' .. v .. '\n'
end
text = text .. '--------------\n' .. 'You can see the images here: http://apimeme.com/'
return text
end
local function callback_send(cb_extra, success, data)
if success == 0 then
send_msg(cb_extra.receiver, "Something wrong happened, probably that meme had been removed from server: " .. cb_extra.url, ok_cb, false)
end
end
local function run(msg, matches)
local receiver = get_receiver(msg)
if matches[1] == 'list' then
local _memes = load_data()
return 'I have ' .. #_memes.memes .. ' meme names.\nCheck this link to see all :)\n' .. _memes.link
elseif matches[1] == 'listall' then
if not is_sudo(msg) then
return "You can't list this way, use \"!meme list\""
else
return get_all_memes_names()
end
elseif matches[1] == "search" then
local meme_id = match_meme(matches[2])
if meme_id == nil then
return "I can't match that search with any meme."
end
return "With that search your meme is " .. meme_id
end
local searchterm = string.gsub(matches[1]:lower(), ' ', '')
local meme_id = _cache[searchterm] or match_meme(matches[1])
if not meme_id then
return 'I don\'t understand the meme name "' .. matches[1] .. '"'
end
_cache[searchterm] = meme_id
print("Generating meme: " .. meme_id .. " with texts " .. matches[2] .. ' and ' .. matches[3])
local url_gen = generate_meme(meme_id, matches[2], matches[3])
send_photo_from_url(receiver, url_gen, callback_send, {receiver=receiver, url=url_gen})
return nil
end
return {
description = "Generate a meme image with up and bottom texts.",
usage = {
"!meme search (name): Return the name of the meme that match.",
"!meme list: Return the link where you can see the memes.",
"!meme listall: Return the list of all memes. Only admin can call it.",
'!meme [name] - [text_up] - [text_down]: Generate a meme with the picture that match with that name with the texts provided.',
'!meme [name] "[text_up]" "[text_down]": Generate a meme with the picture that match with that name with the texts provided.',
},
patterns = {
"^!meme (search) (.+)$",
'^!meme (list)$',
'^!meme (listall)$',
'^!meme (.+) "(.*)" "(.*)"$',
'^!meme "(.+)" "(.*)" "(.*)"$',
"^!meme (.+) %- (.*) %- (.*)$"
},
run = run
}
| gpl-2.0 |
artynet/luci | applications/luci-app-mwan3/luasrc/model/cbi/mwan/interface.lua | 7 | 7256 | -- Copyright 2014 Aedan Renner <chipdankly@gmail.com
-- Copyright 2018 Florian Eckert <fe@dev.tdt.de>
-- Licensed to the public under the GNU General Public License v2.
local dsp = require "luci.dispatcher"
local uci = require "uci"
local m, mwan_interface, enabled, track_method, reliability, interval
local down, up, metric
function interfaceWarnings(overview, count, iface_max)
local warnings = ""
if count <= iface_max then
warnings = string.format("<strong>%s</strong><br />",
translatef("There are currently %d of %d supported interfaces configured", count, iface_max)
)
else
warnings = string.format("<strong>%s</strong><br />",
translatef("WARNING: %d interfaces are configured exceeding the maximum of %d!", count, iface_max)
)
end
for i, k in pairs(overview) do
if overview[i]["network"] == false then
warnings = warnings .. string.format("<strong>%s</strong><br />",
translatef("WARNING: Interface %s are not found in /etc/config/network", i)
)
end
if overview[i]["default_route"] == false then
warnings = warnings .. string.format("<strong>%s</strong><br />",
translatef("WARNING: Interface %s has no default route in the main routing table", i)
)
end
if overview[i]["reliability"] == false then
warnings = warnings .. string.format("<strong>%s</strong><br />",
translatef("WARNING: Interface %s has a higher reliability " ..
"requirement than tracking hosts (%d)", i, overview[i]["tracking"])
)
end
if overview[i]["duplicate_metric"] == true then
warnings = warnings .. string.format("<strong>%s</strong><br />",
translatef("WARNING: Interface %s has a duplicate metric %s configured", i, overview[i]["metric"])
)
end
end
return warnings
end
function configCheck()
local overview = {}
local count = 0
local duplicate_metric = {}
uci.cursor():foreach("mwan3", "interface",
function (section)
local uci = uci.cursor(nil, "/var/state")
local iface = section[".name"]
overview[iface] = {}
count = count + 1
local network = uci:get("network", iface)
overview[iface]["network"] = false
if network ~= nil then
overview[iface]["network"] = true
local device = uci:get("network", iface, "ifname")
if device ~= nil then
overview[iface]["device"] = device
end
local metric = uci:get("network", iface, "metric")
if metric ~= nil then
overview[iface]["metric"] = metric
overview[iface]["duplicate_metric"] = false
for _, m in ipairs(duplicate_metric) do
if m == metric then
overview[iface]["duplicate_metric"] = true
end
end
table.insert(duplicate_metric, metric)
end
local dump = require("luci.util").ubus("network.interface.%s" % iface, "status", {})
overview[iface]["default_route"] = false
if dump and dump.route then
local _, route
for _, route in ipairs(dump.route) do
if dump.route[_].target == "0.0.0.0" then
overview[iface]["default_route"] = true
end
end
end
end
local trackingNumber = uci:get("mwan3", iface, "track_ip")
overview[iface]["tracking"] = 0
if trackingNumber and #trackingNumber > 0 then
overview[iface]["tracking"] = #trackingNumber
overview[iface]["reliability"] = false
local reliabilityNumber = tonumber(uci:get("mwan3", iface, "reliability"))
if reliabilityNumber and reliabilityNumber <= #trackingNumber then
overview[iface]["reliability"] = true
end
end
end
)
-- calculate iface_max usage from firewall mmx_mask
function bit(p)
return 2 ^ (p - 1)
end
function hasbit(x, p)
return x % (p + p) >= p
end
function setbit(x, p)
return hasbit(x, p) and x or x + p
end
local uci = require("uci").cursor(nil, "/var/state")
local mmx_mask = uci:get("mwan3", "globals", "mmx_mask") or "0x3F00"
local number = tonumber(mmx_mask, 16)
local bits = 0
local iface_max = 0
for i=1,16 do
if hasbit(number, bit(i)) then
bits = bits + 1
iface_max = setbit( iface_max, bit(bits))
end
end
-- subtract blackhole, unreachable and default table from iface_max
iface_max = iface_max - 3
return overview, count, iface_max
end
m = Map("mwan3", translate("MWAN - Interfaces"),
interfaceWarnings(configCheck()))
mwan_interface = m:section(TypedSection, "interface", nil,
translate("MWAN supports up to 252 physical and/or logical interfaces<br />" ..
"MWAN requires that all interfaces have a unique metric configured in /etc/config/network<br />" ..
"Names must match the interface name found in /etc/config/network<br />" ..
"Names may contain characters A-Z, a-z, 0-9, _ and no spaces<br />" ..
"Interfaces may not share the same name as configured members, policies or rules"))
mwan_interface.addremove = true
mwan_interface.dynamic = false
mwan_interface.sectionhead = translate("Interface")
mwan_interface.sortable = false
mwan_interface.template = "cbi/tblsection"
mwan_interface.extedit = dsp.build_url("admin", "network", "mwan", "interface", "%s")
function mwan_interface.create(self, section)
TypedSection.create(self, section)
m.uci:save("mwan3")
luci.http.redirect(dsp.build_url("admin", "network", "mwan", "interface", section))
end
enabled = mwan_interface:option(DummyValue, "enabled", translate("Enabled"))
enabled.rawhtml = true
function enabled.cfgvalue(self, s)
if self.map:get(s, "enabled") == "1" then
return translate("Yes")
else
return translate("No")
end
end
track_method = mwan_interface:option(DummyValue, "track_method", translate("Tracking method"))
track_method.rawhtml = true
function track_method.cfgvalue(self, s)
local tracked = self.map:get(s, "track_ip")
if tracked then
return self.map:get(s, "track_method") or "ping"
else
return "—"
end
end
reliability = mwan_interface:option(DummyValue, "reliability", translate("Tracking reliability"))
reliability.rawhtml = true
function reliability.cfgvalue(self, s)
local tracked = self.map:get(s, "track_ip")
if tracked then
return self.map:get(s, "reliability") or "1"
else
return "—"
end
end
interval = mwan_interface:option(DummyValue, "interval", translate("Ping interval"))
interval.rawhtml = true
function interval.cfgvalue(self, s)
local tracked = self.map:get(s, "track_ip")
if tracked then
local intervalValue = self.map:get(s, "interval")
if intervalValue then
return intervalValue .. "s"
else
return "5s"
end
else
return "—"
end
end
down = mwan_interface:option(DummyValue, "down", translate("Interface down"))
down.rawhtml = true
function down.cfgvalue(self, s)
local tracked = self.map:get(s, "track_ip")
if tracked then
return self.map:get(s, "down") or "3"
else
return "—"
end
end
up = mwan_interface:option(DummyValue, "up", translate("Interface up"))
up.rawhtml = true
function up.cfgvalue(self, s)
local tracked = self.map:get(s, "track_ip")
if tracked then
return self.map:get(s, "up") or "3"
else
return "—"
end
end
metric = mwan_interface:option(DummyValue, "metric", translate("Metric"))
metric.rawhtml = true
function metric.cfgvalue(self, s)
local uci = uci.cursor(nil, "/var/state")
local metric = uci:get("network", s, "metric")
if metric then
return metric
else
return "—"
end
end
return m
| apache-2.0 |
TGlandTeam/AntiSpamCreatorBot | plugins/setver.lua | 1 | 2078 | do
local function run(msg, matches)
hashfun = 'bot:help:fun'
hashmods = 'bot:help:mods'
hashadmin = 'bot:help:admin'
hashver = 'bot:ver'
hash = 'bot:help'
if matches[1] == 'helpfun' then
if not is_sudo(msg) then return end
redis:set(hashfun,'waiting:'..msg.from.id)
return 'Send Your Text Now 📌'
else
if redis:get(hashfun) == 'waiting:'..msg.from.id then
redis:set(hashfun,msg.text)
return 'Done!'
end
end
if matches[1] == 'sethelpmods' then
if not is_sudo(msg) then return end
redis:set(hashmods,'waiting:'..msg.from.id)
return 'Send Your Text Now 📌'
else
if redis:get(hashmods) == 'waiting:'..msg.from.id then
redis:set(hashmods,msg.text)
return 'Done!'
end
end
if matches[1] == 'sethelpadmin' then
if not is_sudo(msg) then return end
redis:set(hashadmin,'waiting:'..msg.from.id)
return 'Send Your Text Now 📌'
else
if redis:get(hashadmin) == 'waiting:'..msg.from.id then
redis:set(hashadmin,msg.text)
return 'Done!'
end
end
if matches[1] == 'sethelp' then
if not is_sudo(msg) then return end
redis:set(hash,'waiting:'..msg.from.id)
return 'Send Your Text Now 📌'
else
if redis:get(hash) == 'waiting:'..msg.from.id then
redis:set(hash,msg.text)
return 'Done!'
end
end
if matches[1] == 'setver' then
if not is_sudo(msg) then return end
redis:set(hashver,'waiting:'..msg.from.id)
return 'Send Your Text Now 📌'
else
if redis:get(hashver) == 'waiting:'..msg.from.id then
redis:set(hashver,msg.text)
return 'انجام شد!'
end
end
if matches[1] == 'helpfun' then
if not is_momod(msg) then return end
return redis:get(hashfun)
end
if matches[1] == 'help' then
if not is_momod(msg) then return end
return redis:get(hash)
end
if matches[1] == 'helpmods' then
if not is_momod(msg) then return end
return redis:get(hashmods)
end
if matches[1] == 'helpadmin' then
if not is_admin(msg) then return end
return redis:get(hashadmin)
end
if matches[1] == 'version' then
return redis:get(hashver)
end
end
return {
patterns = {
'[/!#](setver)$',
'[/!#](version)$',
'(.*)',
},
run = run,
pre_process = pre_process
}
end
| gpl-2.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.