repo_name stringlengths 6 78 | path stringlengths 4 206 | copies stringclasses 281
values | size stringlengths 4 7 | content stringlengths 625 1.05M | license stringclasses 15
values |
|---|---|---|---|---|---|
Grocel/wire-extras | lua/weapons/gmod_tool/stools/wire_field_device.lua | 3 | 6244 | TOOL.Category = "Wire Extras/Physics"
TOOL.Name = "Field Generator"
TOOL.Command = nil
TOOL.ConfigName = ""
TOOL.ClientConVar[ "type" ] = ""
TOOL.ClientConVar[ "workonplayers" ] = "1"
TOOL.ClientConVar[ "ignoreself" ] = "1"
TOOL.ClientConVar[ "arc" ] = "360"
TOOL.Tab = "Wire"
if ( CLIENT ) then
language.Add( "Tool.wire_field_device.name", "Field Generator Tool (Wire)" )
language.Add( "Tool.wire_field_device.desc", "Spawns a Field Generator." )
language.Add( "Tool.wire_field_device.0", "Primary: Create Field Generator" )
language.Add( "sboxlimit_wire_field_device", "You've hit Field Generator limit!" )
language.Add( "Undone_wire_field_device", "Undone Wire Field Generator" )
language.Add( "hint_field_type" , "You Must Select Field Type" )
language.Add( "hint_field_type" , "You Must Select Field Type" )
end
if (SERVER) then
CreateConVar('sbox_maxwire_field_device', 5)
end
TOOL.ClientConVar["Model"] = "models/jaanus/wiretool/wiretool_grabber_forcer.mdl"
TOOL.FirstSelected = nil
cleanup.Register( "wire_field_device" )
function TOOL:LeftClick( trace )
if (!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() && trace.Entity:GetClass() == "gmod_wire_field_device" && trace.Entity:GetTable().pl == ply ) then
return true
end
if ( !self:GetSWEP():CheckLimit( "wire_field_device" ) ) then return false end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local lType=self:GetClientInfo( "type" );
if string.len( lType ) < 2 then ply:SendHint( "field_type" , 0 ) return false end
local wire_field_device_obj = Makewire_field_device( ply, trace.HitPos, Ang , self:GetClientInfo("Model") , lType , self:GetClientNumber("ignoreself") , self:GetClientNumber("workonplayers"), self:GetClientNumber("arc") )
local min = wire_field_device_obj:OBBMins()
wire_field_device_obj:SetPos( trace.HitPos - trace.HitNormal * min.z )
local const = WireLib.Weld(wire_field_device_obj, trace.Entity, trace.PhysicsBone, true)
undo.Create("wire_field_device")
undo.AddEntity( wire_field_device_obj )
undo.AddEntity( const )
undo.SetPlayer( ply )
undo.Finish()
ply:AddCleanup( "wire_field_device", wire_field_device_obj )
ply:AddCleanup( "wire_field_device", const )
return true
end
function TOOL:RightClick( trace )
return false
end
function TOOL:Reload( trace )
return false
end
if (SERVER) then
function Makewire_field_device( pl, Pos, Ang, Model , Type , ignoreself , workonplayers , arc )
if ( !pl:CheckLimit( "wire_field_device" ) ) then return false end
local wire_field_device_obj = ents.Create( "gmod_wire_field_device" )
if (!wire_field_device_obj:IsValid()) then return false end
wire_field_device_obj:Setworkonplayers(workonplayers);
wire_field_device_obj:Setignoreself(ignoreself);
wire_field_device_obj:SetType(Type);
wire_field_device_obj:Setarc(arc);
wire_field_device_obj:SetAngles( Ang )
wire_field_device_obj:SetPos( Pos )
wire_field_device_obj:SetModel( Model )
wire_field_device_obj:Spawn()
wire_field_device_obj:SetPlayer( pl )
wire_field_device_obj.pl = pl
wire_field_device_obj:SetCreator(pl)
pl:AddCount( "wire_field_device", wire_field_device_obj )
return wire_field_device_obj
end
duplicator.RegisterEntityClass("gmod_wire_field_device", Makewire_field_device, "Pos", "Ang", "Model", "FieldType" , "ignoreself" , "workonplayers" , "arc" , "Vel", "aVel", "frozen")
end
function TOOL:UpdateGhostgmod_wire_field_device( ent, player )
if ( !ent || !ent:IsValid() ) then return end
local tr = util.GetPlayerTrace( player, player:GetAimVector() )
local trace = util.TraceLine( tr )
if (!trace.Hit || trace.Entity:IsPlayer() || trace.Entity:GetClass() == "gmod_wire_field_device" ) then
ent:SetNoDraw( true )
return
end
local Ang = trace.HitNormal:Angle()
Ang.pitch = Ang.pitch + 90
local min = ent:OBBMins()
ent:SetPos( trace.HitPos - trace.HitNormal * min.z )
ent:SetAngles( Ang )
ent:SetNoDraw( false )
end
function TOOL:Think()
if (!self.GhostEntity || !self.GhostEntity:IsValid() || self.GhostEntity:GetModel() != self.Model ) then
self:MakeGhostEntity( self:GetClientInfo("Model"), Vector(0,0,0), Angle(0,0,0) )
end
self:UpdateGhostgmod_wire_field_device( self.GhostEntity, self:GetOwner() )
end
function TOOL.BuildCPanel(panel)
panel:AddControl("Header", { Text = "#Tool.wire_field_device.name", Description = "#Tool.wire_field_device.desc" })
panel:AddControl("ComboBox", {
Label = "#Type",
Options = {
Gravity = {
wire_field_device_type="Gravity"
},
Attraction = {
wire_field_device_type="Pull"
},
Repulsion = {
wire_field_device_type="Push"
},
Stasis = {
wire_field_device_type="Hold"
},
Wind = {
wire_field_device_type="Wind"
},
Vortex = {
wire_field_device_type="Vortex"
},
Flame = {
wire_field_device_type="Flame"
},
Pressure = {
wire_field_device_type="Crush"
},
Electromagnetic = {
wire_field_device_type="EMP"
},
Radiation = {
wire_field_device_type="Death"
},
Recovery = {
wire_field_device_type="Heal"
},
Acceleration = {
wire_field_device_type="Speed"
},
Battery = {
wire_field_device_type="Battery"
},
Phase = {
wire_field_device_type="NoCollide"
}
}
} )
panel:AddControl( "Checkbox", { Label = "Ignore Self & Connected Props:", Description = "Makes the Generator, and its contraption, Immune it its own effects.", Command = "wire_field_device_ignoreself" } )
panel:AddControl( "Checkbox", { Label = "Affect players:", Description = "Removes Player Immunity to fields.", Command = "wire_field_device_workonplayers" } )
panel:AddControl( "Slider" , {
Type = "Float",
Min = "0.1",
Max = "360.0",
Label = "Arc Size:" ,
Description = "The Arc( in Degrees ) taht the field is emitted, ( 0 or 360 for circle )" ,
Command ="wire_field_device_arc"
} );
end
| apache-2.0 |
TerminalShell/zombiesurvival | entities/weapons/weapon_zs_spotlamp/init.lua | 1 | 1720 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function SWEP:Deploy()
gamemode.Call("WeaponDeployed", self.Owner, self)
self:SpawnGhost()
return true
end
function SWEP:OnRemove()
self:RemoveGhost()
end
function SWEP:Holster()
self:RemoveGhost()
return true
end
function SWEP:SpawnGhost()
local owner = self.Owner
if owner and owner:IsValid() then
owner:GiveStatus("ghost_spotlamp")
end
end
function SWEP:RemoveGhost()
local owner = self.Owner
if owner and owner:IsValid() then
owner:RemoveStatus("ghost_spotlamp", false, true)
end
end
function SWEP:PrimaryAttack()
if not self:CanPrimaryAttack() then return end
local owner = self.Owner
local status = owner.status_ghost_spotlamp
if not (status and status:IsValid()) then return end
status:RecalculateValidity()
if not status:GetValidPlacement() then return end
local pos, ang = status:RecalculateValidity()
if not pos or not ang then return end
self:SetNextPrimaryAttack(CurTime() + self.Primary.Delay)
local ent = ents.Create("prop_spotlamp")
if ent:IsValid() then
ent:SetPos(pos)
ent:SetAngles(ang)
ent:Spawn()
ent:SetObjectOwner(owner)
ent:EmitSound("npc/dog/dog_servo12.wav")
ent:GhostAllPlayersInMe(5)
self:TakePrimaryAmmo(1)
local stored = owner.m_PackedSpotLamps and owner.m_PackedSpotLamps[1]
if stored then
ent:SetObjectHealth(stored.Health)
table.remove(owner.m_PackedSpotLamps, 1)
end
if self:GetPrimaryAmmoCount() <= 0 then
owner:StripWeapon(self:GetClass())
end
end
end
function SWEP:Think()
local count = self:GetPrimaryAmmoCount()
if count ~= self:GetReplicatedAmmo() then
self:SetReplicatedAmmo(count)
self.Owner:ResetSpeed()
end
end
| gpl-3.0 |
RyMarq/Zero-K | LuaRules/Gadgets/start_waterlevel.lua | 6 | 1485 | if not gadgetHandler:IsSyncedCode() then return end
function gadget:GetInfo() return {
name = "Water level modoption",
layer = 1, -- after terraform whence GG.Terraform_RaiseWater comes
enabled = true,
} end
local DRY_WATERLEVEL = -50
local FLOODED_AREA = 0.5 -- (0; 1]
local FLOOD_OFFSET = -72 -- often the median of map height will be some large flat area. Setting waterlevel very close to any flat plane will result in major clipping ugliness. This ofset is intended to make most of the map covered by a decent depth of sea.
function gadget:Initialize() -- GamePreload causes issues with widgets.
if Spring.GetGameFrame () > 1 then
return
end
local waterlevel = Spring.GetModOptions().waterlevel or 0
local preset = Spring.GetModOptions().waterpreset or "manual"
if preset == "dry" then
local lowest, highest = Spring.GetGroundExtremes ()
waterlevel = math.min (0, lowest + DRY_WATERLEVEL)
elseif preset == "flooded" then
local heights = {}
local heightsCount = 0
local spGetGroundHeight = Spring.GetGroundHeight
for i = 0, Game.mapSizeX-1, Game.squareSize do
for j = 0, Game.mapSizeZ-1, Game.squareSize do
heightsCount = heightsCount + 1
heights [heightsCount] = spGetGroundHeight (i, j)
end
end
table.sort (heights)
waterlevel = heights [math.ceil (heightsCount * FLOODED_AREA)] - FLOOD_OFFSET
end
Spring.SetGameRulesParam("waterlevel", waterlevel)
if waterlevel ~= 0 then
GG.Terraform_RaiseWater(waterlevel)
end
end
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/WorldKey/WorldKeyManager.lua | 1 | 7937 | --[[
Title: WorldKeyManager
Author(s): yangguiyi
Date: 2021/4/28
Desc:
Use Lib:
-------------------------------------------------------
local WorldKeyManager = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/WorldKey/WorldKeyManager.lua")
--]]
local KeepworkServiceProject = NPL.load("(gl)Mod/WorldShare/service/KeepworkService/Project.lua")
local WorldKeyManager = NPL.export();
function WorldKeyManager.GenerateActivationCodes(count, private_key, projectId, filename, folder_path, succee_cb)
count = count or 5
projectId = tonumber(projectId)
private_key = WorldKeyManager.GetCurrentSearchKey(private_key)
local key_list = ""
for i = 1, count do
local key = WorldKeyManager.EncodeKeys(private_key, projectId, mathlib.bit.band(math.random(10, 9999) + os.time(), 0xff))
key_list = key_list .. key .. "\n"
end
local filename = filename .. ".txt"
filename = commonlib.Encoding.Utf8ToDefault(filename)
local file_path = string.format("%s/%s", folder_path, filename)
ParaIO.CreateDirectory(file_path)
local file = ParaIO.open(file_path, "w");
if(file) then
file:write(key_list, #key_list);
file:close();
end
-- local path = string.gsub(folder_path, "/", "\\")
if succee_cb then
succee_cb(string.gsub(file_path, "/", "\\"))
end
end
function WorldKeyManager.EncodeKeys(nKey1, nKey2, nKey3)
nKey2 = mathlib.bit.band(0xffffff, nKey2)
nKey3 = mathlib.bit.band(0xff, nKey3)
-- print("cccccccccccc", mathlib.bit.band(0xffffff, 100), mathlib.bit.band(math.random(1, 1000), 0xff))
local part1 = WorldKeyManager.SYMETRIC_ENCODE_32_BY_8(nKey1, nKey3)
local part2 = mathlib.bit.lshift(WorldKeyManager.SYMETRIC_ENCODE_32_BY_8(nKey2, nKey3), 8)
part2 = part2 + nKey3
local num_a = mathlib.bit.rshift(part1, 16)
local num_b = mathlib.bit.band(part1, 0xffff)
local num_c = mathlib.bit.rshift(part2, 16)
local num_d = mathlib.bit.band(part2, 0xffff)
return string.format("%sx-%sx-%sx-%sx", num_a, num_b, num_c, num_d)
end
function WorldKeyManager.DecodeKeys(sActivationCode)
local parts = commonlib.split(sActivationCode,"x-");
if #parts ~= 4 then
return "", ""
end
if string.find(sActivationCode, "xx") then
return "", ""
end
local nKey3 = mathlib.bit.band(0xff, parts[4])
local nKey1 = mathlib.bit.lshift(parts[1], 16)+parts[2];
nKey1 = WorldKeyManager.SYMETRIC_ENCODE_32_BY_8(nKey1, nKey3);
local nKey2 = mathlib.bit.lshift(parts[3], 8)+mathlib.bit.rshift(parts[4], 8);
nKey2 = mathlib.bit.band(WorldKeyManager.SYMETRIC_ENCODE_32_BY_8(nKey2, nKey3), 0x00ffffff);
return nKey1, nKey2
end
function WorldKeyManager.SYMETRIC_ENCODE_32_BY_8(a, k)
local encode_a = mathlib.bit.band(mathlib.bit.bxor(a, (mathlib.bit.lshift(k, 24))), 0xff000000)
local encode_b = mathlib.bit.band(mathlib.bit.bxor(a, (mathlib.bit.lshift(k, 16))), 0x00ff0000)
local encode_c = mathlib.bit.band(mathlib.bit.bxor(a, (mathlib.bit.lshift(k, 8))), 0x0000ff00)
local encode_d = mathlib.bit.band(mathlib.bit.bxor(a, k), 0x000000ff)
-- local encode_b = mathlib.bit.band((a^(mathlib.bit.lshift(k, 16))), 0x00ff0000)
-- local encode_c = mathlib.bit.band((a^(mathlib.bit.lshift(k, 8)))), 0x0000ff00)
-- local encode_d = mathlib.bit.band((a^(mathlib.bit.lshift(k)))), 0x000000ff)
return encode_a + encode_b + encode_c + encode_d
end
function WorldKeyManager.CharToBase64(byte)
local n = 0
if byte >= string.byte('0') and byte <= string.byte('9') then
n=byte - string.byte('0')
elseif byte>= string.byte('a') and byte <= string.byte('z') then
n=10+byte - string.byte('a')
elseif byte >= string.byte('A') and byte <= string.byte('Z') then
n=36+byte - string.byte('A')
elseif byte == string.byte('.') then
n=63;
end
return n
end
function WorldKeyManager.Base64ToChar(num)
local char = ""
if num < 10 then
char = string.char(string.byte('0') + num)
elseif num < 36 then
char = string.char(string.byte('a') + num)
elseif num < 62 then
char = string.char(string.byte('A') + num)
else
char = '.'
end
return char
end
function WorldKeyManager.isValidActivationCode(code, world_data)
local params = world_data or {}
local name = params.username or ""
local project_id = params.id
local extra = params.extra or {}
local world_encodekey_data = extra.world_encodekey_data or {}
local invalid_key_list = world_encodekey_data.invalid_key_list or {}
if invalid_key_list[code] then
return false
end
local part1, part2 = WorldKeyManager.DecodeKeys(code)
if part2 == project_id and part1 == WorldKeyManager.GetCurrentSearchKey(name) then
local decode_world_list = GameLogic.GetPlayerController():LoadRemoteData("WorldKeyManager.DecodeWorldList", {});
decode_world_list[project_id] = 1
GameLogic.GetPlayerController():SaveRemoteData("WorldKeyManager.DecodeWorldList", decode_world_list)
return true
end
return false
end
function WorldKeyManager.GetCurrentSearchKey(serach_key)
local key_num = 0
for index = 1, #serach_key do
key_num = mathlib.bit.lshift(key_num, 6) + WorldKeyManager.CharToBase64(string.byte(serach_key, index))
end
return key_num
end
function WorldKeyManager.DecodeSearchKey(key_num)
local str = ""
while (key_num > 0) do
local rshift = mathlib.bit.rshift(key_num, 6)
local byte = key_num - rshift
-- print("bbbb", key_num , rshift)
local char = WorldKeyManager.Base64ToChar(byte)
str = char .. str
key_num = rshift
end
end
function WorldKeyManager.HasActivate(project_id)
if GameLogic.IsVip() then
return true
end
local DecodeWorldList = GameLogic.GetPlayerController():LoadRemoteData("WorldKeyManager.DecodeWorldList", {});
if DecodeWorldList[project_id] then
return true
end
end
function WorldKeyManager.OnclickNpc(project_id)
if project_id == nil then
return
end
local KeepworkServiceProject = NPL.load("(gl)Mod/WorldShare/service/KeepworkService/Project.lua")
KeepworkServiceProject:GetProject(project_id, function(data, err)
if type(data) == 'table' then
if data.username == System.User.username then
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/WorldKey/WorldKeyEncodePage.lua").Show(project_id);
else
local CommandManager = commonlib.gettable("MyCompany.Aries.Game.CommandManager")
CommandManager:RunCommand(string.format('/loadworld -force -s %s', project_id))
end
end
end)
end
function WorldKeyManager.AddInvalidKey(key, world_data, succee_cb)
if not WorldKeyManager.isValidActivationCode(key, world_data) then
GameLogic.AddBBS(nil, L"无效激活码,不需要注销", 3000, "255 0 0")
return
end
local params = world_data or {}
local extra = params.extra or {}
params.extra = extra
local world_encodekey_data = params.extra.world_encodekey_data or {}
extra.world_encodekey_data = world_encodekey_data
if world_encodekey_data.invalid_key_list == nil then
world_encodekey_data.invalid_key_list = {}
end
if world_encodekey_data.invalid_key_list[key] then
GameLogic.AddBBS(nil, L"无效激活码,不需要注销", 3000, "255 0 0")
return
end
world_encodekey_data.invalid_key_list[key] = 1
local projectId = world_data.id
if projectId == nil then
return
end
KeepworkServiceProject:UpdateProject(projectId, params, function(data, err)
if err == 200 then
GameLogic.AddBBS(nil, L"注销成功", 3000, "0 255 0")
if succee_cb then
succee_cb()
end
end
end)
end | gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/zones/temple-of-creation/npcs.lua | 3 | 4212 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
load("/data/general/npcs/aquatic_critter.lua", rarity(5))
load("/data/general/npcs/aquatic_demon.lua", rarity(7))
load("/data/general/npcs/naga.lua", rarity(0))
local Talents = require("engine.interface.ActorTalents")
newEntity{ define_as = "SLASUL",
allow_infinite_dungeon = true,
type = "humanoid", subtype = "naga", unique = true,
name = "Slasul",
faction="temple-of-creation",
display = "@", color=colors.VIOLET,
resolvers.nice_tile{image="invis.png", add_mos = {{image="npc/humanoid_naga_slasul.png", display_h=2, display_y=-1}}},
desc = [[This towering naga exudes power, and radiates a certain charismatic charm as well. His masculine face stares at you with great intensity, and you struggle to meet his gaze. His torso is bare apart from an exquisite pearl set directly in his chest, and in his muscular arms he holds ready a heavy mace and shield. You sense there is more to him also, as if the very power of the ocean were concentrated in this great creature, and that the wrath of it may come flooding out at any moment.]],
killer_message = "and perverted into a monstrous aberration as a warning to the surface",
global_speed_base = 1.7,
level_range = {30, nil}, exp_worth = 4,
max_life = 350, life_rating = 19, fixed_rating = true,
max_stamina = 85,
stats = { str=25, dex=10, cun=40, mag=50, con=50 },
rank = 4,
size_category = 3,
can_breath={water=1},
infravision = 10,
move_others=true,
instakill_immune = 1,
teleport_immune = 1,
confusion_immune= 1,
combat_spellresist = 25,
combat_mentalresist = 25,
combat_physresist = 30,
resists = { [DamageType.COLD] = 60, [DamageType.ACID] = 20, },
body = { INVEN = 10, MAINHAND=1, OFFHAND=1, BODY=1, LITE=1 },
resolvers.equip{
{type="weapon", subtype="mace", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true},
{type="armor", subtype="shield", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true},
{type="armor", subtype="heavy", force_drop=true, tome_drops="boss", forbid_power_source={antimagic=true}, autoreq=true},
{type="jewelry", subtype="lite", defined="ELDRITCH_PEARL", autoreq=true},
},
resolvers.drops{chance=100, nb=1, {defined="SLASUL_NOTE"} },
resolvers.drops{chance=100, nb=5, {tome_drops="boss"} },
resolvers.talents{
[Talents.T_WEAPON_COMBAT]={base=3, every=10, max=5},
[Talents.T_WEAPONS_MASTERY]={base=3, every=10, max=5},
[Talents.T_SHIELD_EXPERTISE]={base=3, every=7, max=6},
[Talents.T_SHIELD_PUMMEL]={base=2, every=7, max=6},
[Talents.T_RIPOSTE]=5,
[Talents.T_BLINDING_SPEED]={base=3, every=7, max=6},
[Talents.T_PERFECT_STRIKE]=5,
[Talents.T_SPIT_POISON]={base=5, every=5, max=9},
[Talents.T_HEAL]={base=6, every=7, max=7},
[Talents.T_UTTERCOLD]=5,
[Talents.T_ICE_SHARDS]=5,
[Talents.T_FREEZE]=3,
[Talents.T_TIDAL_WAVE]=5,
[Talents.T_ICE_STORM]=5,
[Talents.T_WATER_BOLT]=5,
[Talents.T_MIND_DISRUPTION]=5,
},
resolvers.sustains_at_birth(),
autolevel = "warrior",
ai = "tactical", ai_state = { talent_in=1, ai_move="move_astar", },
ai_tactic = resolvers.tactic"melee",
resolvers.inscriptions(4, "infusion"),
resolvers.inscriptions(1, {"manasurge rune"}),
on_die = function(self, who)
game.player:resolveSource():setQuestStatus("temple-of-creation", engine.Quest.COMPLETED, "kill-slasul")
game.player:resolveSource():hasQuest("temple-of-creation"):portal_back()
end,
can_talk = "slasul",
}
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Commands/CommandManager.lua | 1 | 21723 | --[[
Title: Command Manager
Author(s): LiXizhi
Date: 2013/2/9
Desc: slash command manager
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandManager.lua");
local CommandManager = commonlib.gettable("MyCompany.Aries.Game.CommandManager");
CommandManager:Init()
CommandManager:RunCommand(cmd_name, cmd_text)
-------------------------------------------------------
]]
NPL.load("(gl)script/ide/STL.lua");
NPL.load("(gl)script/apps/Aries/SlashCommand/SlashCommand.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CmdParser.lua");
local CmdParser = commonlib.gettable("MyCompany.Aries.Game.CmdParser");
local SlashCommand = commonlib.gettable("MyCompany.Aries.SlashCommand.SlashCommand");
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local EnterGamePage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.EnterGamePage");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local TaskManager = commonlib.gettable("MyCompany.Aries.Game.TaskManager")
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local block = commonlib.gettable("MyCompany.Aries.Game.block")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local BroadcastHelper = commonlib.gettable("CommonCtrl.BroadcastHelper");
local Commands = commonlib.gettable("MyCompany.Aries.Game.Commands");
local CommandManager = commonlib.gettable("MyCompany.Aries.Game.CommandManager");
function CommandManager:TryInit()
if(not self.is_registered) then
self:Init()
end
end
-- call this when command
function CommandManager:Init(bRefresh)
if(not self.isInited) then
self.isInited = true;
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandBlocks.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandShapes.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandGlobals.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandWorlds.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandScreenRecorder.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandInstall.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandPlayer.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandMovie.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandRules.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandProgram.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandItem.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandTime.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandTemplate.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandCamera.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandAudio.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandActivate.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandBlockType.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandTexture.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandSet.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandOpen.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandBlockTransform.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandEntity.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandPublishSourceScript.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandActor.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandRecord.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandConvert.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandNetwork.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandEffect.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandSelect.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandCreate.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandCCS.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandShow.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandDropFile.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandMenu.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandSystem.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandDump.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandSky.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandTeleport.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandWalk.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandSay.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandDoc.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandEvent.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandSpawn.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandProperty.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandLanguage.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandMount.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandQuest.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandWiki.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandDiff.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandTerrain.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandParalife.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandMake430App.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Commands/CommandEnvironment.lua");
-- TODO: add more system command here
end
GameLogic.GetFilters():apply_filters("register_command", Commands, SlashCommand.GetSingleton());
self:Register(SlashCommand.GetSingleton(), bRefresh);
end
-- run one text command
-- @param cmd_name: this can be command name or full command text that begin with "/" or nothing.
function CommandManager:RunCommand(cmd_name, cmd_text, ...)
self:TryInit()
if(not cmd_text or cmd_text == "") then
cmd_name, cmd_text = cmd_name:match("^/*(%w+)%s*(.*)$");
end
local cmd_class = SlashCommand.GetSingleton():GetSlashCommand(cmd_name);
if(cmd_class) then
if(GameLogic.isRemote and not cmd_class:IsLocal()) then
GameLogic.GetPlayer():AddToSendQueue(GameLogic.Packets.PacketClientCommand:new():Init(format("/%s %s", cmd_name, cmd_text)));
elseif(not GameLogic.isRemote or cmd_class:IsLocal()) then
cmd_text = self:RunInlineCommand(cmd_text, ...);
return SlashCommand.GetSingleton():RunCommand(cmd_name, cmd_text, ...);
end
end
end
function CommandManager:GetCommandName(cmd_text)
return cmd_text:match("^%s*/*(%w+)");
end
-- run text with may contain one or several commands.
-- it will treat ; or \r\n as a new line of command
-- @param ...: ususally fromEntity,
function CommandManager:RunText(text, ...)
if(text) then
for cmd in text:gmatch("(/*[^\r\n;]+)") do
self:RunCommand(cmd, nil, ...);
end
end
end
-- like linux bash shell, text inside $() is regarded as inline command, whose returned value is used in current command.
-- brackets can be nested
-- @return the new cmd_text after inline command is executed.
function CommandManager:RunInlineCommand(cmd_text, ...)
while(cmd_text) do
local from, to;
from, to, end_bracket = cmd_text:find("%$%(/?[^%$%(%)]+([%)%(])");
while(to and end_bracket == "(") do
local from1;
from1, to, end_bracket = cmd_text:find("%)[^%(%)]*([%)%(])", to+1);
end
if(end_bracket == ")") then
local inline_cmd = cmd_text:sub(from+2, to - 1);
if(inline_cmd) then
local result = self:RunCommand(inline_cmd, nil, ...) or "";
cmd_text = cmd_text:sub(1, from - 1)..tostring(result)..cmd_text:sub(to+1, -1);
end
else
break;
end
end
return cmd_text;
end
-- run commands
-- @return p1, p2: if p1 is false, then p2 is the label name where to goto. If p2 is nil, it means end of all lines.
-- if p1 is not false, such as nil or any other value, the next command will be invoked normally.
function CommandManager:Run(cmd, ... )
return self:RunWithVariables(nil, cmd, ...);
end
-- @return cmd_class, cmd_name, cmd_text;
function CommandManager:GetCmdByString(cmd)
if(cmd) then
local cmd_name, cmd_text = cmd:match("^/*(%w+)%s*(.*)$");
if(cmd_name) then
local cmd_class = SlashCommand.GetSingleton():GetSlashCommand(cmd_name);
if(cmd_class) then
return cmd_class, cmd_name, cmd_text;
end
end
end
end
-- @param variables: nil or a must be an object containning Compile() function.
-- @return p1, p2: if p1 is false, then p2 is the label name where to goto. If p2 is nil, it means end of all lines.
-- if p1 is not false, such as nil or any other value, the next command will be invoked normally.
function CommandManager:RunWithVariables(variables, cmd, ...)
local cmd_class, cmd_name, cmd_text = self:GetCmdByString(cmd);
if(cmd_class) then
cmd_text = self:RunInlineCommand(cmd_text, ...);
if(variables) then
cmd_class:SetCompiler(variables);
local p1, p2 = cmd_class:Run(cmd_name, cmd_text, ...);
cmd_class:SetCompiler(nil);
return p1, p2;
else
return cmd_class:Run(cmd_name, cmd_text, ...);
end
end
end
-- run command from console for the current player
-- @param player: fromEntity, if nil, this is current player. last trigger entity is also set to this player.
-- after command is run, it will set back to previous value.
function CommandManager:RunFromConsole(cmd, player)
local cmd_class, cmd_name, cmd_text = self:GetCmdByString(cmd);
GameLogic.GetFilters():apply_filters("user_event_stat", "cmd", "execute:"..tostring(cmd_name), 2, nil);
if(cmd_class) then
if(GameLogic.isRemote and not cmd_class:IsLocal()) then
GameLogic.GetPlayer():AddToSendQueue(GameLogic.Packets.PacketClientCommand:new():Init(cmd));
elseif(not GameLogic.isRemote or cmd_class:IsLocal()) then
local variables;
if(not player) then
if(EntityManager.GetPlayer) then
player = EntityManager.GetPlayer();
end
end
if(player) then
variables = player:GetVariables();
end
if(cmd_class:CheckGameMode(GameLogic.GameMode:GetMode())) then
local last_trigger_entity = false;
if(player and EntityManager.SetLastTriggerEntity) then
last_trigger_entity = EntityManager.GetLastTriggerEntity();
EntityManager.SetLastTriggerEntity(player);
end
local res, res2 = self:RunWithVariables(variables, cmd, player);
if(last_trigger_entity~=false) then
EntityManager.SetLastTriggerEntity(last_trigger_entity);
end
return res, res2;
else
BroadcastHelper.PushLabel({id="cmderror", label = format("当前模式下不可执行命令%s", cmd_name), max_duration=3000, color = "255 0 0", scaling=1.1, bold=true, shadow=true,});
return;
end
end
end
end
-- call this function to register the slash command and init
function CommandManager:Register(slash_command, bRefresh)
if(self.is_registered and not bRefresh) then
return;
end
self.is_registered = true;
self.slash_command = slash_command;
-- register all predefined system commands
for name, cmd in pairs(Commands) do
slash_command:RegisterSlashCommand(cmd);
end
end
-- get command list
-- @param line_reg_exp: default to "([%-]*)%s*(/?[^\r\n]+)", change this if one uses different line endings.
function CommandManager:GetCmdList(cmds_str, line_reg_exp)
if(cmds_str) then
line_reg_exp = line_reg_exp or "([%-]*)%s*(/?[^\r\n]+)";
local out = {};
for comment, cmd in string.gmatch(cmds_str, line_reg_exp) do
if(comment == "") then
out[#out+1] = cmd
--else
--out[#out+1] = "";
end
end
return out;
end
end
-- @param cmd_list: array of command text. if nil, the current command list is used.
-- @param func_name: function name,
-- function [name]
-- -- cmd here will be called.
-- functionend
-- return true, function_return_value: if function is found and called. otherwise return nil;
function CommandManager:CallFunction(cmd_list, func_name, variables, fromEntity)
cmd_list = cmd_list or self:GetCurrentCmdList();
if(cmd_list and func_name) then
local line_index = 1;
local func_name_reg = "^/?function "..func_name;
local line_count = #cmd_list;
local insideFunc;
local fromLine, toLine;
while line_index <= line_count do
local cmd = cmd_list[line_index];
if(cmd~="") then
if(not insideFunc) then
if(cmd:match(func_name_reg)) then
insideFunc = true;
fromLine = line_index + 1;
end
else
if(cmd:match("^/?functionend")) then
toLine = line_index - 1;
break;
end
end
end
line_index = line_index + 1;
end
if(insideFunc) then
-- execute function between
local res = self:RunCmdSegment(cmd_list, fromLine, toLine, variables, fromEntity);
return true, res;
end
end
end
-- get the current command list if any that is being executed;
function CommandManager:GetCurrentCmdList()
return self.cmd_list;
end
-- run command from fromLine to toLine
-- @param cmd_list: array of cmd strings
-- @param fromLine: default to 1
-- @param toLine: default to #cmd_list
function CommandManager:RunCmdSegment(cmd_list, fromLine, toLine, variables, fromEntity)
local last_result, goto_label;
local line_index = fromLine or 1;
local line_count = toLine or #cmd_list;
self.cmd_list = cmd_list;
local macros;
while line_index <= line_count do
local cmd = cmd_list[line_index];
if(cmd~="" and cmd:match("^[%w_%.]+%(.*%)$")) then
-- macro command
macros = macros or {}
macros[#macros+1] = cmd;
line_index = line_index + 1;
elseif(cmd~="") then
-- ordinary command
last_result, goto_label = self:RunWithVariables(variables, cmd, fromEntity);
if( last_result == false) then
if(goto_label) then
if(type(goto_label) == "number") then
local goto_line = line_index + goto_label;
line_index = goto_line;
else
if(goto_label == "end") then
break;
elseif(goto_label == "begin") then
line_index = 1;
elseif(goto_label == "if_end") then
-- goto if's "end" command
line_index = line_index + 1;
-- support nested if, else
local nested_count = 0;
while line_index <= line_count do
local cmd = cmd_list[line_index];
if(cmd~="") then
local cmd_name = self:GetCommandName(cmd);
if(cmd_name == "fi") then
if(nested_count > 0) then
nested_count = nested_count - 1;
else
line_index = line_index + 1;
break;
end
elseif(cmd_name == "if") then
if(cmd:match("%s+then%s*$")) then
nested_count = nested_count + 1;
end
end
end
line_index = line_index + 1;
end
elseif(goto_label == "else") then
-- continue to "else", "elseif", "fi", command
line_index = line_index + 1;
-- support nested if, else
local nested_count = 0;
while line_index <= line_count do
local cmd = cmd_list[line_index];
if(cmd~="") then
local cmd_name = self:GetCommandName(cmd);
if(cmd_name == "else") then
if(nested_count == 0) then
line_index = line_index + 1;
break;
end
elseif(cmd_name == "fi") then
if(nested_count > 0) then
nested_count = nested_count - 1;
else
line_index = line_index + 1;
break;
end
elseif(cmd_name == "if") then
if(cmd:match("%s+then%s*$")) then
nested_count = nested_count + 1;
end
elseif(cmd_name == "elseif" or cmd_name == "elif") then
if(nested_count == 0) then
cmd = cmd:gsub("^[%s/]*els?e?if", "if");
last_result, goto_label = self:RunWithVariables(variables, cmd, fromEntity);
if(goto_label ~= "else") then
line_index = line_index + 1;
break;
end
end
end
end
line_index = line_index + 1;
end
elseif(goto_label == "functionend") then
line_index = line_index + 1;
while line_index <= line_count do
local cmd = cmd_list[line_index];
if(cmd~="") then
local cmd_name = self:GetCommandName(cmd);
if(cmd_name == "functionend") then
line_index = line_index + 1;
break;
end
end
line_index = line_index + 1;
end
else
-- TODO: jump to a labeled line that starts with ":"
break;
end
end
else
break;
end
else
line_index = line_index + 1;
end
else
line_index = line_index + 1;
end
end
if(macros) then
local text = table.concat(macros, "\n");
if(not GameLogic.Macros:HasUnplayedPreparedMode()) then
local player = GameLogic.EntityManager.GetPlayer()
local cx, cy, cz = player:GetBlockPos();
GameLogic.Macros:PrepareDefaultPlayMode(cx, cy, cz)
end
GameLogic.Macros:PrepareInitialBuildState()
GameLogic.Macros:Play(text);
end
return last_result;
end
-- run command list and return the result.
function CommandManager:RunCmdList(cmd_list, variables, fromEntity)
return self:RunCmdSegment(cmd_list, nil, nil, variables, fromEntity);
end
function CommandManager:LoadCmdHelpFile()
NPL.load("(gl)script/ide/Encoding.lua");
local Encoding = commonlib.gettable("commonlib.Encoding");
CommandManager.cmd_helps = CommandManager.cmd_helps or {};
CommandManager.cmd_types = CommandManager.cmd_types or {};
local cmd_helps = CommandManager.cmd_helps;
local dir = L"config/Aries/creator/Commands.xml";
local xmlRoot = ParaXML.LuaXML_ParseFile(dir);
if(xmlRoot) then
LOG.std(nil, "info", "CommandManager", "cmd help loaded from %s", dir);
local cmds = SlashCommand.GetSingleton();
for type_node in commonlib.XPath.eachNode(xmlRoot, "/Commands/Type") do
if(type_node.attr and type_node.attr.name) then
local type_name = type_node.attr.name;
local cmd_type = CommandManager.cmd_types[type_name] or {};
for cmd_node in commonlib.XPath.eachNode(type_node, "/Command") do
local attr = cmd_node.attr;
local cmd_class = cmds:GetSlashCommand(attr.name);
if(not cmd_class) then
LOG.std(nil, "warn", "CommandManager", "unknown command tip of %s in file %s", attr.name, dir);
else
local cmd = {};
cmd.name = attr.name;
-- @note Xizhi: show both source file and xml file version if they differ and desc begins with a Chinese letter.
if(cmd_class.desc~=attr.desc and cmd_class.desc) then
-- prepend source version
--local src_desc = Encoding.EncodeHTMLInnerText(cmd_class.desc);
local src_desc = cmd_class.desc;
if(attr.desc and (string.byte(attr.desc, 1) or 0) > 128) then
cmd.desc = (src_desc or "").."\n"..attr.desc;
else
cmd.desc = src_desc;
end
else
cmd.desc = attr.desc;
end
if(cmd_class.quick_ref~=attr.quick_ref and cmd_class.quick_ref) then
-- append xml quick ref version
cmd.desc = (attr.quick_ref or "").."\n"..cmd.desc;
--cmd.quick_ref = Encoding.EncodeHTMLInnerText(cmd_class.quick_ref);
cmd.quick_ref = cmd_class.quick_ref;
else
cmd.quick_ref = attr.quick_ref;
end
local params = {};
local param_node;
for param_node in commonlib.XPath.eachNode(cmd_node,"/Param") do
if(param_node.attr) then
params[#params + 1] = {name = param_node.attr.name,desc = param_node.attr.desc};
end
end
cmd.params = params;
local instances = {};
local instance_node;
for instance_node in commonlib.XPath.eachNode(cmd_node,"/Instance") do
if(instance_node.attr) then
instances[#instances + 1] = {content = instance_node.attr.content,desc = instance_node.attr.desc};
end
end
cmd.instances = instances;
if(not cmd_helps[cmd.name]) then
cmd_helps[cmd.name] = cmd;
end
if(not cmd_type) then
cmd_type = {};
end
if(not cmd_type[cmd.name]) then
cmd_type[#cmd_type + 1] = cmd;
end
end
end
if(not CommandManager.cmd_types[type_name]) then
table.sort(cmd_type,function(a,b)
return (a.name) < (b.name);
end);
CommandManager.cmd_types[type_name] = cmd_type;
end
end
end
else
LOG.std(nil, "warn", "CommandManager", "can not find file %s", dir);
end
-- add any missing command names to help.
local cmd_type = CommandManager.cmd_types[L"命令列表"];
if(not cmd_type) then
cmd_type = {};
CommandManager.cmd_types[L"命令列表"] = cmd_type;
end
for name, cmd in pairs(SlashCommand.slash_command_maps) do
if(not cmd_helps[name]) then
--cmd_helps[name] = {name = name, quick_ref = Encoding.EncodeHTMLInnerText(cmd.quick_ref), desc = Encoding.EncodeHTMLInnerText(cmd.desc or ""), params = {}, instances = {}, }
cmd_helps[name] = {name = name, quick_ref = cmd.quick_ref, desc = cmd.desc or "", params = {}, instances = {}, }
cmd_type[#cmd_type + 1] = cmd_helps[name];
end
end
end
-- lazy load all command help
function CommandManager:GetCmdHelpDS()
if(not CommandManager.cmd_helps) then
self:LoadCmdHelpFile();
end
return CommandManager.cmd_helps;
end
function CommandManager:GetCmdTypeDS()
if(not CommandManager.cmd_types) then
self:LoadCmdHelpFile();
end
return CommandManager.cmd_types;
end
| gpl-2.0 |
Grocel/wire-extras | lua/entities/gmod_wire_wireless_recv/init.lua | 4 | 3455 |
AddCSLuaFile( "cl_init.lua" )
AddCSLuaFile( "shared.lua" )
include('shared.lua')
ENT.WireDebugName = "BT_Recv"
local MODEL = Model( "models/props_lab/binderblue.mdl" )
local Recvs = {}
function GetWirelessRecv()
return Recvs;
end
function ENT:Initialize()
self:PhysicsInit( SOLID_VPHYSICS )
self:SetMoveType( MOVETYPE_VPHYSICS )
self:SetSolid( SOLID_VPHYSICS )
self.Key=0;
self.SendMsg=0;
self.Buff={};
self.Byte=0;
self.Connected=0;
self:SetOverlayText("Wireless Receiver - Scanning")
table.insert( Recvs , self );
self.Inputs = Wire_CreateInputs(self, { "Pop" , "Message" , "Send" , "Reset" , "Key" })
self.Outputs = Wire_CreateOutputs(self, { "Connected" , "Count" , "Message" })
end
function ENT:TriggerInput(iname, value)
if ( value != nil && iname == "Key" ) then
self.Key=value;
iname="Reset";
value=1;
end
if ( iname == "Reset" ) then
if ( value != nil && math.floor( value ) != 0 ) then
if self.Connected != 0 then
self.Connected:Dissconnect( self );
end
self.SendMsg=0;
self.Buff={};
self.Byte=0;
self.Connected=0;
end
end
if ( iname == "Pop" ) then
if ( value != nil && math.floor( value ) != 0 ) then
table.remove( self.Buff , 1 )
end
end
if ( value != nil && iname == "Message" ) then
self.SendMsg=value;
end
if ( iname == "Send" ) then
if ( value != nil && value != nil && math.floor( value ) != 0 ) then
if ( self.Connected != 0 ) then
if ( self.Connected:IsValid() ) then
self.Connected:Push( self , self.SendMsg )
else
self.Connected=0
end
end
end
end
self:UpdateRMessage();
end
function ENT:UpdateRMessage()
if ( self.Connected != 0 ) then
if self.Key != 0 then
self:SetOverlayText("Wireless Receiver (" .. self.Key .. ") - Connected")
else
self:SetOverlayText("Wireless Receiver - Connected")
end
Wire_TriggerOutput(self, "Connected", 1 )
else
if self.Key != 0 then
self:SetOverlayText("Wireless Receiver (" .. self.Key .. ") - Scanning")
else
self:SetOverlayText("Wireless Receiver - Scanning")
end
Wire_TriggerOutput(self, "Connected", 0 )
end
Wire_TriggerOutput(self, "Count", #self.Buff )
Wire_TriggerOutput(self, "Message", self.Buff[1] or 0 )
end
function ENT:Push( data )
table.insert( self.Buff, data );
self:UpdateRMessage();
end
function ENT:Think()
if self.Connected != 0 then
if ( not self.Connected:IsValid() ) then self.Connected=0 end
else
local Closest=0;
local CDistance=0;
if self then
local myPos = self:GetPos();
for _,Server in pairs( GetWirelessSrv() ) do
if Server then
if Server.Key == self.Key then
local TheirPos=Server:GetPos();
local ldist=TheirPos:Distance( myPos )
if ( Closest == 0 || ldist < CDistance ) then
CDistance=ldist
Closest=Server
end
end
end
end
end
if ( Closest != 0 ) then
self.Connected=Closest;
Closest:Connect( self );
self:UpdateRMessage();
end
end
self.BaseClass.Think(self)
end
function ENT:OnRemove()
if self.Connected != 0 then
self.Connected:Dissconnect( self );
end
for Key,BT in pairs( GetWirelessRecv() ) do
if BT == self then
table.remove( Recvs , Key )
end
end
end
| apache-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/talents/techniques/unarmed-discipline.lua | 2 | 10360 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
-- We don't have to worry much about this vs. players since it requires combo points to be really effective and the AI isn't very bright
-- I lied, letting the AI use this is a terrible idea
newTalent{
name = "Combination Kick",
type = {"technique/unarmed-discipline", 1},
short_name = "PUSH_KICK",
require = techs_dex_req1,
points = 5,
random_ego = "attack",
cooldown = 10,
stamina = 40,
message = "@Source@ unleashes a flurry of disrupting kicks.",
tactical = { ATTACK = { weapon = 2 }, },
requires_target = true,
--on_pre_use = function(self, t, silent) if not self:hasEffect(self.EFF_COMBO) then if not silent then game.logPlayer(self, "You must have a combo going to use this ability.") end return false end return true end,
getStrikes = function(self, t) return self:getCombo() end,
getDamage = function(self, t) return self:combatTalentWeaponDamage(t, 0.1, 0.4) + getStrikingStyle(self, dam) end,
checkType = function(self, t, talent)
if talent.is_spell and self:getTalentLevel(t) < 3 then
return false
end
if talent.is_mind and self:getTalentLevel(t) < 5 then
return false
end
return true
end,
action = function(self, t)
local tg = {type="hit", range=self:getTalentRange(t)}
local x, y, target = self:getTarget(tg)
if not x or not y or not target then return nil end
if core.fov.distance(self.x, self.y, x, y) > 1 then return nil end
-- breaks active grapples if the target is not grappled
if not target:isGrappled(self) then
self:breakGrapples()
end
local talents = {}
for i = 1, t.getStrikes(self, t) do
local hit = self:attackTarget(target, nil, t.getDamage(self, t), true)
if hit then
for tid, active in pairs(target.sustain_talents) do
if active then
local talent = target:getTalentFromId(tid)
if t.checkType(self, t, talent) then talents[tid] = true end
end
end
end
end
local nb = t.getStrikes(self, t)
talents = table.keys(talents)
while #talents > 0 and nb > 0 do
local tid = rng.tableRemove(talents)
target:forceUseTalent(tid, {ignore_energy=true})
nb = nb - 1
end
self:clearCombo()
return true
end,
info = function(self, t)
local damage = t.getDamage(self, t) * 100
return ([[Unleash a flurry of disruptive kicks at your target's vulnerable areas. For each combo point you attack for %d%% weapon damage and deactivate one physical sustain.
At talent level 3 #DARK_ORCHID#Magical#LAST# sustains will also be effected.
At talent level 5 #YELLOW#Mental#LAST# sustains will also be effected.
Using this talent removes your combo points.]])
:format(damage)
end,
}
newTalent{
name = "Defensive Throw",
type = {"technique/unarmed-discipline", 2},
require = techs_dex_req2,
mode = "passive",
points = 5,
-- Limit defensive throws/turn for balance using a buff (warns attacking players of the talent)
-- EFF_DEFENSIVE_GRAPPLING effect is refreshed each turn in _M:actBase in mod.class.Actor.lua
getDamage = function(self, t) return self:combatTalentPhysicalDamage(t, 5, 50) * getUnarmedTrainingBonus(self) end,
getDamageTwo = function(self, t) return self:combatTalentPhysicalDamage(t, 10, 75) * getUnarmedTrainingBonus(self) end,
getchance = function(self, t)
return self:combatLimit(self:getTalentLevel(t) * (5 + self:getCun(5, true)), 100, 0, 0, 50, 50) -- Limit < 100%
end,
getThrows = function(self, t)
return self:combatScale(self:getStr() + self:getDex()-20, 0, 0, 2.24, 180)
end,
-- called by _M:attackTargetWith function in mod\class\interface\Combat.lua (includes adjacency check)
do_throw = function(self, target, t)
local ef = self:hasEffect(self.EFF_DEFENSIVE_GRAPPLING)
if not ef or not rng.percent(self.tempeffect_def.EFF_DEFENSIVE_GRAPPLING.throwchance(self, ef)) then return end
local grappled = target:isGrappled(self)
local hit = self:checkHit(self:combatAttack(), target:combatDefense(), 0, 95) and (grappled or not self:checkEvasion(target)) -- grappled target can't evade
ef.throws = ef.throws - 1
if ef.throws <= 0 then self:removeEffect(self.EFF_DEFENSIVE_GRAPPLING) end
if hit then
self:project(target, target.x, target.y, DamageType.PHYSICAL, self:physicalCrit(t.getDamageTwo(self, t), nil, target, self:combatAttack(), target:combatDefense()))
-- if grappled stun
if grappled and target:canBe("stun") then
target:setEffect(target.EFF_STUNNED, 2, {apply_power=self:combatAttack(), min_dur=1})
self:logCombat(target, "#Source# slams #Target# into the ground!")
-- if not grappled daze
else
self:logCombat(target, "#Source# throws #Target# to the ground!")
-- see if the throw dazes the enemy
if target:canBe("stun") then
target:setEffect(target.EFF_DAZED, 2, {apply_power=self:combatAttack(), min_dur=1})
end
end
else
self:logCombat(target, "#Source# misses a defensive throw against #Target#!", self.name:capitalize(),target.name:capitalize())
end
end,
on_unlearn = function(self, t)
self:removeEffect(self.EFF_DEFENSIVE_GRAPPLING)
end,
info = function(self, t)
local damage = t.getDamage(self, t)
local damagetwo = t.getDamageTwo(self, t)
return ([[When you avoid a melee blow while unarmed, you have a %d%% chance to throw the target to the ground. If the throw lands, the target will take %0.2f damage and be dazed for 2 turns, or %0.2f damage and be stunned for 2 turns if the target is grappled. You may attempt up to %0.1f throws per turn.
The chance of throwing increases with your Accuracy, the damage scales with your Physical Power, and the number of attempts with your Strength and Dexterity.]]):
format(t.getchance(self,t), damDesc(self, DamageType.PHYSICAL, (damage)), damDesc(self, DamageType.PHYSICAL, (damagetwo)), t.getThrows(self, t))
end,
}
newTalent{
name = "Open Palm Block",
short_name = "BREATH_CONTROL",
type = {"technique/unarmed-discipline", 3},
require = techs_dex_req3,
points = 5,
random_ego = "attack",
cooldown = 8,
stamina = 25,
message = "@Source@ prepares to block incoming attacks.",
tactical = { ATTACK = 3, DEFEND = 3 },
requires_target = true,
getBlock = function(self, t) return self:combatTalentPhysicalDamage(t, 10, 75) end,
action = function(self, t)
local blockval = t.getBlock(self, t) * self:getCombo()
self:setEffect(self.EFF_BRAWLER_BLOCK, 2, {block = blockval})
self:clearCombo()
return true
end,
info = function(self, t)
local block = t.getBlock(self, t)
local maxblock = block*5
return ([[Toughen your body blocking up to %d damage per combo point (Max %d) across 2 turns.
Current block value: %d
Using this talent removes your combo points.]])
:format(block, maxblock, block * self:getCombo())
end,
}
newTalent{
name = "Roundhouse Kick",
type = {"technique/unarmed-discipline", 4},
require = techs_dex_req4,
points = 5,
random_ego = "attack",
cooldown = 12,
stamina = 18,
range = 0,
radius = function(self, t) return 1 end,
tactical = { ATTACKAREA = { PHYSICAL = 2 }, DISABLE = { knockback = 2 } },
requires_target = true,
getDamage = function(self, t) return self:combatTalentPhysicalDamage(t, 15, 150) * getUnarmedTrainingBonus(self) end,
target = function(self, t)
return {type="cone", range=self:getTalentRange(t), radius=self:getTalentRadius(t), selffire=false, talent=t}
end,
action = function(self, t)
local tg = self:getTalentTarget(t)
local x, y, target = self:getTarget(tg)
if not x or not y then return nil end
self:breakGrapples()
self:project(tg, x, y, DamageType.PHYSKNOCKBACK, {dam=t.getDamage(self, t), dist=4})
return true
end,
info = function(self, t)
local damage = t.getDamage(self, t)
return ([[Attack your foes in a frontal arc with a roundhouse kick, which deals %0.2f physical damage and knocks your foes back.
This will break any grapples you're maintaining, and the damage will scale with your Physical Power.]]):
format(damDesc(self, DamageType.PHYSICAL, (damage)))
end,
}
--[[
newTalent{
name = "Tempo",
type = {"technique/unarmed-discipline", 3},
short_name = "BREATH_CONTROL",
require = techs_dex_req3,
mode = "sustained",
points = 5,
cooldown = 30,
sustain_stamina = 15,
tactical = { BUFF = 1, STAMINA = 2 },
getStamina = function(self, t) return 1 end,
getDamage = function(self, t) return math.min(10, math.floor(self:combatTalentScale(t, 1, 4))) end,
getDefense = function(self, t) return math.floor(self:combatTalentScale(t, 1, 8)) end,
getResist = function(self, t) return 20 end,
activate = function(self, t)
return {
}
end,
deactivate = function(self, t, p)
return true
end,
callbackOnMeleeAttack = function(self, t, target, hitted, crit, weapon, damtype, mult, dam)
if not hitted or self.turn_procs.tempo or not (self:reactionToward(target) < 0) then return end
self.turn_procs.tempo = true
self:setEffect(target.EFF_RELENTLESS_TEMPO, 2, {
stamina = t.getStamina(self, t),
damage = t.getDamage(self, t),
defense = t.getDefense(self, t),
resist = t.getResist(self, t)
})
return true
end,
info = function(self, t)
local stamina = t.getStamina(self, t)
local damage = t.getDamage(self, t)
local resistance = t.getResist(self, t)
local defense = t.getDefense(self, t)
return (Your years of fighting have trained you for sustained engagements. Each turn you attack at least once you gain %d Stamina Regeneration, %d Defense, and %d%% Damage Increase.
This effect lasts 2 turns and stacks up to 5 times.
At talent level 3 you gain %d%% All Resistance upon reaching 5 stacks.
):
--format(stamina, defense, damage, resistance ) --
--end,
--}
--]]
| gpl-3.0 |
hfjgjfg/PERSIANGUARD10 | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/The_Eldieme_Necropolis_[S]/Zone.lua | 1 | 1159 | -----------------------------------
--
-- Zone: The_Eldieme_Necropolis_[S]
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs"] = nil;
require("scripts/zones/The_Eldieme_Necropolis_[S]/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
| gpl-3.0 |
DashingStrike/Automato-ATITD | scripts/bricks_auto.lua | 2 | 3349 | dofile("ui_utils.inc");
dofile("settings.inc");
dofile("constants.inc");
dofile("screen_reader_common.inc");
dofile("common.inc");
imgTake = "Take.png";
imgEverything = "Everything.png";
imgToMake = "toMake.png";
brickNames = { "Bricks", "Clay Bricks", "Firebricks" };
brickImages = { "makeBricks.png", "makeClayBricks.png", "makeFirebricks.png" };
typeOfBrick = 1;
arrangeWindows = true;
unpinWindows = true;
function doit()
promptParameters();
askForWindow("Make sure your chats are minimized and brick rack menus are pinned then hover ATITD window and press Shift to continue.");
if(arrangeWindows) then
arrangeInGrid();
end
while(true) do
checkBreak();
makeBricks();
lsSleep(click_delay);
end
end
function promptParameters()
scale = 1.1;
local z = 0;
local is_done = nil;
local value = nil;
-- Edit box and text display
while not is_done do
-- Make sure we don't lock up with no easy way to escape!
checkBreak();
local y = 5;
lsSetCamera(0,0,lsScreenX*scale,lsScreenY*scale);
typeOfBrick = readSetting("typeOfBrick",typeOfBrick);
typeOfBrick = lsDropdown("typeOfBrick", 5, y, 0, 150, typeOfBrick, brickNames);
writeSetting("typeOfBrick",typeOfBrick);
y = y + 32;
arrangeWindows = readSetting("arrangeWindows",arrangeWindows);
arrangeWindows = lsCheckBox(10, y, z, 0xFFFFFFff, "Arrange windows", arrangeWindows);
writeSetting("arrangeWindows",arrangeWindows);
y = y + 32;
unpinWindows = readSetting("unpinWindows",unpinWindows);
unpinWindows = lsCheckBox(10, y, z, 0xFFFFFFff, "Unpin windows on exit", unpinWindows);
writeSetting("unpinWindows",unpinWindows);
y = y + 32;
lsPrintWrapped(10, y, z+10, lsScreenX - 20, 0.7, 0.7, 0xD0D0D0ff,
"Stand where you can reach all brick racks with all ingredients on you.");
if lsButtonText(10, (lsScreenY - 30) * scale, z, 100, 0xFFFFFFff, "OK") then
is_done = 1;
end
if lsButtonText((lsScreenX - 100) * scale, (lsScreenY - 30) * scale, z, 100, 0xFFFFFFff,
"End script") then
error "Clicked End Script button";
end
lsDoFrame();
lsSleep(tick_delay);
end
if(unpinWindows) then
setCleanupCallback(cleanup);
end
end
function makeBricks()
-- Click pin ups to refresh the window
clickAllImages("ThisIs.png");
statusScreen("Making bricks");
srReadScreen();
local ThisIsList;
ThisIsList = findAllImages("ThisIs.png");
local i;
for i=1,#ThisIsList do
local x = ThisIsList[i][0];
local y = ThisIsList[i][1];
local width = 100;
local height = 250;
local util = srFindImageInRange("utility.png", x, y, width, height, 5000);
if(util) then
height = util[1] - y;
local p = srFindImageInRange(brickImages[typeOfBrick], x, y, width, height);
if(p) then
safeClick(p[0]+4,p[1]+4);
lsSleep(click_delay);
srReadScreen();
else
local s = findAllImages(imgToMake);
if(#s > 0) then
cleanup();
error("Out of supplies.");
else
p = srFindImageInRange("Take.png", x, y, width, height, 5000);
if(p) then
safeClick(p[0]+4,p[1]+4);
lsSleep(click_delay);
srReadScreen();
p = srFindImage("Everything.png", 5000);
if(p) then
safeClick(p[0]+4,p[1]+4);
lsSleep(click_delay);
srReadScreen();
end
end
end
end
end
end
end
function cleanup()
if(unpinWindows) then
closeAllWindows();
end
end | mit |
KenPowers/dotfiles | home/config/nvim/lua/keymaps.lua | 1 | 2324 | --
-- Global Keymaps
--
local cmd = vim.cmd
local nvim_set_keymap = vim.api.nvim_set_keymap
local wk = require('which-key')
-- Close quickfix if in quickfix
nvim_set_keymap('n', '<C-d>', '&bt ==# "quickfix" ? ":ccl<Cr>" : "<C-d>"', { noremap = true, expr = true })
-- Use <C-d> as escape sequence
nvim_set_keymap('i', '<C-d>', '<Esc>', {})
nvim_set_keymap('c', '<C-d>', '<Esc>', {})
nvim_set_keymap('v', '<C-d>', '<Esc>', {})
nvim_set_keymap('t', '<C-d>', [[<C-\><C-n>]], { noremap = true })
-- Allow <C-d> to be sent to terminal
nvim_set_keymap('t', '<C-f>', '<C-d>', { noremap = true })
-- Toggle relative line numbers
cmd([[
function! NumberToggle()
if (&relativenumber == 1)
set norelativenumber
set number
else
set nonumber
set relativenumber
endif
endfunc
]])
nvim_set_keymap('n', '<C-n>', ':call NumberToggle()<Cr>', { noremap = true })
-- <C-l> redraws the screen and removes any search highlighting.
nvim_set_keymap('n', '<C-l>', ':nohl<Cr><C-l>', { noremap = true })
-- Do not jump on invocation of *
nvim_set_keymap('n', '*', ':keepjumps normal! mi*`i<Cr>', {})
-- Execute macro over lines in visual mode
cmd([[
function! ExecuteMacroOverVisualRange()
echo "@".getcmdline()
execute ":'<,'>normal @".nr2char(getchar())
endfunction
]])
nvim_set_keymap('x', '@', ':<C-u>call ExecuteMacroOverVisualRange()<Cr>', { noremap = true })
wk.register(
{
r = { ':%s/<C-r><C-w>//g<Left><Left>', 'Replace Word Under Cursor' },
s = { '<Cmd>set spell!<Cr>', 'Toggle Spellchecking' },
P = { '<Cmd>set paste!<Cr>', 'Toggle Paste Mode' },
[','] = { '<Cmd>e $MYVIMRC<Cr>', 'Edit init.lua' },
['-'] = { '<Cmd>split<Cr>', 'Horizontal Split' },
['|'] = { '<Cmd>vsplit<Cr>', 'Vertical Split' },
},
{
prefix = '<Leader>',
}
)
-- Copy/yank file paths
nvim_set_keymap('n', 'cp', ':let @*=expand("%")<Cr>', {})
nvim_set_keymap('n', 'cP', ':let @*=expand("%:p")<Cr>', {})
nvim_set_keymap('n', 'yp', ':let @"=expand("%")<Cr>', {})
nvim_set_keymap('n', 'yP', ':let @"=expand("%:p")<Cr>', {})
-- :ww writes with sudo (temporary)
-- https://github.com/neovim/neovim/issues/1716
-- https://github.com/lambdalisue/suda.vim
-- command! -nargs=0 WriteWithSudo :w !sudo tee % > /dev/null
-- cnoreabbrev ww WriteWithSudo
cmd('cnoreabbrev ww SudaWrite')
| mit |
purebn/ShadowBot | plugins/lyrics.lua | 695 | 2113 | do
local BASE_LNM_URL = 'http://api.lyricsnmusic.com/songs'
local LNM_APIKEY = '1f5ea5cf652d9b2ba5a5118a11dba5'
local BASE_LYRICS_URL = 'http://api.chartlyrics.com/apiv1.asmx/SearchLyricDirect'
local function getInfo(query)
print('Getting info of ' .. query)
local url = BASE_LNM_URL..'?api_key='..LNM_APIKEY
..'&q='..URL.escape(query)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local result = json:decode(b)
local artist = result[1].artist.name
local track = result[1].title
return artist, track
end
local function getLyrics(query)
local artist, track = getInfo(query)
if artist and track then
local url = BASE_LYRICS_URL..'?artist='..URL.escape(artist)
..'&song='..URL.escape(track)
local b, c = http.request(url)
if c ~= 200 then
return nil
end
local xml = require("xml")
local result = xml.load(b)
if not result then
return nil
end
if xml.find(result, 'LyricSong') then
track = xml.find(result, 'LyricSong')[1]
end
if xml.find(result, 'LyricArtist') then
artist = xml.find(result, 'LyricArtist')[1]
end
local lyric
if xml.find(result, 'Lyric') then
lyric = xml.find(result, 'Lyric')[1]
else
lyric = nil
end
local cover
if xml.find(result, 'LyricCovertArtUrl') then
cover = xml.find(result, 'LyricCovertArtUrl')[1]
else
cover = nil
end
return artist, track, lyric, cover
else
return nil
end
end
local function run(msg, matches)
local artist, track, lyric, cover = getLyrics(matches[1])
if track and artist and lyric then
if cover then
local receiver = get_receiver(msg)
send_photo_from_url(receiver, cover)
end
return '🎵 ' .. artist .. ' - ' .. track .. ' 🎵\n----------\n' .. lyric
else
return 'Oops! Lyrics not found or something like that! :/'
end
end
return {
description = 'Getting lyrics of a song',
usage = '!lyrics [track or artist - track]: Search and get lyrics of the song',
patterns = {
'^!lyrics? (.*)$'
},
run = run
}
end
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Abdhaljs_Isle-Purgonorgo/Zone.lua | 1 | 1153 | -----------------------------------
--
-- Zone: Abdhaljs_Isle-Purgonorgo
--
-----------------------------------
require("scripts/globals/settings");
package.loaded["scripts/zones/Abdhaljs_Isle-Purgonorgo/TextIDs"] = nil;
require("scripts/zones/Abdhaljs_Isle-Purgonorgo/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,menuchoice)
--print("CSID: ",csid);
--print("RESULT: ",menuchoice);
end;
| gpl-3.0 |
matin-igdery/og | plugins/leaders.lua | 51 | 12502 |
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]
redis:srem(hash, user_id)
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] == 'c' 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 /clink first !"
end
local name = user_print_name(msg.from)
savelog(matches[1], name.." ["..msg.from.id.."] requested group link ["..group_link.."]")
return "invition Group link for this groups is:\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/logs/"..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 |
8devices/carambola2-new-packages | net/luci-app-e2guardian/files/e2guardian-cbi.lua | 39 | 18596 | --[[
LuCI E2Guardian module
Copyright (C) 2015, Itus Networks, Inc.
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
Author: Marko Ratkaj <marko.ratkaj@sartura.hr>
Luka Perkov <luka.perkov@sartura.hr>
]]--
local fs = require "nixio.fs"
local sys = require "luci.sys"
m = Map("e2guardian", translate("E2Guardian"))
m.on_after_commit = function() luci.sys.call("/etc/init.d/e2guardian restart") end
s = m:section(TypedSection, "e2guardian")
s.anonymous = true
s.addremove = false
s:tab("tab_general", translate("General Settings"))
s:tab("tab_additional", translate("Additional Settings"))
s:tab("tab_logs", translate("Logs"))
----------------- General Settings Tab -----------------------
filterip = s:taboption("tab_general", Value, "filterip", translate("IP that E2Guardian listens"))
filterip.datatype = "ip4addr"
filterports = s:taboption("tab_general", Value, "filterports", translate("Port that E2Guardian listens"))
filterports.datatype = "portrange"
filterports.placeholder = "0-65535"
proxyip = s:taboption("tab_general", Value, "proxyip", translate("IP address of the proxy"))
proxyip.datatype = "ip4addr"
proxyip.default = "127.0.0.1"
proxyport = s:taboption("tab_general", Value, "proxyport", translate("Port of the proxy"))
proxyport.datatype = "portrange"
proxyport.placeholder = "0-65535"
languagedir = s:taboption("tab_general", Value, "languagedir", translate("Language dir"))
languagedir.datatype = "string"
languagedir.default = "/usr/share/e2guardian/languages"
language = s:taboption("tab_general", Value, "language", translate("Language to use"))
language.datatype = "string"
language.default = "ukenglish"
loglevel = s:taboption("tab_general", ListValue, "loglevel", translate("Logging Settings"))
loglevel:value("0", translate("none"))
loglevel:value("1", translate("just denied"))
loglevel:value("2", translate("all text based"))
loglevel:value("3", translate("all requests"))
loglevel.default = "2"
logexceptionhits = s:taboption("tab_general", ListValue, "logexceptionhits", translate("Log Exception Hits"))
logexceptionhits:value("0", translate("never"))
logexceptionhits:value("1", translate("log, but don't mark as exceptions"))
logexceptionhits:value("2", translate("log and mark"))
logexceptionhits.default = "2"
logfileformat = s:taboption("tab_general", ListValue, "logfileformat", translate("Log File Format"))
logfileformat:value("1", translate("DansgGuardian format, space delimited"))
logfileformat:value("2", translate("CSV-style format"))
logfileformat:value("3", translate("Squid Log File Format"))
logfileformat:value("4", translate("Tab delimited"))
logfileformat:value("5", translate("Protex format"))
logfileformat:value("6", translate("Protex format with server field blanked"))
logfileformat.default = "1"
accessdeniedaddress = s:taboption("tab_general", Value, "accessdeniedaddress", translate("Access denied address"),
translate("Server to which the cgi e2guardian reporting script was copied. Reporting levels 1 and 2 only"))
accessdeniedaddress.datatype = "string"
accessdeniedaddress.default = "http://YOURSERVER.YOURDOMAIN/cgi-bin/e2guardian.pl"
usecustombannedimage = s:taboption("tab_general", ListValue, "usecustombannedimage", translate("Banned image replacement"))
usecustombannedimage:value("on", translate("Yes"))
usecustombannedimage:value("off", translate("No"))
usecustombannedimage.default = "on"
custombannedimagefile = s:taboption("tab_general", Value, "custombannedimagefile", translate("Custom banned image file"))
custombannedimagefile.datatype = "string"
custombannedimagefile.default = "/usr/share/e2guardian/transparent1x1.gif"
usecustombannedflash = s:taboption("tab_general", ListValue, "usecustombannedflash", translate("Banned flash replacement"))
usecustombannedflash:value("on", translate("Yes"))
usecustombannedflash:value("off", translate("No"))
usecustombannedflash.default = "on"
custombannedflashfile = s:taboption("tab_general", Value, "custombannedflashfile", translate("Custom banned flash file"))
custombannedflashfile.datatype = "string"
custombannedflashfile.default = "/usr/share/e2guardian/blockedflash.swf"
filtergroups = s:taboption("tab_general", Value, "filtergroups", translate("Number of filter groups"))
filtergroups.datatype = "and(uinteger,min(1))"
filtergroups.default = "1"
filtergroupslist = s:taboption("tab_general", Value, "filtergroupslist", translate("List of filter groups"))
filtergroupslist.datatype = "string"
filtergroupslist.default = "/etc/e2guardian/lists/filtergroupslist"
bannediplist = s:taboption("tab_general", Value, "bannediplist", translate("List of banned IPs"))
bannediplist.datatype = "string"
bannediplist.default = "/etc/e2guardian/lists/bannediplist"
exceptioniplist = s:taboption("tab_general", Value, "exceptioniplist", translate("List of IP exceptions"))
exceptioniplist.datatype = "string"
exceptioniplist.default = "/etc/e2guardian/lists/exceptioniplist"
perroomblockingdirectory = s:taboption("tab_general", Value, "perroomblockingdirectory", translate("Per-Room blocking definition directory"))
perroomblockingdirectory.datatype = "string"
perroomblockingdirectory.default = "/etc/e2guardian/lists/bannedrooms/"
showweightedfound = s:taboption("tab_general", ListValue, "showweightedfound", translate("Show weighted phrases found"))
showweightedfound:value("on", translate("Yes"))
showweightedfound:value("off", translate("No"))
showweightedfound.default = "on"
weightedphrasemode = s:taboption("tab_general", ListValue, "weightedphrasemode", translate("Weighted phrase mode"))
weightedphrasemode:value("0", translate("off"))
weightedphrasemode:value("1", translate("on, normal operation"))
weightedphrasemode:value("2", translate("on, phrase found only counts once on a page"))
weightedphrasemode.default = "2"
urlcachenumber = s:taboption("tab_general", Value, "urlcachenumber", translate("Clean result caching for URLs"))
urlcachenumber.datatype = "and(uinteger,min(0))"
urlcachenumber.default = "1000"
urlcacheage = s:taboption("tab_general", Value, "urlcacheage", translate("Age before they should be ignored in seconds"))
urlcacheage.datatype = "and(uinteger,min(0))"
urlcacheage.default = "900"
scancleancache = s:taboption("tab_general", ListValue, "scancleancache", translate("Cache for content (AV) scans as 'clean'"))
scancleancache:value("on", translate("Yes"))
scancleancache:value("off", translate("No"))
scancleancache.default = "on"
phrasefiltermode = s:taboption("tab_general", ListValue, "phrasefiltermode", translate("Filtering options"))
phrasefiltermode:value("0", translate("raw"))
phrasefiltermode:value("1", translate("smart"))
phrasefiltermode:value("2", translate("both raw and smart"))
phrasefiltermode:value("3", translate("meta/title"))
phrasefiltermode.default = "2"
preservecase = s:taboption("tab_general", ListValue, "perservecase", translate("Lower caseing options"))
preservecase:value("0", translate("force lower case"))
preservecase:value("1", translate("don't change"))
preservecase:value("2", translate("scan fist in lower, then in original"))
preservecase.default = "0"
hexdecodecontent = s:taboption("tab_general", ListValue, "hexdecodecontent", translate("Hex decoding options"))
hexdecodecontent:value("on", translate("Yes"))
hexdecodecontent:value("off", translate("No"))
hexdecodecontent.default = "off"
forcequicksearch = s:taboption("tab_general", ListValue, "forcequicksearch", translate("Quick search"))
forcequicksearch:value("on", translate("Yes"))
forcequicksearch:value("off", translate("No"))
forcequicksearch.default = "off"
reverseaddresslookups= s:taboption("tab_general", ListValue, "reverseaddresslookups", translate("Reverse lookups for banned site and URLs"))
reverseaddresslookups:value("on", translate("Yes"))
reverseaddresslookups:value("off", translate("No"))
reverseaddresslookups.default = "off"
reverseclientiplookups = s:taboption("tab_general", ListValue, "reverseclientiplookups", translate("Reverse lookups for banned and exception IP lists"))
reverseclientiplookups:value("on", translate("Yes"))
reverseclientiplookups:value("off", translate("No"))
reverseclientiplookups.default = "off"
logclienthostnames = s:taboption("tab_general", ListValue, "logclienthostnames", translate("Perform reverse lookups on client IPs for successful requests"))
logclienthostnames:value("on", translate("Yes"))
logclienthostnames:value("off", translate("No"))
logclienthostnames.default = "off"
createlistcachefiles = s:taboption("tab_general", ListValue, "createlistcachefiles", translate("Build bannedsitelist and bannedurllist cache files"))
createlistcachefiles:value("on",translate("Yes"))
createlistcachefiles:value("off",translate("No"))
createlistcachefiles.default = "on"
prefercachedlists = s:taboption("tab_general", ListValue, "prefercachedlists", translate("Prefer cached list files"))
prefercachedlists:value("on", translate("Yes"))
prefercachedlists:value("off", translate("No"))
prefercachedlists.default = "off"
maxuploadsize = s:taboption("tab_general", Value, "maxuploadsize", translate("Max upload size (in Kbytes)"))
maxuploadsize:value("-1", translate("no blocking"))
maxuploadsize:value("0", translate("complete block"))
maxuploadsize.default = "-1"
maxcontentfiltersize = s:taboption("tab_general", Value, "maxcontentfiltersize", translate("Max content filter size"),
translate("The value must not be higher than max content ram cache scan size or 0 to match it"))
maxcontentfiltersize.datatype = "and(uinteger,min(0))"
maxcontentfiltersize.default = "256"
maxcontentramcachescansize = s:taboption("tab_general", Value, "maxcontentramcachescansize", translate("Max content ram cache scan size"),
translate("This is the max size of file that DG will download and cache in RAM"))
maxcontentramcachescansize.datatype = "and(uinteger,min(0))"
maxcontentramcachescansize.default = "2000"
maxcontentfilecachescansize = s:taboption("tab_general", Value, "maxcontentfilecachescansize", translate("Max content file cache scan size"))
maxcontentfilecachescansize.datatype = "and(uinteger,min(0))"
maxcontentfilecachescansize.default = "20000"
proxytimeout = s:taboption("tab_general", Value, "proxytimeout", translate("Proxy timeout (5-100)"))
proxytimeout.datatype = "range(5,100)"
proxytimeout.default = "20"
proxyexchange = s:taboption("tab_general", Value, "proxyexchange", translate("Proxy header excahnge (20-300)"))
proxyexchange.datatype = "range(20,300)"
proxyexchange.default = "20"
pcontimeout = s:taboption("tab_general", Value, "pcontimeout", translate("Pconn timeout"),
translate("How long a persistent connection will wait for other requests"))
pcontimeout.datatype = "range(5,300)"
pcontimeout.default = "55"
filecachedir = s:taboption("tab_general", Value, "filecachedir", translate("File cache directory"))
filecachedir.datatype = "string"
filecachedir.default = "/tmp"
deletedownloadedtempfiles = s:taboption("tab_general", ListValue, "deletedownloadedtempfiles", translate("Delete file cache after user completes download"))
deletedownloadedtempfiles:value("on", translate("Yes"))
deletedownloadedtempfiles:value("off", translate("No"))
deletedownloadedtempfiles.default = "on"
initialtrickledelay = s:taboption("tab_general", Value, "initialtrickledelay", translate("Initial Trickle delay"),
translate("Number of seconds a browser connection is left waiting before first being sent *something* to keep it alive"))
initialtrickledelay.datatype = "and(uinteger,min(0))"
initialtrickledelay.default = "20"
trickledelay = s:taboption("tab_general", Value, "trickledelay", translate("Trickle delay"),
translate("Number of seconds a browser connection is left waiting before being sent more *something* to keep it alive"))
trickledelay.datatype = "and(uinteger,min(0))"
trickledelay.default = "10"
downloadmanager = s:taboption("tab_general", Value, "downloadmanager", translate("Download manager"))
downloadmanager.datatype = "string"
downloadmanager.default = "/etc/e2guardian/downloadmanagers/default.conf"
contentscannertimeout = s:taboption("tab_general", Value, "contentscannertimeout", translate("Content scanner timeout"))
contentscannertimeout.datatype = "and(uinteger,min(0))"
contentscannertimeout.default = "60"
contentscanexceptions = s:taboption("tab_general", ListValue, "contentscanexceptions", translate("Content scan exceptions"))
contentscanexceptions:value("on", translate("Yes"))
contentscanexceptions:value("off", translate("No"))
contentscanexceptions.default = "off"
recheckreplacedurls = s:taboption("tab_general", ListValue, "recheckreplacedurls", translate("e-check replaced URLs"))
recheckreplacedurls:value("on", translate("Yes"))
recheckreplacedurls:value("off", translate("No"))
recheckreplacedurls.default = "off"
forwardedfor = s:taboption("tab_general", ListValue, "forwardedfor", translate("Misc setting: forwardedfor"),
translate("If on, it may help solve some problem sites that need to know the source ip."))
forwardedfor:value("on", translate("Yes"))
forwardedfor:value("off", translate("No"))
forwardedfor.default = "off"
usexforwardedfor = s:taboption("tab_general", ListValue, "usexforwardedfor", translate("Misc setting: usexforwardedfor"),
translate("This is for when you have squid between the clients and E2Guardian"))
usexforwardedfor:value("on", translate("Yes"))
usexforwardedfor:value("off", translate("No"))
usexforwardedfor.default = "off"
logconnectionhandlingerrors = s:taboption("tab_general", ListValue, "logconnectionhandlingerrors", translate("Log debug info about log()ing and accept()ing"))
logconnectionhandlingerrors:value("on", translate("Yes"))
logconnectionhandlingerrors:value("off", translate("No"))
logconnectionhandlingerrors.default = "on"
logchildprocesshandling = s:taboption("tab_general", ListValue, "logchildprocesshandling", translate("Log child process handling"))
logchildprocesshandling:value("on", translate("Yes"))
logchildprocesshandling:value("off", translate("No"))
logchildprocesshandling.default = "off"
maxchildren = s:taboption("tab_general", Value, "maxchildren", translate("Max number of processes to spawn"))
maxchildren.datatype = "and(uinteger,min(0))"
maxchildren.default = "180"
minchildren = s:taboption("tab_general", Value, "minchildren", translate("Min number of processes to spawn"))
minchildren.datatype = "and(uinteger,min(0))"
minchildren.default = "20"
minsparechildren = s:taboption("tab_general", Value, "minsparechildren", translate("Min number of processes to keep ready"))
minsparechildren.datatype = "and(uinteger,min(0))"
minsparechildren.default = "16"
preforkchildren = s:taboption("tab_general", Value, "preforkchildren", translate("Sets minimum nuber of processes when it runs out"))
preforkchildren.datatype = "and(uinteger,min(0))"
preforkchildren.default = "10"
maxsparechildren = s:taboption("tab_general", Value, "maxsparechildren", translate("Sets the maximum number of processes to have doing nothing"))
maxsparechildren.datatype = "and(uinteger,min(0))"
maxsparechildren.default = "32"
maxagechildren = s:taboption("tab_general", Value, "maxagechildren", translate("Max age of child process"))
maxagechildren.datatype = "and(uinteger,min(0))"
maxagechildren.default = "500"
maxips = s:taboption("tab_general", Value, "maxips", translate("Max number of clinets allowed to connect"))
maxips:value("0", translate("no limit"))
maxips.default = "0"
ipipcfilename = s:taboption("tab_general", Value, "ipipcfilename", translate("IP list IPC server directory and filename"))
ipipcfilename.datatype = "string"
ipipcfilename.default = "/tmp/.dguardianipc"
urlipcfilename = s:taboption("tab_general", Value, "urlipcfilename", translate("Defines URL list IPC server directory and filename used to communicate with the URL cache process"))
urlipcfilename.datatype = "string"
urlipcfilename.default = "/tmp/.dguardianurlipc"
ipcfilename = s:taboption("tab_general", Value, "ipcfilename", translate("Defines URL list IPC server directory and filename used to communicate with the URL cache process"))
ipcfilename.datatype = "string"
ipcfilename.default = "/tmp/.dguardianipipc"
nodeamon = s:taboption("tab_general", ListValue, "nodeamon", translate("Disable deamoning"))
nodeamon:value("on", translate("Yes"))
nodeamon:value("off", translate("No"))
nodeamon.default = "off"
nologger = s:taboption("tab_general", ListValue, "nologger", translate("Disable logger"))
nologger:value("on", translate("Yes"))
nologger:value("off", translate("No"))
nologger.default = "off"
logadblock = s:taboption("tab_general", ListValue, "logadblock", translate("Enable logging of ADs"))
logadblock:value("on", translate("Yes"))
logadblock:value("off", translate("No"))
logadblock.default = "off"
loguseragent = s:taboption("tab_general", ListValue, "loguseragent", translate("Enable logging of client user agent"))
loguseragent:value("on", translate("Yes"))
loguseragent:value("off", translate("No"))
loguseragent.default = "off"
softrestart = s:taboption("tab_general", ListValue, "softrestart", translate("Enable soft restart"))
softrestart:value("on", translate("Yes"))
softrestart:value("off", translate("No"))
softrestart.default = "off"
------------------------ Additional Settings Tab ----------------------------
e2guardian_config_file = s:taboption("tab_additional", TextValue, "_data", "")
e2guardian_config_file.wrap = "off"
e2guardian_config_file.rows = 25
e2guardian_config_file.rmempty = false
function e2guardian_config_file.cfgvalue()
local uci = require "luci.model.uci".cursor_state()
file = "/etc/e2guardian/e2guardianf1.conf"
if file then
return fs.readfile(file) or ""
else
return ""
end
end
function e2guardian_config_file.write(self, section, value)
if value then
local uci = require "luci.model.uci".cursor_state()
file = "/etc/e2guardian/e2guardianf1.conf"
fs.writefile(file, value:gsub("\r\n", "\n"))
end
end
---------------------------- Logs Tab -----------------------------
e2guardian_logfile = s:taboption("tab_logs", TextValue, "lines", "")
e2guardian_logfile.wrap = "off"
e2guardian_logfile.rows = 25
e2guardian_logfile.rmempty = true
function e2guardian_logfile.cfgvalue()
local uci = require "luci.model.uci".cursor_state()
file = "/tmp/e2guardian/access.log"
if file then
return fs.readfile(file) or ""
else
return "Can't read log file"
end
end
function e2guardian_logfile.write()
return ""
end
return m
| gpl-2.0 |
catch222/neural-style | neural_style.lua | 5 | 11576 | require 'torch'
require 'nn'
require 'image'
require 'optim'
local loadcaffe_wrap = require 'loadcaffe_wrapper'
--------------------------------------------------------------------------------
local cmd = torch.CmdLine()
-- Basic options
cmd:option('-style_image', 'examples/inputs/seated-nude.jpg',
'Style target image')
cmd:option('-content_image', 'examples/inputs/tubingen.jpg',
'Content target image')
cmd:option('-image_size', 512, 'Maximum height / width of generated image')
cmd:option('-gpu', 0, 'Zero-indexed ID of the GPU to use; for CPU mode set -gpu = -1')
-- Optimization options
cmd:option('-content_weight', 5e0)
cmd:option('-style_weight', 1e2)
cmd:option('-tv_weight', 1e-3)
cmd:option('-num_iterations', 1000)
cmd:option('-init', 'random', 'random|image')
-- Output options
cmd:option('-print_iter', 50)
cmd:option('-save_iter', 100)
cmd:option('-output_image', 'out.png')
-- Other options
cmd:option('-style_scale', 1.0)
cmd:option('-pooling', 'max', 'max|avg')
cmd:option('-proto_file', 'models/VGG_ILSVRC_19_layers_deploy.prototxt')
cmd:option('-model_file', 'models/VGG_ILSVRC_19_layers.caffemodel')
cmd:option('-backend', 'nn', 'nn|cudnn')
local function main(params)
if params.gpu >= 0 then
require 'cutorch'
require 'cunn'
cutorch.setDevice(params.gpu + 1)
else
params.backend = 'nn-cpu'
end
if params.backend == 'cudnn' then
require 'cudnn'
end
local cnn = loadcaffe_wrap.load(params.proto_file, params.model_file, params.backend):float()
if params.gpu >= 0 then
cnn:cuda()
end
local content_image = image.load(params.content_image, 3)
content_image = image.scale(content_image, params.image_size, 'bilinear')
local content_image_caffe = preprocess(content_image):float()
local style_image = image.load(params.style_image, 3)
local style_size = math.ceil(params.style_scale * params.image_size)
style_image = image.scale(style_image, style_size, 'bilinear')
local style_image_caffe = preprocess(style_image):float()
if params.gpu >= 0 then
content_image_caffe = content_image_caffe:cuda()
style_image_caffe = style_image_caffe:cuda()
end
-- Hardcode these for now
local content_layers = {23}
local style_layers = {2, 7, 12, 21, 30}
local style_layer_weights = {1e0, 1e0, 1e0, 1e0, 1e0}
-- Set up the network, inserting style and content loss modules
local content_losses, style_losses = {}, {}
local next_content_idx, next_style_idx = 1, 1
local net = nn.Sequential()
if params.tv_weight > 0 then
local tv_mod = nn.TVLoss(params.tv_weight):float()
if params.gpu >= 0 then
tv_mod:cuda()
end
net:add(tv_mod)
end
for i = 1, #cnn do
if next_content_idx <= #content_layers or next_style_idx <= #style_layers then
local layer = cnn:get(i)
local layer_type = torch.type(layer)
local is_pooling = (layer_type == 'cudnn.SpatialMaxPooling' or layer_type == 'nn.SpatialMaxPooling')
if is_pooling and params.pooling == 'avg' then
assert(layer.padW == 0 and layer.padH == 0)
local kW, kH = layer.kW, layer.kH
local dW, dH = layer.dW, layer.dH
local avg_pool_layer = nn.SpatialAveragePooling(kW, kH, dW, dH):float()
if params.gpu >= 0 then avg_pool_layer:cuda() end
local msg = 'Replacing max pooling at layer %d with average pooling'
print(string.format(msg, i))
net:add(avg_pool_layer)
else
net:add(layer)
end
if i == content_layers[next_content_idx] then
local target = net:forward(content_image_caffe):clone()
local loss_module = nn.ContentLoss(params.content_weight, target):float()
if params.gpu >= 0 then
loss_module:cuda()
end
net:add(loss_module)
table.insert(content_losses, loss_module)
next_content_idx = next_content_idx + 1
end
if i == style_layers[next_style_idx] then
local gram = GramMatrix():float()
if params.gpu >= 0 then
gram = gram:cuda()
end
local target_features = net:forward(style_image_caffe):clone()
local target = gram:forward(target_features)
target:div(target_features:nElement())
local weight = params.style_weight * style_layer_weights[next_style_idx]
local loss_module = nn.StyleLoss(weight, target):float()
if params.gpu >= 0 then
loss_module:cuda()
end
net:add(loss_module)
table.insert(style_losses, loss_module)
next_style_idx = next_style_idx + 1
end
end
end
-- We don't need the base CNN anymore, so clean it up to save memory.
cnn = nil
collectgarbage()
-- Initialize the image
local img = nil
if params.init == 'random' then
img = torch.randn(content_image:size()):float():mul(0.001)
elseif params.init == 'image' then
img = content_image_caffe:clone():float()
else
error('Invalid init type')
end
if params.gpu >= 0 then
img = img:cuda()
end
-- Run it through the network once to get the proper size for the gradient
-- All the gradients will come from the extra loss modules, so we just pass
-- zeros into the top of the net on the backward pass.
local y = net:forward(img)
local dy = img.new(#y):zero()
-- Declaring this here lets us access it in maybe_print
local optim_state = {
maxIter = params.num_iterations,
verbose=true,
}
local function maybe_print(t, loss)
local verbose = (params.print_iter > 0 and t % params.print_iter == 0)
if verbose then
print(string.format('Iteration %d / %d', t, params.num_iterations))
for i, loss_module in ipairs(content_losses) do
print(string.format(' Content %d loss: %f', i, loss_module.loss))
end
for i, loss_module in ipairs(style_losses) do
print(string.format(' Style %d loss: %f', i, loss_module.loss))
end
print(string.format(' Total loss: %f', loss))
end
end
local function maybe_save(t)
local should_save = params.save_iter > 0 and t % params.save_iter == 0
should_save = should_save or t == params.num_iterations
if should_save then
local disp = deprocess(img:double())
disp = image.minmax{tensor=disp, min=0, max=1}
local filename = build_filename(params.output_image, t)
if t == params.num_iterations then
filename = params.output_image
end
image.save(filename, disp)
end
end
-- Function to evaluate loss and gradient. We run the net forward and
-- backward to get the gradient, and sum up losses from the loss modules.
-- optim.lbfgs internally handles iteration and calls this fucntion many
-- times, so we manually count the number of iterations to handle printing
-- and saving intermediate results.
local num_calls = 0
local function feval(x)
num_calls = num_calls + 1
net:forward(x)
local grad = net:backward(x, dy)
local loss = 0
for _, mod in ipairs(content_losses) do
loss = loss + mod.loss
end
for _, mod in ipairs(style_losses) do
loss = loss + mod.loss
end
maybe_print(num_calls, loss)
maybe_save(num_calls)
collectgarbage()
-- optim.lbfgs expects a vector for gradients
return loss, grad:view(grad:nElement())
end
-- Run optimization.
local x, losses = optim.lbfgs(feval, img, optim_state)
end
function build_filename(output_image, iteration)
local idx = string.find(output_image, '%.')
local basename = string.sub(output_image, 1, idx - 1)
local ext = string.sub(output_image, idx)
return string.format('%s_%d%s', basename, iteration, ext)
end
-- Preprocess an image before passing it to a Caffe model.
-- We need to rescale from [0, 1] to [0, 255], convert from RGB to BGR,
-- and subtract the mean pixel.
function preprocess(img)
local mean_pixel = torch.DoubleTensor({103.939, 116.779, 123.68})
local perm = torch.LongTensor{3, 2, 1}
img = img:index(1, perm):mul(256.0)
mean_pixel = mean_pixel:view(3, 1, 1):expandAs(img)
img:add(-1, mean_pixel)
return img
end
-- Undo the above preprocessing.
function deprocess(img)
local mean_pixel = torch.DoubleTensor({103.939, 116.779, 123.68})
mean_pixel = mean_pixel:view(3, 1, 1):expandAs(img)
img = img + mean_pixel
local perm = torch.LongTensor{3, 2, 1}
img = img:index(1, perm):div(256.0)
return img
end
-- Define an nn Module to compute content loss in-place
local ContentLoss, parent = torch.class('nn.ContentLoss', 'nn.Module')
function ContentLoss:__init(strength, target)
parent.__init(self)
self.strength = strength
self.target = target
self.loss = 0
self.crit = nn.MSECriterion()
end
function ContentLoss:updateOutput(input)
if input:nElement() == self.target:nElement() then
self.loss = self.crit:forward(input, self.target) * self.strength
else
print('WARNING: Skipping content loss')
end
self.output = input
return self.output
end
function ContentLoss:updateGradInput(input, gradOutput)
if input:nElement() == self.target:nElement() then
self.gradInput = self.crit:backward(input, self.target)
end
self.gradInput:mul(self.strength)
self.gradInput:add(gradOutput)
return self.gradInput
end
-- Returns a network that computes the CxC Gram matrix from inputs
-- of size C x H x W
function GramMatrix()
local net = nn.Sequential()
net:add(nn.View(-1):setNumInputDims(2))
local concat = nn.ConcatTable()
concat:add(nn.Identity())
concat:add(nn.Identity())
net:add(concat)
net:add(nn.MM(false, true))
return net
end
-- Define an nn Module to compute style loss in-place
local StyleLoss, parent = torch.class('nn.StyleLoss', 'nn.Module')
function StyleLoss:__init(strength, target)
parent.__init(self)
self.strength = strength
self.target = target
self.loss = 0
self.gram = GramMatrix()
self.G = nil
self.crit = nn.MSECriterion()
end
function StyleLoss:updateOutput(input)
self.G = self.gram:forward(input)
self.G:div(input:nElement())
self.loss = self.crit:forward(self.G, self.target)
self.loss = self.loss * self.strength
self.output = input
return self.output
end
function StyleLoss:updateGradInput(input, gradOutput)
local dG = self.crit:backward(self.G, self.target)
dG:div(input:nElement())
self.gradInput = self.gram:backward(input, dG)
self.gradInput:mul(self.strength)
self.gradInput:add(gradOutput)
return self.gradInput
end
local TVLoss, parent = torch.class('nn.TVLoss', 'nn.Module')
function TVLoss:__init(strength)
parent.__init(self)
self.strength = strength
self.x_diff = torch.Tensor()
self.y_diff = torch.Tensor()
end
function TVLoss:updateOutput(input)
self.output = input
return self.output
end
-- TV loss backward pass inspired by kaishengtai/neuralart
function TVLoss:updateGradInput(input, gradOutput)
self.gradInput:resizeAs(input):zero()
local C, H, W = input:size(1), input:size(2), input:size(3)
self.x_diff:resize(3, H - 1, W - 1)
self.y_diff:resize(3, H - 1, W - 1)
self.x_diff:copy(input[{{}, {1, -2}, {1, -2}}])
self.x_diff:add(-1, input[{{}, {1, -2}, {2, -1}}])
self.y_diff:copy(input[{{}, {1, -2}, {1, -2}}])
self.y_diff:add(-1, input[{{}, {2, -1}, {1, -2}}])
self.gradInput[{{}, {1, -2}, {1, -2}}]:add(self.x_diff):add(self.y_diff)
self.gradInput[{{}, {1, -2}, {2, -1}}]:add(-1, self.x_diff)
self.gradInput[{{}, {2, -1}, {1, -2}}]:add(-1, self.y_diff)
self.gradInput:mul(self.strength)
self.gradInput:add(gradOutput)
return self.gradInput
end
local params = cmd:parse(arg)
main(params)
| mit |
flyzjhz/witi-openwrt | package/ramips/ui/luci-mtk/src/modules/admin-full/luasrc/model/cbi/admin_system/admin.lua | 79 | 3356 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Steven Barth <steven@midlink.org>
Copyright 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"
m = Map("system", translate("Router Password"),
translate("Changes the administrator password for accessing the device"))
s = m:section(TypedSection, "_dummy", "")
s.addremove = false
s.anonymous = true
pw1 = s:option(Value, "pw1", translate("Password"))
pw1.password = true
pw2 = s:option(Value, "pw2", translate("Confirmation"))
pw2.password = true
function s.cfgsections()
return { "_pass" }
end
function m.on_commit(map)
local v1 = pw1:formvalue("_pass")
local v2 = pw2:formvalue("_pass")
if v1 and v2 and #v1 > 0 and #v2 > 0 then
if v1 == v2 then
if luci.sys.user.setpasswd(luci.dispatcher.context.authuser, v1) == 0 then
m.message = translate("Password successfully changed!")
else
m.message = translate("Unknown Error, password not changed!")
end
else
m.message = translate("Given password confirmation did not match, password not changed!")
end
end
end
if fs.access("/etc/config/dropbear") then
m2 = Map("dropbear", translate("SSH Access"),
translate("Dropbear offers <abbr title=\"Secure Shell\">SSH</abbr> network shell access and an integrated <abbr title=\"Secure Copy\">SCP</abbr> server"))
s = m2:section(TypedSection, "dropbear", translate("Dropbear Instance"))
s.anonymous = true
s.addremove = true
ni = s:option(Value, "Interface", translate("Interface"),
translate("Listen only on the given interface or, if unspecified, on all"))
ni.template = "cbi/network_netlist"
ni.nocreate = true
ni.unspecified = true
pt = s:option(Value, "Port", translate("Port"),
translate("Specifies the listening port of this <em>Dropbear</em> instance"))
pt.datatype = "port"
pt.default = 22
pa = s:option(Flag, "PasswordAuth", translate("Password authentication"),
translate("Allow <abbr title=\"Secure Shell\">SSH</abbr> password authentication"))
pa.enabled = "on"
pa.disabled = "off"
pa.default = pa.enabled
pa.rmempty = false
ra = s:option(Flag, "RootPasswordAuth", translate("Allow root logins with password"),
translate("Allow the <em>root</em> user to login with password"))
ra.enabled = "on"
ra.disabled = "off"
ra.default = ra.enabled
gp = s:option(Flag, "GatewayPorts", translate("Gateway ports"),
translate("Allow remote hosts to connect to local SSH forwarded ports"))
gp.enabled = "on"
gp.disabled = "off"
gp.default = gp.disabled
s2 = m2:section(TypedSection, "_dummy", translate("SSH-Keys"),
translate("Here you can paste public SSH-Keys (one per line) for SSH public-key authentication."))
s2.addremove = false
s2.anonymous = true
s2.template = "cbi/tblsection"
function s2.cfgsections()
return { "_keys" }
end
keys = s2:option(TextValue, "_data", "")
keys.wrap = "off"
keys.rows = 3
keys.rmempty = false
function keys.cfgvalue()
return fs.readfile("/etc/dropbear/authorized_keys") or ""
end
function keys.write(self, section, value)
if value then
fs.writefile("/etc/dropbear/authorized_keys", value:gsub("\r\n", "\n"))
end
end
end
return m, m2
| gpl-2.0 |
artynet/openwrt-packages | net/prosody/files/prosody.cfg.lua | 65 | 9428 | -- Prosody Example Configuration File
--
-- Information on configuring Prosody can be found on our
-- website at https://prosody.im/doc/configure
--
-- Tip: You can check that the syntax of this file is correct
-- when you have finished by running this command:
-- prosodyctl check config
-- If there are any errors, it will let you know what and where
-- they are, otherwise it will keep quiet.
--
-- The only thing left to do is rename this file to remove the .dist ending, and fill in the
-- blanks. Good luck, and happy Jabbering!
---------- Server-wide settings ----------
-- Settings in this section apply to the whole server and are the default settings
-- for any virtual hosts
-- This is a (by default, empty) list of accounts that are admins
-- for the server. Note that you must create the accounts separately
-- (see https://prosody.im/doc/creating_accounts for info)
-- Example: admins = { "user1@example.com", "user2@example.net" }
admins = { }
-- Enable use of libevent for better performance under high load
-- For more information see: https://prosody.im/doc/libevent
--use_libevent = true
-- Prosody will always look in its source directory for modules, but
-- this option allows you to specify additional locations where Prosody
-- will look for modules first. For community modules, see https://modules.prosody.im/
--plugin_paths = {}
-- This is the list of modules Prosody will load on startup.
-- It looks for mod_modulename.lua in the plugins folder, so make sure that exists too.
-- Documentation on modules can be found at: http://prosody.im/doc/modules
modules_enabled = {
-- Generally required
"roster"; -- Allow users to have a roster. Recommended ;)
"saslauth"; -- Authentication for clients and servers. Recommended if you want to log in.
"tls"; -- Add support for secure TLS on c2s/s2s connections
"dialback"; -- s2s dialback support
"disco"; -- Service discovery
-- Not essential, but recommended
"carbons"; -- Keep multiple clients in sync
"pep"; -- Enables users to publish their avatar, mood, activity, playing music and more
"private"; -- Private XML storage (for room bookmarks, etc.)
"blocklist"; -- Allow users to block communications with other users
"vcard4"; -- User profiles (stored in PEP)
"vcard_legacy"; -- Conversion between legacy vCard and PEP Avatar, vcard
-- Nice to have
"version"; -- Replies to server version requests
"uptime"; -- Report how long server has been running
"time"; -- Let others know the time here on this server
"ping"; -- Replies to XMPP pings with pongs
"register"; -- Allow users to register on this server using a client and change passwords
--"mam"; -- Store messages in an archive and allow users to access it
--"csi_simple"; -- Simple Mobile optimizations
-- Admin interfaces
"admin_adhoc"; -- Allows administration via an XMPP client that supports ad-hoc commands
--"admin_telnet"; -- Opens telnet console interface on localhost port 5582
-- HTTP modules
--"bosh"; -- Enable BOSH clients, aka "Jabber over HTTP"
--"websocket"; -- XMPP over WebSockets
--"http_files"; -- Serve static files from a directory over HTTP
-- Other specific functionality
--"limits"; -- Enable bandwidth limiting for XMPP connections
--"groups"; -- Shared roster support
--"server_contact_info"; -- Publish contact information for this service
--"announce"; -- Send announcement to all online users
--"welcome"; -- Welcome users who register accounts
--"watchregistrations"; -- Alert admins of registrations
--"motd"; -- Send a message to users when they log in
--"legacyauth"; -- Legacy authentication. Only used by some old clients and bots.
--"proxy65"; -- Enables a file transfer proxy service which clients behind NAT can use
}
-- These modules are auto-loaded, but should you want
-- to disable them then uncomment them here:
modules_disabled = {
-- "offline"; -- Store offline messages
-- "c2s"; -- Handle client connections
-- "s2s"; -- Handle server-to-server connections
-- "posix"; -- POSIX functionality, sends server to background, enables syslog, etc.
}
-- Disable account creation by default, for security
-- For more information see https://prosody.im/doc/creating_accounts
allow_registration = false
-- Force clients to use encrypted connections? This option will
-- prevent clients from authenticating unless they are using encryption.
c2s_require_encryption = true
-- Force servers to use encrypted connections? This option will
-- prevent servers from authenticating unless they are using encryption.
s2s_require_encryption = true
-- Force certificate authentication for server-to-server connections?
s2s_secure_auth = false
-- Some servers have invalid or self-signed certificates. You can list
-- remote domains here that will not be required to authenticate using
-- certificates. They will be authenticated using DNS instead, even
-- when s2s_secure_auth is enabled.
--s2s_insecure_domains = { "insecure.example" }
-- Even if you disable s2s_secure_auth, you can still require valid
-- certificates for some domains by specifying a list here.
--s2s_secure_domains = { "jabber.org" }
-- Select the authentication backend to use. The 'internal' providers
-- use Prosody's configured data storage to store the authentication data.
authentication = "internal_hashed"
-- Select the storage backend to use. By default Prosody uses flat files
-- in its configured data directory, but it also supports more backends
-- through modules. An "sql" backend is included by default, but requires
-- additional dependencies. See https://prosody.im/doc/storage for more info.
--storage = "sql" -- Default is "internal"
-- For the "sql" backend, you can uncomment *one* of the below to configure:
--sql = { driver = "SQLite3", database = "prosody.sqlite" } -- Default. 'database' is the filename.
--sql = { driver = "MySQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
--sql = { driver = "PostgreSQL", database = "prosody", username = "prosody", password = "secret", host = "localhost" }
-- Archiving configuration
-- If mod_mam is enabled, Prosody will store a copy of every message. This
-- is used to synchronize conversations between multiple clients, even if
-- they are offline. This setting controls how long Prosody will keep
-- messages in the archive before removing them.
archive_expires_after = "1w" -- Remove archived messages after 1 week
-- You can also configure messages to be stored in-memory only. For more
-- archiving options, see https://prosody.im/doc/modules/mod_mam
-- Logging configuration
-- For advanced logging see http://prosody.im/doc/logging
log = {
info = "/var/log/prosody/prosody.log"; -- Change 'info' to 'debug' for verbose logging
error = "/var/log/prosody/prosody.err";
-- "*syslog"; -- Uncomment this for logging to syslog; needs mod_posix
-- "*console"; -- Log to the console, useful for debugging with daemonize=false
}
-- Uncomment to enable statistics
-- For more info see https://prosody.im/doc/statistics
-- statistics = "internal"
-- Pidfile, used by prosodyctl and the init.d script
pidfile = "/var/run/prosody/prosody.pid"
-- User and group, used for daemon
prosody_user = "prosody"
prosody_group = "prosody"
-- Certificates
-- Every virtual host and component needs a certificate so that clients and
-- servers can securely verify its identity. Prosody will automatically load
-- certificates/keys from the directory specified here.
-- For more information, including how to use 'prosodyctl' to auto-import certificates
-- (from e.g. Let's Encrypt) see https://prosody.im/doc/certificates
-- Location of directory to find certificates in (relative to main config file):
--certificates = "certs"
-- HTTPS currently only supports a single certificate, specify it here:
--https_certificate = "certs/localhost.crt"
----------- Virtual hosts -----------
-- You need to add a VirtualHost entry for each domain you wish Prosody to serve.
-- Settings under each VirtualHost entry apply *only* to that host.
VirtualHost "localhost"
VirtualHost "example.com"
enabled = false -- Remove this line to enable this host
-- Assign this host a certificate for TLS, otherwise it would use the one
-- set in the global section (if any).
-- Note that old-style SSL on port 5223 only supports one certificate, and will always
-- use the global one.
ssl = {
key = "/etc/prosody/certs/example.com.key";
certificate = "/etc/prosody/certs/example.com.crt";
}
------ Components ------
-- You can specify components to add hosts that provide special services,
-- like multi-user conferences, and transports.
-- For more information on components, see http://prosody.im/doc/components
---Set up a MUC (multi-user chat) room server on conference.example.com:
--Component "conference.example.com" "muc"
-- Set up a SOCKS5 bytestream proxy for server-proxied file transfers:
--Component "proxy.example.com" "proxy65"
--- Store MUC messages in an archive and allow users to access it
--modules_enabled = { "muc_mam" }
---Set up an external component (default component port is 5347)
--
-- External components allow adding various services, such as gateways/
-- transports to other networks like ICQ, MSN and Yahoo. For more info
-- see: http://prosody.im/doc/components#adding_an_external_component
--
--Component "gateway.example.com"
-- component_secret = "password"
| gpl-2.0 |
TeamHypersomnia/Hypersomnia | hypersomnia/content/gfx/water_surface_3.meta.lua | 66 | 1953 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"122 171 252 255",
"118 168 252 255",
"103 159 251 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/Hypersomnia | hypersomnia/content/gfx/water_surface_33.meta.lua | 66 | 1953 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"122 171 252 255",
"118 168 252 255",
"103 159 251 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/Hypersomnia | hypersomnia/content/gfx/water_surface_31.meta.lua | 66 | 1953 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"122 171 252 255",
"118 168 252 255",
"103 159 251 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/Hypersomnia | hypersomnia/content/gfx/water_surface_25.meta.lua | 66 | 1953 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"122 171 252 255",
"118 168 252 255",
"103 159 251 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/Hypersomnia | hypersomnia/content/gfx/water_surface_12.meta.lua | 66 | 1953 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"122 171 252 255",
"118 168 252 255",
"103 159 251 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/Hypersomnia | hypersomnia/content/gfx/water_surface_15.meta.lua | 66 | 1953 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"122 171 252 255",
"118 168 252 255",
"103 159 251 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/Hypersomnia | hypersomnia/content/gfx/water_surface_7.meta.lua | 66 | 1953 | return {
extra_loadables = {
enabled_generate_neon_map = {
alpha_multiplier = 1,
amplification = 60,
light_colors = {
"122 171 252 255",
"118 168 252 255",
"103 159 251 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 |
RyMarq/Zero-K | effects/zombie.lua | 24 | 1480 | return {
["zombie"] = {
light = {
air = true,
class = [[CSimpleGroundFlash]],
count = 1,
ground = true,
water = true,
properties = {
colormap = [[0 0.75 0 0.33 0 0 0 0.01]],
size = "d1",
sizegrowth = 0.5,
texture = [[groundflash]],
ttl = 32,
},
},
light2 = {
air = true,
class = [[CSimpleGroundFlash]],
count = 1,
ground = true,
water = true,
properties = {
colormap = [[0 0.75 0 0.33 0 0 0 0.01]],
size = "d1",
sizegrowth = -0.5,
texture = [[groundflash]],
ttl = 32,
},
},
airpop = {
air = true,
class = [[heatcloud]],
count = 10,
ground = true,
water = true,
unit = true,
properties = {
heat = "18 r20",
heatfalloff = 0.6,
maxheat = 38,
pos = [[-15 r30, r10, -15 r30]],
size = "3r",
sizegrowth = -0.01,
speed = [[0, 1, 0]],
texture = [[greenlight]],
},
},
},
}
| gpl-2.0 |
madpilot78/ntopng | scripts/lua/hash_table_details.lua | 1 | 2899 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
if(ntop.isPro()) then
package.path = dirs.installdir .. "/pro/scripts/lua/modules/?.lua;" .. package.path
local snmp_utils = require "snmp_utils"
end
require "lua_utils"
local graph_utils = require "graph_utils"
local alert_utils = require "alert_utils"
local page_utils = require("page_utils")
local os_utils = require "os_utils"
local ts_utils = require "ts_utils"
local hash_table = _GET["hash_table"]
local ifstats = interface.getStats()
local ifId = ifstats.id
sendHTTPContentTypeHeader('text/html')
page_utils.set_active_menu_entry(page_utils.menu_entries.interface, {ifname=getHumanReadableInterfaceName(ifId)})
dofile(dirs.installdir .. "/scripts/lua/inc/menu.lua")
if(hash_table == nil) then
print("<div class=\"alert alert alert-danger\"><i class='fas fa-exclamation-triangle fa-lg fa-ntopng-warning'></i> Hash_Table parameter is missing (internal error ?)</div>")
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
return
end
if(not ts_utils.exists("ht:state", {ifid = ifId, hash_table = hash_table})) then
print("<div class=\"alert alert alert-danger\"><i class='fas fa-exclamation-triangle fa-lg fa-ntopng-warning'></i> No available stats for hash table "..hash_table.."</div>")
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
return
end
local nav_url = ntop.getHttpPrefix().."/lua/hash_table_details.lua?ifid="..ifId
local title = i18n("internals.hash_table").. ": "..hash_table
page_utils.print_navbar(title, nav_url,
{
{
active = page == "historical" or not page,
page_name = "historical",
label = "<i class='fas fa-lg fa-chart-area'></i>",
},
}
)
local schema = _GET["ts_schema"] or "ht:state"
local selected_epoch = _GET["epoch"] or ""
local url = ntop.getHttpPrefix()..'/lua/hash_table_details.lua?ifid='..ifId..'&page=historical'
local tags = {
ifid = ifId,
hash_table = hash_table,
}
graph_utils.drawGraphs(ifId, schema, tags, _GET["zoom"], url, selected_epoch, {
timeseries = {
{schema = "ht:state", label = i18n("hash_table.CountriesHash"), extra_params = {hash_table = "CountriesHash"}},
{schema = "ht:state", label = i18n("hash_table.HostHash"), extra_params = {hash_table = "HostHash"}},
{schema = "ht:state", label = i18n("hash_table.MacHash"), extra_params = {hash_table = "MacHash"}},
{schema = "ht:state", label = i18n("hash_table.FlowHash"), extra_params = {hash_table = "FlowHash"}},
{schema = "ht:state", label = i18n("hash_table.AutonomousSystemHash"), extra_params = {hash_table = "AutonomousSystemHash"}},
{schema = "ht:state", label = i18n("hash_table.VlanHash"), extra_params = {hash_table = "VlanHash"}},
}
})
dofile(dirs.installdir .. "/scripts/lua/inc/footer.lua")
| gpl-3.0 |
TerminalShell/zombiesurvival | entities/weapons/weapon_zs_electrohammer/cl_init.lua | 1 | 1258 | include("shared.lua")
SWEP.PrintName = "Electrohammer"
SWEP.ViewModelFOV = 75
function SWEP:DrawHUD()
if GetGlobalBool("classicmode") then return end
surface.SetFont("ZSHUDFontSmall")
local nails = self:GetPrimaryAmmoCount()
local nTEXW, nTEXH = surface.GetTextSize("Right Click to hammer in a nail.")
if 0 < nails then
draw.SimpleText("Nails: "..nails, "ZSHUDFontSmall", w - nTEXW * 0.5 - 24, h - nTEXH * 3, COLOR_LIMEGREEN, TEXT_ALIGN_CENTER)
else
draw.SimpleText("Nails: 0", "ZSHUDFontSmall", w - nTEXW * 0.5 - 24, h - nTEXH * 3, COLOR_RED, TEXT_ALIGN_CENTER)
end
draw.SimpleText("Right click to hammer in a nail.", "ZSHUDFontSmall", w - nTEXW * 0.5 - 24, h - nTEXH * 2, COLOR_LIMEGREEN, TEXT_ALIGN_CENTER)
if GetConVarNumber("crosshair") ~= 1 then return end
self:DrawCrosshairDot()
--if LocalPlayer() == self:GetOwner() then
--local eyes = LocalPlayer():EyePos()
--local props = {}
--for _, ent in pairs( ents.FindByClass( "prop_physics*" )) do
-- if !ent:IsNailed() and (ent:GetMaxBarricadeHealth() == 0 or ent:GetBarricadeHealth() > 0) and --TrueVisible( eyes, ent:NearestPoint( eyes ) ) then
-- table.insert( props, ent )
-- end
--end
--halo.Add( props, Color( 255, 255, 0 ), 2, 2, 1, true, true )
--end
end
| gpl-3.0 |
madpilot78/ntopng | scripts/lua/rest/v2/get/host/fingerprint/ja3.lua | 1 | 1846 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
local graph_utils = require "graph_utils"
require "flow_utils"
require "historical_utils"
local fingerprint_utils = require "fingerprint_utils"
local rest_utils = require("rest_utils")
local available_fingerprints = {
ja3 = {
stats_key = "ja3_fingerprint",
href = function(fp) return '<A class="ntopng-external-link" href="https://sslbl.abuse.ch/ja3-fingerprints/'..fp..'" target="_blank">'..fp..' <i class="fas fa-external-link-alt"></i></A>' end
},
hassh = {
stats_key = "hassh_fingerprint",
href = function(fp) return fp end
}
}
-- Parameters used for the rest answer --
local rc
local res = {}
local ifid = _GET["ifid"]
local host_info = url2hostinfo(_GET)
local fingerprint_type = _GET["fingerprint_type"]
-- #####################################################################
local stats
if isEmptyString(fingerprint_type) then
rc = rest_utils.consts.err.invalid_args
rest_utils.answer(rc)
return
end
if isEmptyString(ifid) then
rc = rest_utils.consts.err.invalid_interface
rest_utils.answer(rc)
return
end
if isEmptyString(host_info["host"]) then
rc = rest_utils.consts.err.invalid_args
rest_utils.answer(rc)
return
end
if(host_info["host"] ~= nil) then
stats = interface.getHostInfo(host_info["host"], host_info["vlan"])
end
stats = stats or {}
if fingerprint_type == "ja3" then
stats = stats and stats.ja3_fingerprint
elseif fingerprint_type == "hassh" then
stats = stats and stats.hassh_fingerprint
end
tprint(stats)
for key, value in pairs(stats) do
res[#res + 1] = value
res[#res]["ja3_fingerprint"] = key
end
rc = rest_utils.consts.success.ok
rest_utils.answer(rc, res)
| gpl-3.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/applications/luci-asterisk/luasrc/model/cbi/asterisk/phone_sip.lua | 80 | 3813 | --[[
LuCI - Lua Configuration Interface
Copyright 2008 Jo-Philipp Wich <xm@subsignal.org>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
$Id$
]]--
local ast = require("luci.asterisk")
local function find_outgoing_contexts(uci)
local c = { }
local h = { }
uci:foreach("asterisk", "dialplan",
function(s)
if not h[s['.name']] then
c[#c+1] = { s['.name'], "Dialplan: %s" % s['.name'] }
h[s['.name']] = true
end
end)
return c
end
local function find_incoming_contexts(uci)
local c = { }
local h = { }
uci:foreach("asterisk", "sip",
function(s)
if s.context and not h[s.context] and
uci:get_bool("asterisk", s['.name'], "provider")
then
c[#c+1] = { s.context, "Incoming: %s" % s['.name'] or s.context }
h[s.context] = true
end
end)
return c
end
--
-- SIP phone info
--
if arg[2] == "info" then
form = SimpleForm("asterisk", "SIP Phone Information")
form.reset = false
form.submit = "Back to overview"
local info, keys = ast.sip.peer(arg[1])
local data = { }
for _, key in ipairs(keys) do
data[#data+1] = {
key = key,
val = type(info[key]) == "boolean"
and ( info[key] and "yes" or "no" )
or ( info[key] == nil or #info[key] == 0 )
and "(none)"
or tostring(info[key])
}
end
itbl = form:section(Table, data, "SIP Phone %q" % arg[1])
itbl:option(DummyValue, "key", "Key")
itbl:option(DummyValue, "val", "Value")
function itbl.parse(...)
luci.http.redirect(
luci.dispatcher.build_url("admin", "asterisk", "phones")
)
end
return form
--
-- SIP phone configuration
--
elseif arg[1] then
cbimap = Map("asterisk", "Edit SIP Client")
peer = cbimap:section(NamedSection, arg[1])
peer.hidden = {
type = "friend",
qualify = "yes",
host = "dynamic",
nat = "no",
canreinvite = "no"
}
back = peer:option(DummyValue, "_overview", "Back to phone overview")
back.value = ""
back.titleref = luci.dispatcher.build_url("admin", "asterisk", "phones")
active = peer:option(Flag, "disable", "Account enabled")
active.enabled = "yes"
active.disabled = "no"
function active.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "yes"
end
exten = peer:option(Value, "extension", "Extension Number")
cbimap.uci:foreach("asterisk", "dialplanexten",
function(s)
exten:value(
s.extension,
"%s (via %s/%s)" %{ s.extension, s.type:upper(), s.target }
)
end)
display = peer:option(Value, "callerid", "Display Name")
username = peer:option(Value, "username", "Authorization ID")
password = peer:option(Value, "secret", "Authorization Password")
password.password = true
regtimeout = peer:option(Value, "registertimeout", "Registration Time Value")
function regtimeout.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "60"
end
sipport = peer:option(Value, "port", "SIP Port")
function sipport.cfgvalue(...)
return AbstractValue.cfgvalue(...) or "5060"
end
linekey = peer:option(ListValue, "_linekey", "Linekey Mode (broken)")
linekey:value("", "Off")
linekey:value("trunk", "Trunk Appearance")
linekey:value("call", "Call Appearance")
dialplan = peer:option(ListValue, "context", "Assign Dialplan")
dialplan.titleref = luci.dispatcher.build_url("admin", "asterisk", "dialplans")
for _, v in ipairs(find_outgoing_contexts(cbimap.uci)) do
dialplan:value(unpack(v))
end
incoming = peer:option(StaticList, "incoming", "Receive incoming calls from")
for _, v in ipairs(find_incoming_contexts(cbimap.uci)) do
incoming:value(unpack(v))
end
--function incoming.cfgvalue(...)
--error(table.concat(MultiValue.cfgvalue(...),"."))
--end
return cbimap
end
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Port_Bastok/npcs/Alib-Mufalib.lua | 3 | 1033 | -----------------------------------
-- Area: Port Bastok
-- NPC: Alib-Mufalib
-- Type: Warp NPC
-- @zone: 236
-- @pos: 116.080 7.372 -31.820
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Port_Bastok/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0166);
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 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/SummerCamp/SummerCampAskView.lua | 1 | 5895 | --[[
author:yangguiyi
date:
Desc:
use lib:
local SummerCampAskView = NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/SummerCamp/SummerCampAskView.lua")
SummerCampAskView.ShowView()
]]
local HttpWrapper = NPL.load("(gl)script/apps/Aries/Creator/HttpAPI/HttpWrapper.lua");
local QuestAction = commonlib.gettable("MyCompany.Aries.Game.Tasks.Quest.QuestAction");
local httpwrapper_version = HttpWrapper.GetDevVersion();
local SummerCampAskView = NPL.export()
local page = nil
local problems = {
{answer = "毛泽东", option1 = "毛泽东", option2 = " 邓小平", questiton = "秋收起义是谁领导的?"},
{answer = "农村包围城市", option1 = "农村包围城市", option2 = "建立全国统一抗日战线", questiton = "秋收起义确立了以下哪个战略思想?"},
{answer = "洛川会议", option1 = "洛川会议", option2 = "遵义会议", questiton = "以下哪次会议确立了全面抗战路线?"},
{answer = "华南战场", option1 = "华北战场", option2 = "华南战场", questiton = "东江纵队是以下哪个战场的武装力量?"},
{answer = "毛泽东", option1 = "毛泽东", option2 = "刘少奇", questiton = "古田会议是由谁主持召开的?"},
{answer = "25000里", option1 = "25000里", option2 = "20000里", questiton = "红军长征总共多少里?"},
{answer = "红井", option1 = "石井", option2 = "红井", questiton = "“吃水不忘挖井人,时刻想念毛主席”中的井后来被人们叫做?"},
{answer = "刘胡兰", option1 = "江姐", option2 = "刘胡兰", questiton = "毛主席题词“生的伟大,死的光荣”是为了纪念以下哪位烈士?"},
{answer = "7月1日", option1 = "7月1日", option2 = "8月1日", questiton = "建党节是哪一天?"},
{answer = "朱德", option1 = "彭德怀", option2 = "朱德", questiton = "毛主席称赞以下那位是“人民的光荣”?"},
{answer = "中共七大", option1 = "中共四大", option2 = "中共七大", questiton = "周恩来在哪次会议上作出了《论统一战线》的重要讲话?"},
{answer = "《论联合政府》", option1 = "《论解放区战场》", option2 = "《论联合政府》", questiton = "毛主席在中共七大上提交了以下哪项报告?"},
{answer = "邓小平", option1 = "周恩来", option2 = "邓小平", questiton = "红八军军部旧址楼前的两棵柏树是由谁亲手栽下的?"},
{answer = "延安", option1 = "延安", option2 = "西安", questiton = "以下哪个城市被誉为红色革命根据地?"},
{answer = "瑞金", option1 = "遵义", option2 = "瑞金", questiton = "伟大长征的起点是哪里?"},
{answer = "激战腊子口", option1 = "激战腊子口", option2 = "淞沪会战", questiton = "以下哪个是长征期间发生的战斗?"},
{answer = "毛泽东", option1 = "博古", option2 = "毛泽东", questiton = "遵义会议确立了谁的领导地位?"},
{answer = "中共一大", option1 = "中共一大", option2 = "中共三大", questiton = "党在嘉兴南湖的红船上召开了哪次会议?"},
{answer = "上海", option1 = "上海", option2 = "南昌", questiton = "中共一大会址所在地在以下哪个城市?"},
{answer = "1921年", option1 = "1921年", option2 = "1925年", questiton = "中国共产党成立于哪一年?"},
}
local gsid = 70010
function SummerCampAskView.OnInit()
page = document:GetPageCtrl();
page.OnCreate = SummerCampAskView.OnCreate
end
function SummerCampAskView.ShowView()
if QuestAction.CheckSummerTaskFinish(gsid) then
_guihelper.MessageBox("您已完成所有答题");
return
end
SummerCampAskView.InitData()
local view_width = 722
local view_height = 231
local params = {
url = "script/apps/Aries/Creator/Game/Tasks/SummerCamp/SummerCampAskView.html",
name = "SummerCampAskView.ShowView",
isShowTitleBar = false,
DestroyOnClose = true,
style = CommonCtrl.WindowFrame.ContainerStyle,
allowDrag = true,
enable_esc_key = true,
zorder = 4,
app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key,
directPosition = true,
align = "_ct",
x = -view_width/2,
y = -view_height/2 + 100,
width = view_width,
height = view_height,
};
System.App.Commands.Call("File.MCMLWindowFrame", params);
end
function SummerCampAskView.GetAskDesc()
local data = problems[SummerCampAskView.ask_index]
if data then
return data.questiton
end
end
function SummerCampAskView.GetButtonDesc(index)
local data = problems[SummerCampAskView.ask_index]
local option = data["option" .. index]
if option then
return option
end
end
function SummerCampAskView.OnClickAnswer(index)
local data = problems[SummerCampAskView.ask_index]
local button_desc = SummerCampAskView.GetButtonDesc(index)
if button_desc == data.answer then
SummerCampAskView.right_num = SummerCampAskView.right_num + 1
else
_guihelper.MessageBox("请您再思考一下");
return
end
SummerCampAskView.ask_index = SummerCampAskView.ask_index + 1
if SummerCampAskView.ask_index > #problems then
if SummerCampAskView.right_num >= #problems then
page:CloseWindow()
GameLogic.AddBBS("summer_ask", L"恭喜你完成所有答题");
QuestAction.SetSummerTaskProgress(gsid, nil, function()
GameLogic.GetCodeGlobal():BroadcastTextEvent("openRemainOriginalUI",{name="certiRemainOriginal"})
end)
end
return
end
page:Refresh(0)
end
function SummerCampAskView.InitData()
SummerCampAskView.ask_index = 1
SummerCampAskView.right_num = 0
SummerCampAskView.error_num = 0
end | gpl-2.0 |
DashingStrike/Automato-ATITD | scripts/gather_resources.lua | 1 | 5714 | -- Gather_Resources.lua v1.0 -- by Darkfyre
--
--
dofile("common.inc");
button_names = {"Grass","Grass Small Icon","Slate","Slate Small Icon","Clay","Clay Small Icon"};
counter = 0;
postClickDelay = 500;
function checkOK()
while 1 do
checkBreak();
srReadScreen();
OK = srFindImage("OK.png");
if OK then
sleepWithStatus(100, "A popup box has been detected!\n\nAre you out of water?\n\nRun to nearby water (leave this popup open).\n\nAs soon as water icon appears, jugs will be refilled and popup window closed.");
if drawWater(1) then
closePopUp();
end
else
break;
end
end
end
function closePopUp()
srReadScreen();
local OK = srFindImage("OK.png");
if OK then
safeClick(OK[0]+3, OK[1]-5);
end
end
function gatherGrass()
while 1 do
checkBreak();
srReadScreen();
local grass = srFindImage("grass.png",1000);
if grass then
srClickMouseNoMove(grass[0]+5,grass[1],1);
sleepWithStatus(postClickDelay, "Clicking Grass Icon\n\nGrass Collected: " .. tostring(counter));
counter = counter + 1;
else
sleepWithStatus(100, "Searching for Grass Icon\n\nGrass Collected: " .. tostring(counter));
end
end
end
function gatherGrassSmall()
while 1 do
checkBreak();
srReadScreen();
local grasssmall = srFindImage("grass_small.png", 1000);
if grasssmall then
srClickMouseNoMove(grasssmall[0]+5,grasssmall[1],1);
sleepWithStatus(postClickDelay, "Clicking Small Grass Icon\n\nGrass Collected: " .. tostring(counter));
counter = counter + 1;
else
sleepWithStatus(100, "Searching for Small Grass Icon\n\nGrass Collected: " .. tostring(counter));
end
end
end
function gatherSlate()
while 1 do
checkBreak();
srReadScreen();
local slate = srFindImage("slate.png",1000);
if slate then
srClickMouseNoMove(slate[0]+5,slate[1],1);
sleepWithStatus(postClickDelay, "Clicking Slate Icon\n\nSlate Collected: " .. tostring(counter));
counter = counter + 1;
else
sleepWithStatus(100, "Searching for Slate Icon\n\nSlate Collected: " .. tostring(counter));
end
end
end
function gatherSlateSmall()
while 1 do
checkBreak();
srReadScreen();
local slatesmall = srFindImage("slate_small.png", 10000);
if slatesmall then
srClickMouseNoMove(slatesmall[0]+5,slatesmall[1],1);
sleepWithStatus(postClickDelay, "Clicking Small Slate Icon\n\nSlate Collected: " .. tostring(counter));
counter = counter + 1;
else
sleepWithStatus(100, "Searching for Small Slate Icon\n\nSlate Collected: " .. tostring(counter));
end
end
end
function gatherClay()
while 1 do
checkOK();
checkBreak();
srReadScreen();
local clay = srFindImage("clay.png");
if clay then
srClickMouseNoMove(clay[0]+5,clay[1],1);
sleepWithStatus(postClickDelay, "Clicking Clay Icon\n\nClay Collected: " .. tostring(counter));
counter = counter + 1;
else
sleepWithStatus(100, "Searching for Clay Icon\n\nClay Collected: " .. tostring(counter));
end
end
end
function gatherClaySmall()
while 1 do
checkOK();
checkBreak();
srReadScreen();
local claysmall = srFindImage("clay_small.png", 10000);
if claysmall then
srClickMouseNoMove(claysmall[0]+5,claysmall[1],1);
sleepWithStatus(postClickDelay, "Clicking Small Clay Icon\n\nClay Collected: " .. tostring(counter));
counter = counter + 1;
else
sleepWithStatus(100, "Searching for Small Clay Icon\n\nClay Collected: " .. tostring(counter));
end
end
end
function doit()
gatherResources();
end
function gatherResources()
askForWindow('Searches for and clicks the selected resource (clay, grass, slate) until stopped. Icons can be on either side of the screen and either large or small.\n\nGrass: It\'s efficient (less running) if you walk instead of run (Self Click -> Emote -> Gait: Walking -- Gait: Running to restore)\n\nPress Shift over ATITD window to continue.');
while 1 do
-- Ask for which button
local image_name = nil;
local is_done = nil;
while not is_done do
local y = nil;
local x = nil;
local bsize = nil;
checkBreak();
lsPrint(5, 200, 2, 0.65, 0.65, 0xffffffff, " If you have \'Smaller Icons\' chosen in ");
lsPrint(5, 215, 2, 0.65, 0.65, 0xffffffff, "Action Icons (Interface-Options), then choose");
lsPrint(5, 230, 2, 0.65, 0.65, 0xffffffff, "\'Small Icon\' button.");
lsPrint(5, 260, 2, 0.65, 0.65, 0xffffffff, " Else choose Grass, Slate, Clay button.");
for i=1, #button_names do
if button_names[i] == "Grass" then
x = 30;
y = 10;
bsize = 130;
elseif button_names[i] == "Grass Small Icon" then
x = 30;
y = 40;
bsize = 130;
elseif button_names[i] == "Slate" then
x = 30;
y = 70;
bsize = 130;
elseif button_names[i] == "Slate Small Icon" then
x = 30;
y = 100;
bsize = 130;
elseif button_names[i] == "Clay" then
x = 30;
y = 130;
bsize = 130;
elseif button_names[i] == "Clay Small Icon" then
x = 30;
y = 160;
bsize = 130;
end
if lsButtonText(x, y, 0, 250, 0xe5d3a2ff, button_names[i]) then
image_name = button_names[i];
is_done = 1;
end
end
if lsButtonText(lsScreenX - 110, lsScreenY - 30, z, 100, 0xFFFFFFff, "End script") then
error "Clicked End Script button";
end
lsDoFrame();
lsSleep(10);
end
if image_name == "Grass" then
gatherGrass();
elseif image_name == "Grass Small Icon" then
gatherGrassSmall();
elseif image_name == "Slate" then
gatherSlate();
elseif image_name == "Slate Small Icon" then
gatherSlateSmall();
elseif image_name == "Clay" then
gatherClay();
elseif image_name == "Clay Small Icon" then
gatherClaySmall();
end
end
end
| mit |
Laterus/Darkstar-Linux-Fork | scripts/zones/Windurst_Woods/npcs/Orlaine.lua | 1 | 1262 | -----------------------------------
-- Area: Windurst Woods
-- NPC: Orlaine
-- Chocobo Vendor
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
price = 100;
gil = player:getGil();
hasLicense = player:hasKeyItem(CHOCOBO_LICENSE);
level = player:getMainLvl();
if (hasLicense and level >= 15) then
player:startEvent(0x2712,price,gil);
else
player:startEvent(0x2715,price,gil);
end
end;
-----------------------------------
-- onEventFinish Action
-----------------------------------
function onEventFinish(player,csid,option)
--print("CSID:",csid);
--print("OPTION:",option);
price = 100;
level = player:getMainLvl();
if (csid == 0x2712 and option == 0) then
if (level >= 20) then
player:addStatusEffect(EFFECT_CHOCOBO,1,0,1800);
else
player:addStatusEffect(EFFECT_CHOCOBO,1,0,900);
end
player:delGil(price);
player:setPos(-122,-4,-520,0,0x74);
end
end; | gpl-3.0 |
premek/brick-script | test/runtime.lua | 1 | 1040 | local luaunit = require('test.luaunit')
local parser = require('brickscript.parser')
local Runtime = require('brickscript.runtime')
function testAssign() doTest('assign') end
function testUpdate() doTest('update') end
function testBind() doTest('bind') end
function testList() doTest('list') end
function testCall() doTest('call') end
function testBitmap() doTest('bitmap') end
function testComment() doTest('comment') end
function testNumber() doTest('number') end
function doTest(name)
local tests = require ('test.runtime.'..name)
print('\n\n\nRT Test:', name)
for i, test in pairs(tests) do
print('\nSubtest: ', i)
local runtime = Runtime()
if test.configure then test.configure(runtime) end
local code = test[1]
print('code:\n'..code)
local tree = parser:match(code)
print('parsed: ', luaunit.prettystr(tree))
local result = runtime.run(tree)
print('result: ', result)
luaunit.assertEquals(result, test[2])
end
end
-- FIXME tests and runtime logging
os.exit( luaunit.LuaUnit.run() )
| apache-2.0 |
TerminalShell/zombiesurvival | entities/effects/gib_player.lua | 1 | 2328 | util.PrecacheSound("physics/flesh/flesh_bloody_break.wav")
local function CollideCallback(oldparticle, hitpos, hitnormal)
oldparticle:SetDieTime(0)
local pos = hitpos + hitnormal
if math.random(3) == 3 then
sound.Play("physics/flesh/flesh_squishy_impact_hard"..math.random(4)..".wav", hitpos, 50, math.Rand(95, 105))
end
util.Decal("Blood", pos, hitpos - hitnormal)
end
local vecGravity = Vector(0, 0, -500)
function EFFECT:Init(data)
local ent = data:GetEntity()
if not ent:IsValid() then return end
ent:EmitSound("physics/flesh/flesh_bloody_break.wav")
local basepos = ent:GetPos()
local vel = ent:GetVelocity()
local dir = vel:GetNormalized()
local up = ent:GetUp()
local speed = math.Clamp(vel:Length() * 2, 512, 2048)
local emitter = ParticleEmitter(ent:LocalToWorld(ent:OBBCenter()))
emitter:SetNearClip(24, 32)
for boneid = 1, ent:GetBoneCount() - 1 do
local pos, ang = ent:GetBonePositionMatrixed(boneid)
if pos and pos ~= basepos then
for i=1, math.random(1, 3) do
local heading = (VectorRand():GetNormalized() + up + dir * 2) / 4
local particle = emitter:Add("noxctf/sprite_bloodspray"..math.random(8), pos + heading)
particle:SetVelocity(speed * math.Rand(0.5, 1) * heading)
particle:SetDieTime(math.Rand(3, 6))
particle:SetStartAlpha(200)
particle:SetEndAlpha(200)
particle:SetStartSize(math.Rand(3, 4))
particle:SetEndSize(2)
particle:SetRoll(math.Rand(0, 360))
particle:SetRollDelta(math.Rand(-20, 20))
particle:SetAirResistance(8)
particle:SetGravity(vecGravity)
particle:SetCollide(true)
particle:SetLighting(true)
particle:SetColor(255, 0, 0)
particle:SetCollideCallback(CollideCallback)
end
for i=1, 4 do
local particle = emitter:Add("noxctf/sprite_bloodspray"..math.random(8), pos)
particle:SetVelocity(math.Rand(0.5, 4) * (VectorRand():GetNormalized() + dir))
particle:SetDieTime(math.Rand(0.75, 2))
particle:SetStartAlpha(230)
particle:SetEndAlpha(0)
particle:SetStartSize(math.Rand(4, 5))
particle:SetEndSize(3)
particle:SetRoll(math.Rand(0, 360))
particle:SetRollDelta(math.Rand(-1, 1))
particle:SetLighting(true)
particle:SetColor(255, 0, 0)
end
end
end
emitter:Finish()
end
function EFFECT:Think()
return false
end
function EFFECT:Render()
end
| gpl-3.0 |
jamesofarrell/TheFatController | control.lua | 1 | 51629 | require "defines"
require "util"
MOD_NAME = "TheFatController"
local function init_global()
global = global or {}
global.guiSettings = global.guiSettings or {}
global.trainsByForce = global.trainsByForce or {}
global.character = global.charactor or {}
global.unlocked = global.unlocked or false
global.unlockedByForce = global.unlockedByForce or {}
global.version = "0.3.1"
end
defaultGuiSettings = { alarm={active=false,noPath=true,timeAtSignal=true,timeToStation=true},
displayCount=9,
fatControllerButtons = {},
fatControllerGui = {},
page = 2,
pageCount = 5,
stationFilterList = {}
}
local function init_player(player)
global.guiSettings[player.index] = global.guiSettings[player.index] or util.table.deepcopy(defaultGuiSettings)
if global.unlockedByForce[player.force.name] then
init_gui(player)
end
end
local function init_players()
for i,player in pairs(game.players) do
init_player(player)
end
end
local function init_force(force)
global.trainsByForce[force.name] = global.trainsByForce[force.name] or {}
if force.technologies["rail-signals"].researched then
global.unlockedByForce[force.name] = true
global.unlocked = true
register_events()
for i,p in pairs(force.players) do
init_player(p)
end
end
end
local function init_forces()
for i, force in pairs(game.forces) do
init_force(force)
end
end
local function on_init()
init_global()
init_forces()
end
local function on_load()
if global.unlocked then
register_events()
end
end
-- run once
local function on_configuration_changed(data)
if not data or not data.mod_changes then
return
end
if data.mod_changes[MOD_NAME] then
local newVersion = data.mod_changes[MOD_NAME].new_version
local oldVersion = data.mod_changes[MOD_NAME].old_version
if oldVersion then
if oldVersion < "0.3.14" then
-- Kill all old versions of TFC
if global.fatControllerGui ~= nil or global.fatControllerButtons ~= nil then
destroyGui(global.fatControllerGui)
destroyGui(global.fatControllerButtons)
end
for i,p in pairs(game.players) do
destroyGui(p.gui.top.fatControllerButtons)
destroyGui(p.gui.left.fatController)
end
global = nil
end
end
init_global()
init_forces()
init_players()
if not oldVersion or oldVersion < "0.3.14" then
findTrains()
end
global.version = newVersion
end
--check for other mods
end
local function on_player_created(event)
init_player(game.players[event.player_index])
end
local function on_force_created(event)
init_force(event.force)
end
local function on_forces_merging(event)
end
script.on_init(on_init)
script.on_load(on_load)
script.on_configuration_changed(on_configuration_changed)
script.on_event(defines.events.on_player_created, on_player_created)
script.on_event(defines.events.on_force_created, on_force_created)
script.on_event(defines.events.on_forces_merging, on_forces_merging)
function register_events()
script.on_event(defines.events.on_train_changed_state, on_train_changed_state)
script.on_event(defines.events.on_tick, onTickAfterUnlocked)
script.on_event(defines.events.on_gui_click, on_gui_click)
end
--Called if tech is unlocked
function init_gui(player)
debugLog("Init: " .. player.name .. " - " .. player.force.name)
if player.gui.top.fatControllerButtons ~= nil then
return
end
local guiSettings = global.guiSettings[player.index]
local forceName = player.force.name
guiSettings.stationFilterList = buildStationFilterList(global.trainsByForce[player.force.name])
debugLog("create guis")
if player.gui.left.fatController == nil then
guiSettings.fatControllerGui = player.gui.left.add({ type="flow", name="fatController", direction="vertical"})--, style="fatcontroller_thin_flow"}) --caption="Fat Controller",
else
guiSettings.fatControllerGui = player.gui.left.fatController
end
if player.gui.top.fatControllerButtons == nil then
guiSettings.fatControllerButtons = player.gui.top.add({ type="flow", name="fatControllerButtons", direction="horizontal", style="fatcontroller_thin_flow"})
else
guiSettings.fatControllerButtons = player.gui.top.fatControllerButtons
end
if guiSettings.fatControllerButtons.toggleTrainInfo == nil then
guiSettings.fatControllerButtons.add({type="button", name="toggleTrainInfo", caption = {"text-trains-collapsed"}, style="fatcontroller_button_style"})
end
if guiSettings.fatControllerGui.trainInfo ~= nil then
newTrainInfoWindow(guiSettings)
updateTrains(global.trainsByForce[forceName])
end
guiSettings.pageCount = getPageCount(global.trainsByForce[forceName], guiSettings)
filterTrainInfoList(global.trainsByForce[forceName], guiSettings.activeFilterList)
updateTrains(global.trainsByForce[forceName])
refreshTrainInfoGui(global.trainsByForce[forceName], guiSettings, player.character)
return guiSettings
end
script.on_event(defines.events.on_research_finished, function(event)
local status, err = pcall(on_research_finished, event)
if err then debugDump(err,true) end
end)
function on_research_finished(event)
if event.research.name == "rail-signals" then
global.unlockedByForce[event.research.force.name] = true
global.unlocked = true
register_events() ;
for _, p in pairs(event.research.force.players) do
init_gui(p)
end
end
end
onTickAfterUnlocked = function(event)
local status, err = pcall(function()
if event.tick%60==13 then
local updateGui = false
for i,guiSettings in pairs(global.guiSettings) do
if guiSettings.fatControllerGui ~= nil and guiSettings.fatControllerGui.trainInfo ~= nil then
updateGui = true
end
end
if updateGui then
debugLog("updateGUI")
for _,trains in pairs(global.trainsByForce) do
updateTrains(trains)
end
refreshAllTrainInfoGuis(global.trainsByForce, global.guiSettings, game.players, false)
for i,player in pairs(game.players) do
refreshTrainInfoGui(global.trainsByForce[player.force.name], global.guiSettings[i], player.character)
global.guiSettings[i].pageCount = getPageCount(global.trainsByForce[player.force.name], global.guiSettings[i])
end
end
end
--handle remote camera
for i,guiSettings in pairs(global.guiSettings) do
if guiSettings.followEntity ~= nil then -- Are we in remote camera mode?
if not guiSettings.followEntity.valid or game.players[i].vehicle == nil then
swapPlayer(game.players[i], global.character[i])
if guiSettings.fatControllerButtons ~= nil and guiSettings.fatControllerButtons.returnToPlayer ~= nil then
guiSettings.fatControllerButtons.returnToPlayer.destroy()
end
if not guiSettings.followEntity.valid then
removeTrainInfoFromEntity(global.trainsByForce[game.players[i].force.name], guiSettings.followEntity)
newTrainInfoWindow(guiSettings)
refreshTrainInfoGui(global.trainsByForce[game.players[i].force.name], guiSettings, game.players[i].character)
end
global.character[i] = nil
guiSettings.followEntity = nil
elseif global.character[i] and global.character[i].valid and guiSettings.fatControllerButtons ~= nil and guiSettings.fatControllerButtons.returnToPlayer == nil then
guiSettings.fatControllerButtons.add({ type="button", name="returnToPlayer", caption={"text-player"}, style = "fatcontroller_selected_button"})
--game.players[1].teleport(global.followEntity.position)
elseif global.character[i] ~= nil and not global.character[i].valid then
game.set_game_state({gamefinished=true, playerwon=false})
end
end
end
-- on_the_path = 0,
-- -- had path and lost it - must stop
-- path_lost = 1,
-- -- doesn't have anywhere to go
-- no_schedule = 2,
-- has no path and is stopped
-- no_path = 3,
-- -- braking before the railSignal
-- arrive_signal = 4,
-- wait_signal = 5,
-- -- braking before the station
-- arrive_station = 6,
-- wait_station = 7,
-- -- switched to the manual control and has to stop
-- manual_control_stop = 8,
-- -- can move if user explicitly sits in and rides the train
-- manual_control = 9,
-- -- train was switched to auto control but it is moving and needs to be stopped
-- stop_for_auto_control = 10
if event.tick%120 == 37 then
local alarmState = {}
alarmState.timeToStation = false
alarmState.timeAtSignal = false
alarmState.noPath = false
local newAlarm = false
for forceName,trains in pairs(global.trainsByForce) do
for i,trainInfo in pairs(trains) do
local alarmSet = false
if trainInfo.lastState == 1 or trainInfo.lastState == 3 then
--game.players[1].print("No Path " .. i .. " " .. game.tick)
if not trainInfo.alarm then
alarmState.noPath = true
newAlarm = true
trainInfo.updated = true
end
alarmSet = true
trainInfo.alarm = true
end
-- 36000, 10 minutes
if trainInfo.lastState ~= 7 and trainInfo.lastStateStation ~= nil and (trainInfo.lastStateStation + 36000 < game.tick and (trainInfo.lastState ~= 2 or trainInfo.lastState ~= 8 or trainInfo.lastState ~= 9)) then
if not trainInfo.alarm then
alarmState.timeToStation = true
newAlarm = true
trainInfo.updated = true
end
alarmSet = true
trainInfo.alarm = true
end
-- 72002 minutes lol, wtf?
if trainInfo.lastState == 5 and (trainInfo.lastStateTick ~= nil and trainInfo.lastStateTick + 7200 < game.tick ) then
if not trainInfo.alarm then
alarmState.timeAtSignal = true
newAlarm = true
trainInfo.updated = true
end
alarmSet = true
trainInfo.alarm = true
end
if not alarmSet then
if trainInfo.alarm then
trainInfo.updated = true
end
trainInfo.alarm = false
end
end
end
for i,guiSettings in pairs(global.guiSettings) do
if guiSettings.alarm == nil or guiSettings.alarm.noPath == nil then
guiSettings.alarm = {}
guiSettings.alarm.timeToStation = true
guiSettings.alarm.timeAtSignal = true
guiSettings.alarm.noPath = true
end
if (guiSettings.alarm.timeToStation or guiSettings.alarm.timeAtSignal or guiSettings.alarm.noPath) and newAlarm then
if guiSettings.alarm.timeToStation and alarmState.timeToStation then
guiSettings.alarm.active = true
alertPlayer(game.players[i], guiSettings, game.tick, ({"msg-alarm-tolongtostation"}))
end
if guiSettings.alarm.timeAtSignal and alarmState.timeAtSignal then
guiSettings.alarm.active = true
alertPlayer(game.players[i], guiSettings, game.tick, ({"msg-alarm-tolongatsignal"}))
end
if guiSettings.alarm.noPath and alarmState.noPath then
guiSettings.alarm.active = true
alertPlayer(game.players[i], guiSettings, game.tick, ({"msg-alarm-nopath"}))
end
else
guiSettings.alarm.active = false
end
end
end
end)
if err then debugDump(err,true) end
--if event.tick%30==4 and global.fatControllerGui.trainInfo ~= nil then
--refreshTrainInfoGui(global.trains, global.fatControllerGui.trainInfo, global.guiSettings, game.players[1].character)
--end
end
function alertPlayer(player,guiSettings,tick,message)
if player ~= nil and guiSettings ~= nil and guiSettings.alarm ~= nil and guiSettings.alarm.active and (guiSettings.alarm.lastMessage == nil or guiSettings.alarm.lastMessage + 120 < tick) then
guiSettings.lastMessage = tick
player.print(message)
end
end
function destroyGui(guiA)
if guiA ~= nil and guiA.valid then
guiA.destroy()
end
end
function buildStationFilterList(trains)
local newList = {}
if trains ~= nil then
for i, trainInfo in pairs(trains) do
-- if trainInfo.group ~= nil then
-- newList[trainInfo.group] = true
-- end
if trainInfo.stations ~= nil then
for station, value in pairs(trainInfo.stations) do
--debugLog(station)
newList[station] = true
end
end
end
end
return newList
end
function getLocomotives(train)
if train ~= nil and train.valid then
local locos = {}
for i,carriage in pairs(train.carriages) do
if carriage ~= nil and carriage.valid and isTrainType(carriage.type) then
table.insert(locos, carriage)
end
end
return locos
end
end
function getNewTrainInfo(train)
if train ~= nil then
local carriages = train.carriages
if carriages ~= nil and carriages[1] ~= nil and carriages[1].valid then
local newTrainInfo = {}
newTrainInfo.train = train
--newTrainInfo.firstCarriage = getFirstCarriage(train)
newTrainInfo.locomotives = getLocomotives(train)
--newTrainInfo.display = true
return newTrainInfo
end
end
end
entityBuilt = function(event)
local entity = event.created_entity
if entity.type == "locomotive" and global.unlocked then --or entity.type == "cargo-wagon"
getTrainInfoOrNewFromEntity(global.trainsByForce[entity.force.name], entity)
end
end
script.on_event(defines.events.on_built_entity, entityBuilt)
script.on_event(defines.events.on_robot_built_entity, entityBuilt)
-- -- normal state - following the path
-- on_the_path = 0,
-- -- had path and lost it - must stop
-- path_lost = 1,
-- -- doesn't have anywhere to go
-- no_schedule = 2,
-- -- has no path and is stopped
-- no_path = 3,
-- -- braking before the railSignal
-- arrive_signal = 4,
-- wait_signal = 5,
-- -- braking before the station
-- arrive_station = 6,
-- wait_station = 7,
-- -- switched to the manual control and has to stop
-- manual_control_stop = 8,
-- -- can move if user explicitly sits in and rides the train
-- manual_control = 9,
-- -- train was switched to auto control but it is moving and needs to be stopped
-- stop_for_auto_control = 10
function on_train_changed_state(event)
local status, err = pcall(function()
--debugLog("State Change - " .. game.tick)
local train = event.train
local entity = train.carriages[1]
local trains = global.trainsByForce[entity.force.name]
local trainInfo = getTrainInfoOrNewFromEntity(trains, entity)
if trainInfo ~= nil then
local newtrain = false
if trainInfo.updated == nil then
newtrain = true
else
end
updateTrainInfo(trainInfo,game.tick)
if newtrain then
for i,player in pairs(game.players) do
global.guiSettings[i].pageCount = getPageCount(trains, global.guiSettings[i])
end
end
refreshAllTrainInfoGuis(global.trainsByForce, global.guiSettings, game.players, newtrain)
end
end)
if err then debugDump(err,true) end
end
function getTrainInfoOrNewFromTrain(trains, train)
if trains ~= nil then
for i, trainInfo in pairs(trains) do
if trainInfo ~= nil and trainInfo.train and trainInfo.train.valid and train == trainInfo.train then
return trainInfo
end
end
local newTrainInfo = getNewTrainInfo(train)
table.insert(trains, newTrainInfo)
return newTrainInfo
end
end
function getTrainInfoOrNewFromEntity(trains, entity)
local trainInfo = getTrainInfoFromEntity(trains, entity)
if trainInfo == nil then
local newTrainInfo = getNewTrainInfo(entity.train)
table.insert(trains, newTrainInfo)
return newTrainInfo
else
return trainInfo
end
end
function on_gui_click(event)
local status, err = pcall(function()
local refreshGui = false
local newInfoWindow = false
local rematchStationList = false
local guiSettings = global.guiSettings[event.element.player_index]
local player = game.players[event.element.player_index]
local trains = global.trainsByForce[player.force.name]
debugLog("CLICK! " .. event.element.name .. game.tick)
if guiSettings.alarm == nil then
guiSettings.alarm = {}
end
if event.element.name == "toggleTrainInfo" then
if guiSettings.fatControllerGui.trainInfo == nil then
newInfoWindow = true
refreshGui = true
event.element.caption = {"text-trains"}
else
guiSettings.fatControllerGui.trainInfo.destroy()
event.element.caption = {"text-trains-collapsed"}
end
elseif event.element.name == "returnToPlayer" then
if global.character[event.element.player_index] ~= nil then
if player.vehicle ~= nil then
player.vehicle.passenger = nil
end
swapPlayer(player, global.character[event.element.player_index])
global.character[event.element.player_index] = nil
event.element.destroy()
guiSettings.followEntity = nil
end
elseif endsWith(event.element.name,"_toggleManualMode") then
local trainInfo = getTrainInfoFromElementName(trains, event.element.name)
if trainInfo ~= nil and trainInfo.train ~= nil and trainInfo.train.valid then
trainInfo.train.manual_mode = not trainInfo.train.manual_mode
swapCaption(event.element, "ll", ">")
end
elseif endsWith(event.element.name,"_toggleFollowMode") then
local trainInfo = getTrainInfoFromElementName(trains, event.element.name)
if trainInfo ~= nil and trainInfo.train ~= nil and trainInfo.train.valid then
if global.character[event.element.player_index] == nil then --Move to train
if trainInfo.train.carriages[1].passenger ~= nil then
player.print({"msg-intrain"})
else
global.character[event.element.player_index] = player.character
guiSettings.followEntity = trainInfo.train.carriages[1] -- HERE
--fatControllerEntity =
swapPlayer(player,newFatControllerEntity(player))
--event.element.style = "fatcontroller_selected_button"
event.element.caption = "X"
trainInfo.train.carriages[1].passenger = player.character
end
elseif guiSettings.followEntity ~= nil and trainInfo.train ~= nil and trainInfo.train.valid then
if player.vehicle ~= nil then
player.vehicle.passenger = nil
end
if guiSettings.followEntity == trainInfo.train.carriages[1] or trainInfo.train.carriages[1].passenger ~= nil then --Go back to player
swapPlayer(player, global.character[event.element.player_index])
--event.element.style = "fatcontroller_button_style"
event.element.caption = "c"
if guiSettings.fatControllerButtons ~= nil and guiSettings.fatControllerButtons.returnToPlayer ~= nil then
guiSettings.fatControllerButtons.returnToPlayer.destroy()
end
global.character[event.element.player_index] = nil
guiSettings.followEntity = nil
else -- Go to different train
guiSettings.followEntity = trainInfo.train.carriages[1] -- AND HERE
--event.element.style = "fatcontroller_selected_button"
event.element.caption = "X"
trainInfo.train.carriages[1].passenger = player.character
--game.players[1].vehicle = trainInfo.train.carriages[1]
end
end
end
elseif event.element.name == "page_back" then
if guiSettings.page > 1 then
guiSettings.page = guiSettings.page - 1
--global.fatControllerGui.trainInfo.trainInfoControls.page_number.caption = global.guiSettings.page
--newTrainInfoWindow(global.fatControllerGui, global.guiSettings)
--refreshTrainInfoGui(global.trains, global.fatControllerGui.trainInfo, global.guiSettings)
newInfoWindow = true
refreshGui = true
end
elseif event.element.name == "page_forward" then
if guiSettings.page < getPageCount(trains, guiSettings) then
guiSettings.page = guiSettings.page + 1
--debugLog(global.guiSettings.page)
--newTrainInfoWindow(global.fatControllerGui, global.guiSettings)
--refreshTrainInfoGui(global.trains, global.fatControllerGui.trainInfo, global.guiSettings)
newInfoWindow = true
refreshGui = true
end
elseif event.element.name == "page_number" then
togglePageSelectWindow(player.gui.center, guiSettings)
elseif event.element.name == "pageSelectOK" then
local gui = player.gui.center.pageSelect
if gui ~= nil then
local newInt = tonumber(gui.pageSelectValue.text)
if newInt then
if newInt < 1 then
newInt = 1
elseif newInt > 50 then
newInt = 50
end
guiSettings.displayCount = newInt
guiSettings.pageCount = getPageCount(trains, guiSettings)
guiSettings.page = 1
refreshGui = true
newInfoWindow = true
else
player.print({"msg-notanumber"})
end
gui.destroy()
end
elseif event.element.name == "toggleStationFilter" then
guiSettings.stationFilterList = buildStationFilterList(trains)
toggleStationFilterWindow(player.gui.center, guiSettings)
elseif event.element.name == "clearStationFilter" or event.element.name == "stationFilterClear" then
if guiSettings.activeFilterList ~= nil then
guiSettings.activeFilterList = nil
rematchStationList = true
newInfoWindow = true
refreshGui = true
end
if player.gui.center.stationFilterWindow ~= nil then
player.gui.center.stationFilterWindow.destroy()
end
elseif event.element.name == "stationFilterOK" then
local gui = player.gui.center.stationFilterWindow
if gui ~= nil and gui.checkboxGroup ~= nil then
local newFilter = {}
local listEmpty = true
for station,value in pairs(guiSettings.stationFilterList) do
local checkboxA = gui.checkboxGroup[station .. "_stationFilter"]
if checkboxA ~= nil and checkboxA.state then
listEmpty = false
--debugLog(station)
newFilter[station] = true
end
end
if not listEmpty then
guiSettings.activeFilterList = newFilter
--glo.filteredTrains = buildFilteredTrainInfoList(global.trains, global.guiSettings.activeFilterList)
else
guiSettings.activeFilterList = nil
end
gui.destroy()
guiSettings.page = 1
rematchStationList = true
newInfoWindow = true
refreshGui = true
end
elseif endsWith(event.element.name,"_stationFilter") then
local stationName = string.gsub(event.element.name, "_stationFilter", "")
if event.element.state then
if guiSettings.activeFilterList == nil then
guiSettings.activeFilterList = {}
end
guiSettings.activeFilterList[stationName] = true
elseif guiSettings.activeFilterList ~= nil then
guiSettings.activeFilterList[stationName] = nil
if tableIsEmpty(guiSettings.activeFilterList) then
guiSettings.activeFilterList = nil
end
end
--debugLog(event.element.name)
guiSettings.page = 1
rematchStationList = true
newInfoWindow = true
refreshGui = true
--alarmOK alarmTimeToStation alarmTimeAtSignal alarmNoPath alarmButton
elseif event.element.name == "alarmButton" or event.element.name == "alarmOK" then
toggleAlarmWindow(player.gui.center, guiSettings)
elseif event.element.name == "alarmTimeToStation" then
guiSettings.alarm.timeToStation = event.element.state
elseif event.element.name == "alarmTimeAtSignal" then
guiSettings.alarm.timeAtSignal = event.element.state
elseif event.element.name == "alarmNoPath" then
guiSettings.alarm.noPath = event.element.state
end
if rematchStationList then
filterTrainInfoList(trains, guiSettings.activeFilterList)
guiSettings.pageCount = getPageCount(trains, guiSettings)
end
if newInfoWindow then
newTrainInfoWindow(guiSettings)
end
if refreshGui then
refreshTrainInfoGui(trains, guiSettings, player.character)
end
end)
if err then debugDump(err,true) end
end
-- function swapStyle(guiElement, styleA, styleB)
-- if guiElement ~= nil and styleA ~= nil and styleB ~= nil then
-- if guiElement.style == styleA then
-- guiElement.style = styleB
-- elseif guiElement.style == styleB then
-- guiElement.style = styleA
-- end
-- end
-- end
function swapCaption(guiElement, captionA, captionB)
if guiElement ~= nil and captionA ~= nil and captionB ~= nil then
if guiElement.caption == captionA then
guiElement.caption = captionB
elseif guiElement.caption == captionB then
guiElement.caption = captionA
end
end
end
function tableIsEmpty(tableA)
if tableA ~= nil then
for i,v in pairs(tableA) do
return false
end
end
return true
end
function toggleStationFilterWindow(gui, guiSettings)
if gui ~= nil then
if gui.stationFilterWindow == nil then
--local sortedList = table.sort(a)
local window = gui.add({type="frame", name="stationFilterWindow", caption={"msg-stationFilter"}, direction="vertical" }) --style="fatcontroller_thin_frame"})
window.add({type="table", name="checkboxGroup", colspan=3})
for name, value in pairsByKeys(guiSettings.stationFilterList) do
if guiSettings.activeFilterList ~= nil and guiSettings.activeFilterList[name] then
window.checkboxGroup.add({type="checkbox", name=name .. "_stationFilter", caption=name, state=true}) --style="filter_group_button_style"})
else
window.checkboxGroup.add({type="checkbox", name=name .. "_stationFilter", caption=name, state=false}) --style="filter_group_button_style"})
end
end
window.add({type="flow", name="buttonFlow"})
window.buttonFlow.add({type="button", name="stationFilterClear", caption={"msg-Clear"}})
window.buttonFlow.add({type="button", name="stationFilterOK", caption={"msg-OK"}})
else
gui.stationFilterWindow.destroy()
end
end
end
function togglePageSelectWindow(gui, guiSettings)
if gui ~= nil then
if gui.pageSelect == nil then
local window = gui.add({type="frame", name="pageSelect", caption={"msg-displayCount"}, direction="vertical" }) --style="fatcontroller_thin_frame"})
window.add({type="textfield", name="pageSelectValue", text=guiSettings.displayCount .. ""})
window.pageSelectValue.text = guiSettings.displayCount .. ""
window.add({type="button", name="pageSelectOK", caption={"msg-OK"}})
else
gui.pageSelect.destroy()
end
end
end
function toggleAlarmWindow(gui, guiSettings)
if gui ~= nil then
if gui.alarmWindow == nil then
local window = gui.add({type="frame",name="alarmWindow", caption={"text-alarmwindow"}, direction="vertical" })
local stateTimeToStation = true
if guiSettings.alarm ~= nil and not guiSettings.alarm.timeToStation then
stateTimeToStation = false
end
window.add({type="checkbox", name="alarmTimeToStation", caption={"text-alarmtimetostation"}, state=stateTimeToStation}) --style="filter_group_button_style"})
local stateTimeAtSignal = true
if guiSettings.alarm ~= nil and not guiSettings.alarm.timeAtSignal then
stateTimeAtSignal = false
end
window.add({type="checkbox", name="alarmTimeAtSignal", caption={"text-alarmtimeatsignal"}, state=stateTimeAtSignal}) --style="filter_group_button_style"})
local stateNoPath = true
if guiSettings.alarm ~= nil and not guiSettings.alarm.noPath then
stateNoPath = false
end
window.add({type="checkbox", name="alarmNoPath", caption={"text-alarmtimenopath"}, state=stateNoPath}) --style="filter_group_button_style"})
window.add({type="button", name="alarmOK", caption={"msg-OK"}})
else
gui.alarmWindow.destroy()
end
end
end
function getPageCount(trains, guiSettings)
local trainCount = 0
for i,trainInfo in pairs(trains) do
if guiSettings.activeFilterList == nil or trainInfo.matchesStationFilter then
trainCount = trainCount + 1
end
end
return math.floor((trainCount - 1) / guiSettings.displayCount) + 1
end
local onEntityDied = function (event)
if global.unlocked and global.guiSettings ~= nil then
for forceName,trains in pairs(global.trainsByForce) do
updateTrains(trains)
end
for i, player in pairs(game.players) do
local guiSettings = global.guiSettings[i]
if guiSettings.followEntity ~= nil and guiSettings.followEntity == event.entity then --Go back to player
if game.players[i].vehicle ~= nil then
game.players[i].vehicle.passenger = nil
end
swapPlayer(game.players[i], global.character[i])
if guiSettings.fatControllerButtons.returnToPlayer ~= nil then
guiSettings.fatControllerButtons.returnToPlayer.destroy()
end
global.character[i] = nil
guiSettings.followEntity = nil
end
end
refreshAllTrainInfoGuis(global.trainsByForce, global.guiSettings, game.players, true)
end
end
function refreshAllTrainInfoGuis(trainsByForce, guiSettings, players, destroy)
for i,player in pairs(players) do
--local trainInfo = guiSettings[i].fatControllerGui.trainInfo
if guiSettings[i] ~= nil and guiSettings[i].fatControllerGui.trainInfo ~= nil then
if destroy then
guiSettings[i].fatControllerGui.trainInfo.destroy()
newTrainInfoWindow(guiSettings[i])
end
refreshTrainInfoGui(trainsByForce[player.force.name], guiSettings[i], player.character)
end
end
end
script.on_event(defines.events.on_entity_died, onEntityDied)
script.on_event(defines.events.on_preplayer_mined_item, onEntityDied)
function swapPlayer(player, character)
--player.teleport(character.position)
if player.character ~= nil and player.character.valid and player.character.name == "fatcontroller" then
player.character.destroy()
end
player.character = character
end
function isTrainType(type)
if type == "locomotive" then
return true
end
return false
end
function getTrainInfoFromElementName(trains, elementName)
for i, trainInfo in pairs(trains) do
if trainInfo ~= nil and trainInfo.guiName ~= nil and startsWith(elementName, trainInfo.guiName .. "_") then
return trainInfo
end
end
end
function getTrainInfoFromEntity(trains, entity)
if trains ~= nil then
for i, trainInfo in pairs(trains) do
if trainInfo ~= nil and trainInfo.train ~= nil and trainInfo.train.valid and entity == trainInfo.train.carriages[1] then
return trainInfo
end
end
end
end
function removeTrainInfoFromElementName(trains, elementName)
for i, trainInfo in pairs(trains) do
if trainInfo ~= nil and trainInfo.guiName ~= nil and startsWith(elementName, trainInfo.guiName .. "_") then
table.remove(trains, i)
return
end
end
end
function removeTrainInfoFromEntity(trains, entity)
for i, trainInfo in pairs(trains) do
if trainInfo ~= nil and trainInfo.train ~= nil and trainInfo.train.valid and trainInfo.train.carriages[1] == entity then
table.remove(trains, i)
return
end
end
end
function getHighestInventoryCount(trainInfo)
local inventory = nil
if trainInfo ~= nil and trainInfo.train ~= nil and trainInfo.train.valid and trainInfo.train.carriages ~= nil then
local itemsCount = 0
local largestItem = {}
local items = trainInfo.train.get_contents() or {}
for i, carriage in pairs(trainInfo.train.carriages) do
if carriage and carriage.valid and carriage.name == "rail-tanker" then
debugLog("Looking for Oil!")
local liquid = remote.call("railtanker","getLiquidByWagon",carriage)
if liquid then
debugLog("Liquid!")
local name = liquid.type
local count = math.floor(liquid.amount)
if name then
if not items[name] then
items[name] = 0
end
items[name] = items[name] + count
end
end
end
end
for name, count in pairs(items) do
if largestItem.count == nil or largestItem.count < items[name] then
largestItem.name = name
largestItem.count = items[name]
end
itemsCount = itemsCount + 1
end
if largestItem.name ~= nil then
local isItem = game.item_prototypes[largestItem.name]
local displayName = isItem and isItem.localised_name or {"", largestItem.name}
local suffix = itemsCount > 1 and "..." or ""
inventory = {"", displayName,": ",largestItem.count, suffix}
else
inventory = ""
end
end
return inventory
end
function newFatControllerEntity(player)
return player.surface.create_entity({name="fatcontroller", position=player.position, force=player.force})
-- local entities = game.find_entities_filtered({area={{position.x, position.y},{position.x, position.y}}, name="fatcontroller"})
-- if entities[1] ~= nil then
-- return entities[1]
-- end
end
function newTrainInfoWindow(guiSettings)
if guiSettings == nil then
guiSettings = util.table.deepcopy({ displayCount = 9, page = 1})
end
local gui = guiSettings.fatControllerGui
if gui ~= nil and gui.trainInfo ~= nil then
gui.trainInfo.destroy()
end
local newGui
if gui ~= nil and gui.trainInfo ~= nil then
newGui = gui.trainInfo
else
newGui = gui.add({ type="flow", name="trainInfo", direction="vertical", style="fatcontroller_thin_flow"})
end
if newGui.trainInfoControls == nil then
newGui.add({type = "frame", name="trainInfoControls", direction="horizontal", style="fatcontroller_thin_frame"})
end
if newGui.trainInfoControls.pageButtons == nil then
newGui.trainInfoControls.add({type = "flow", name="pageButtons", direction="horizontal", style="fatcontroller_button_flow"})
end
if newGui.trainInfoControls.pageButtons.page_back == nil then
if guiSettings.page > 1 then
newGui.trainInfoControls.pageButtons.add({type="button", name="page_back", caption="<", style="fatcontroller_button_style"})
else
newGui.trainInfoControls.pageButtons.add({type="button", name="page_back", caption="<", style="fatcontroller_disabled_button"})
end
end
-- if guiSettings.page > 1 then
-- newGui.trainInfoControls.pageButtons.page_back.style = "fatcontroller_button_style"
-- else
-- newGui.trainInfoControls.pageButtons.page_back.style = "fatcontroller_disabled_button"
-- end
if newGui.trainInfoControls.pageButtons.page_number == nil then
newGui.trainInfoControls.pageButtons.add({type="button", name="page_number", caption=guiSettings.page .. "/" .. guiSettings.pageCount, style="fatcontroller_button_style"})
else
newGui.trainInfoControls.pageButtons.page_number.caption = guiSettings.page .. "/" .. guiSettings.pageCount
end
if newGui.trainInfoControls.pageButtons.page_forward == nil then
if guiSettings.page < guiSettings.pageCount then
newGui.trainInfoControls.pageButtons.add({type="button", name="page_forward", caption=">", style="fatcontroller_button_style"})
else
newGui.trainInfoControls.pageButtons.add({type="button", name="page_forward", caption=">", style="fatcontroller_disabled_button"})
end
end
-- if guiSettings.page < guiSettings.pageCount then
-- newGui.trainInfoControls.pageButtons.page_forward.style = "fatcontroller_button_style"
-- else
-- newGui.trainInfoControls.pageButtons.page_forward.style = "fatcontroller_disabled_button"
-- end
if newGui.trainInfoControls.filterButtons == nil then
newGui.trainInfoControls.add({type = "flow", name="filterButtons", direction="horizontal", style="fatcontroller_button_flow"})
end
if newGui.trainInfoControls.filterButtons.toggleStationFilter == nil then
if guiSettings.activeFilterList ~= nil then
newGui.trainInfoControls.filterButtons.add({type="button", name="toggleStationFilter", caption="s", style="fatcontroller_selected_button"})
else
newGui.trainInfoControls.filterButtons.add({type="button", name="toggleStationFilter", caption="s", style="fatcontroller_button_style"})
end
end
if newGui.trainInfoControls.filterButtons.clearStationFilter == nil then
--if guiSettings.activeFilterList ~= nil then
--newGui.trainInfoControls.filterButtons.add({type="button", name="clearStationFilter", caption="x", style="fatcontroller_selected_button"})
--else
newGui.trainInfoControls.filterButtons.add({type="button", name="clearStationFilter", caption="x", style="fatcontroller_button_style"})
--end
end
if newGui.trainInfoControls.alarm == nil then
newGui.trainInfoControls.add({type = "flow", name="alarm", direction="horizontal", style="fatcontroller_button_flow"})
end
if newGui.trainInfoControls.alarm.alarmButton == nil then
newGui.trainInfoControls.alarm.add({type="button", name="alarmButton", caption="!", style="fatcontroller_button_style"})
end
-- if guiSettings.activeFilterList ~= nil then
-- newGui.trainInfoControls.filterButtons.toggleStationFilter.style = "fatcontroller_selected_button"
-- newGui.trainInfoControls.filterButtons.clearStationFilter.style = "fatcontroller_button_style"
-- else
-- newGui.trainInfoControls.filterButtons.toggleStationFilter.style = "fatcontroller_button_style"
-- newGui.trainInfoControls.filterButtons.clearStationFilter.style = "fatcontroller_disabled_button"
-- end
return newGui
end
-- function getFirstCarriage(train)
-- if train ~= nil and train.valid then
-- for i, carriage in pairs(train.carriages) do
-- if carriage ~= nil and carriage.valid and isTrainType(carriage.type) then
-- return carriage
-- end
-- end
-- end
-- end
function getTrainFromLocomotives(locomotives)
if locomotives ~= nil then
for i,loco in pairs(locomotives) do
if loco ~= nil and loco.valid and loco.train ~= nil and loco.train.valid then
return loco.train
end
end
end
end
function isTrainInfoDuplicate(trains, trainInfoB, index)
--local trainInfoB = trains[index]
if trainInfoB ~= nil and trainInfoB.train ~= nil and trainInfoB.train.valid then
for i, trainInfo in pairs(trains) do
--debugLog(i)
if i ~= index and trainInfo.train ~= nil and trainInfo.train.valid and compareTrains(trainInfo.train, trainInfoB.train) then
return true
end
end
end
return false
end
function compareTrains(trainA, trainB)
if trainA ~= nil and trainA.valid and trainB ~= nil and trainB.valid and trainA.carriages[1] == trainB.carriages[1] then
return true
end
return false
end
function updateTrains(trains)
--if trains ~= nil then
for i, trainInfo in pairs(trains) do
--refresh invalid train objects
if trainInfo.train == nil or not trainInfo.train.valid then
trainInfo.train = getTrainFromLocomotives(trainInfo.locomotives)
trainInfo.locomotives = getLocomotives(trainInfo.train)
if isTrainInfoDuplicate(trains, trainInfo, i) then
trainInfo.train = nil
end
end
if (trainInfo.train == nil or not trainInfo.train.valid) then
table.remove(trains, i)
else
trainInfo.locomotives = getLocomotives(trainInfo.train)
updateTrainInfo(trainInfo, game.tick)
--debugLog(trainInfo.train.state)
end
end
--end
end
function updateTrainInfoIfChanged(trainInfo, field, value)
if trainInfo ~= nil and field ~= nil and trainInfo[field] ~= value then
trainInfo[field] = value
trainInfo.updated = true
return true
end
return false
end
function updateTrainInfo(trainInfo, tick)
if trainInfo ~= nil then
trainInfo.updated = false
if trainInfo.lastState == nil or trainInfo.lastState ~= trainInfo.train.state then
trainInfo.updated = true
if trainInfo.train.state == 7 then
trainInfo.lastStateStation = tick
end
trainInfo.lastState = trainInfo.train.state
trainInfo.lastStateTick = tick
end
updateTrainInfoIfChanged(trainInfo, "manualMode", trainInfo.train.manual_mode)
updateTrainInfoIfChanged(trainInfo, "speed", trainInfo.train.speed)
--SET InventoryText (trainInfo.train.state == 9 or trainInfo.train.state == 7
if (trainInfo.train.state == 7 or (trainInfo.train.state == 9 and trainInfo.train.speed == 0)) or not trainInfo.updatedInventory then
local tempInventory = getHighestInventoryCount(trainInfo)
trainInfo.updatedInventory = true
if tempInventory ~= nil then
updateTrainInfoIfChanged(trainInfo, "inventory", tempInventory)
end
end
--SET CurrentStationText
if trainInfo.train.schedule ~= nil and trainInfo.train.schedule.current ~= nil and trainInfo.train.schedule.current ~= 0 then
if trainInfo.train.schedule.records[trainInfo.train.schedule.current] ~= nil then
updateTrainInfoIfChanged(trainInfo, "currentStation", trainInfo.train.schedule.records[trainInfo.train.schedule.current].station)
else
updateTrainInfoIfChanged(trainInfo, "currentStation", "Auto")
end
end
if trainInfo.train.schedule ~= nil and trainInfo.train.schedule.records ~= nil and trainInfo.train.schedule.records[1] ~= nil then
trainInfo.stations = {}
-- if trainInfo.stations == nil then
-- end
for i, record in pairs(trainInfo.train.schedule.records) do
trainInfo.stations[record.station] = true
end
else
trainInfo.stations = nil
end
end
end
function containsEntity(entityTable, entityA)
if entityTable ~= nil and entityA ~= nil then
for i, entityB in pairs(entityTable) do
if entityB ~= nil and entityB == entityA then
return true
end
end
end
return false
end
function refreshTrainInfoGui(trains, guiSettings, character)
local gui = guiSettings.fatControllerGui.trainInfo
if gui ~= nil and trains ~= nil then
local removeTrainInfo = {}
local pageStart = ((guiSettings.page - 1) * guiSettings.displayCount) + 1
debugLog("Page:" .. pageStart)
local display = 0
local filteredCount = 0
for i, trainInfo in pairs(trains) do
local newGuiName = nil
if display < guiSettings.displayCount then
if guiSettings.activeFilterList == nil or trainInfo.matchesStationFilter then
filteredCount = filteredCount + 1
newGuiName = "Info" .. filteredCount
if filteredCount >= pageStart then
--removeGuiFromCount = removeGuiFromCount + 1
display = display + 1
if trainInfo.updated or gui[newGuiName] == nil then --trainInfo.guiName ~= newGuiName or
trainInfo.guiName = newGuiName
if gui[trainInfo.guiName] == nil then
gui.add({ type="frame", name=trainInfo.guiName, direction="horizontal", style="fatcontroller_thin_frame"})
end
local trainGui = gui[trainInfo.guiName]
--Add buttons
if trainGui.buttons == nil then
trainGui.add({type = "flow", name="buttons", direction="horizontal", style="fatcontroller_traininfo_button_flow"})
end
if trainGui.buttons[trainInfo.guiName .. "_toggleManualMode"] == nil then
trainGui.buttons.add({type="button", name=trainInfo.guiName .. "_toggleManualMode", caption="ll", style="fatcontroller_button_style"})
end
if trainInfo.manualMode then
--debugLog("Set >")
trainGui.buttons[trainInfo.guiName .. "_toggleManualMode"].caption = ">"
else
--debugLog("Set ll")
trainGui.buttons[trainInfo.guiName .. "_toggleManualMode"].caption = "ll"
end
if trainGui.buttons[trainInfo.guiName .. "_toggleFollowMode"] == nil then
trainGui.buttons.add({type="button", name=trainInfo.guiName .. "_toggleFollowMode", caption={"text-controlbutton"}, style="fatcontroller_button_style"})
end
--Add info
if trainGui.info == nil then
trainGui.add({type = "flow", name="info", direction="vertical", style="fatcontroller_thin_flow"})
end
if trainGui.info.topInfo == nil then
trainGui.info.add({type="label", name="topInfo", style="fatcontroller_label_style"})
end
if trainGui.info.bottomInfo == nil then
trainGui.info.add({type="label", name="bottomInfo", style="fatcontroller_label_style"})
end
local topString = ""
local station = trainInfo.currentStation
if station == nil then station = "" end
if trainInfo.lastState ~= nil then
if trainInfo.lastState == 1 or trainInfo.lastState == 3 then
topString = "No Path "-- .. trainInfo.lastState
elseif trainInfo.lastState == 2 then
topString = "Stopped"
elseif trainInfo.lastState == 5 then
topString = "Signal || " .. station
elseif trainInfo.lastState == 8 or trainInfo.lastState == 9 or trainInfo.lastState == 10 then
topString = "Manual"
if trainInfo.speed == 0 then
topString = topString .. ": " .. "Stopped" -- REPLACE WITH TRANSLAION
else
topString = topString .. ": " .. "Moving" -- REPLACE WITH TRANSLAION
end
elseif trainInfo.lastState == 7 then
topString = "Station || " .. station
else
topString = "Moving -> " .. station
end
end
local bottomString = ""
if trainInfo.inventory ~= nil then
bottomString = trainInfo.inventory
else
bottomString = ""
end
if guiSettings.alarm ~= nil and trainInfo.alarm then
topString = "! " .. topString
end
trainGui.info.topInfo.caption = topString
trainGui.info.bottomInfo.caption = bottomString
end
-- if character ~= nil and containsEntity(trainInfo.locomotives, character.opened) then --character.opened ~= nil and
-- gui[newGuiName].buttons[trainInfo.guiName .. "_removeTrain"].style = "fatcontroller_selected_button"
-- else
-- --debugLog("Failed: " .. i)
-- gui[newGuiName].buttons[trainInfo.guiName .. "_removeTrain"].style = "fatcontroller_button_style"
-- end
if character ~= nil and character.name == "fatcontroller" and containsEntity(trainInfo.locomotives, character.vehicle) then
gui[newGuiName].buttons[newGuiName .. "_toggleFollowMode"].style = "fatcontroller_selected_button"
gui[newGuiName].buttons[newGuiName .. "_toggleFollowMode"].caption = "X"
else
gui[newGuiName].buttons[newGuiName .. "_toggleFollowMode"].style = "fatcontroller_button_style"
gui[newGuiName].buttons[newGuiName .. "_toggleFollowMode"].caption = "c"
end
end
end
end
trainInfo.guiName = newGuiName
end
end
end
function filterTrainInfoList(trains, activeFilterList)
--if trains ~= nil then
for i,trainInfo in pairs(trains) do
if activeFilterList ~= nil then
trainInfo.matchesStationFilter = matchStationFilter(trainInfo, activeFilterList)
else
trainInfo.matchesStationFilter = true
end
end
--end
end
function matchStationFilter(trainInfo, activeFilterList)
local fullMatch = false
if trainInfo ~= nil and trainInfo.stations ~= nil then
for filter, value in pairs(activeFilterList) do
if trainInfo.stations[filter] then
fullMatch = true
else
return false
end
end
end
return fullMatch
end
-- function findTrainInfoFromEntity(trains, entity)
-- for i, trainInfo in pairs(trains) do
-- if train ~= nil and train.valid and train.carriages[1] ~= nil and trainInfo ~= nil and trainInfo.train.carriages[1] ~= nil and entity.equals(trainB.train.carriages[1]) then
-- return trainInfo
-- end
-- end
-- end
function trainInList(trains, train)
for i, trainInfo in pairs(trains) do
if train ~= nil and train.valid and train.carriages[1] ~= nil and trainInfo ~= nil and trainInfo.train ~= nil and trainInfo.train.valid and trainInfo.train.carriages[1] ~= nil and train.carriages[1] == trainInfo.train.carriages[1] then
return true
end
end
return false
end
-- function addNewTrainGui(gui, train)
-- if train ~= nil and train.valid and train.carriages[1] ~= nil and train.carriages[1].valid then
-- if gui.toggleTrain ~= nil then
-- gui.toggleTrain.destroy()
-- end
-- end
-- end
function matchStringInTable(stringA, tableA)
for i, stringB in pairs(tableA) do
if stringA == stringB then
return true
end
end
return false
end
function round(num, idp)
local mult = 10^(idp or 0)
return math.floor(num * mult + 0.5) / mult
end
function debugLog(message)
if false then -- set for debug
for i,player in pairs(game.players) do
player.print(message)
end
end
end
function endsWith(String,End)
return End=='' or string.sub(String,-string.len(End))==End
end
function startsWith(String,Start)
debugLog(String)
debugLog(Start)
return string.sub(String,1,string.len(Start))==Start
end
function pairsByKeys (t, f)
local a = {}
for n in pairs(t) do table.insert(a, n) end
table.sort(a, f)
local i = 0 -- iterator variable
local iter = function () -- iterator function
i = i + 1
if a[i] == nil then return nil
else return a[i], t[a[i]]
end
end
return iter
end
function debugDump(var, force)
if false or force then
for i,player in pairs(game.players) do
local msg
if type(var) == "string" then
msg = var
else
msg = serpent.dump(var, {name="var", comment=false, sparse=false, sortkeys=true})
end
player.print(msg)
end
end
end
function saveVar(var, name)
local var = var or global
local n = name or ""
game.write_file("FAT"..n..".lua", serpent.block(var, {name="global"}))
end
function findTrains()
-- create shorthand object for primary game surface
local surface = game.surfaces['nauvis']
-- determine map size
local min_x, min_y, max_x, max_y = 0, 0, 0, 0
for c in surface.get_chunks() do
if c.x < min_x then
min_x = c.x
elseif c.x > max_x then
max_x = c.x
end
if c.y < min_y then
min_y = c.y
elseif c.y > max_y then
max_y = c.y
end
end
-- create bounding box covering entire generated map
local bounds = {{min_x*32,min_y*32},{max_x*32,max_y*32}}
for _, loco in pairs(surface.find_entities_filtered{area=bounds, type="locomotive"}) do
getTrainInfoOrNewFromTrain(global.trainsByForce[loco.force.name], loco.train)
end
end
remote.add_interface("fat",
{
saveVar = function(name)
saveVar(global, name)
end,
})
| mit |
pakoito/ToME---t-engine4 | game/modules/tome/data/texts/tutorial/stats/stats3.lua | 3 | 1161 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
return [[
The final three important #GOLD#combat stats#WHITE# of your character are these:
#LIGHT_GREEN#Physical power: #WHITE#Your ability to inflict damage and effects with weapons (including fists).
#LIGHT_GREEN#Spellpower: #WHITE#Your ability to inflict damage and effects with spells.
#LIGHT_GREEN#Mindpower: #WHITE#Your ability to inflict damage and effects with your mind.
]]
| gpl-3.0 |
MessageSystems/momentum-scriptlets | dkimsign/dkimsign.lua | 1 | 1193 | require("msys.core");
require("msys.validate.opendkim");
require("msys.extended.message");
require("dkimsign_config");
local mod = {};
local function table_merge(defaults, specifics)
local new_t = {};
if !specifics then
return defaults;
end
for k, v in pairs(defaults) do
if specifics and !specifics[k] then
new_t[k] = v;
end;
end;
if specifics then
for k, v in pairs(specifics) do
new_t[k] = v;
end;
end;
return new_t;
end;
function mod:core_final_validation(msg, ac, vctx)
local sending_domain = msg:address_header("From", "domain");
local options = table_merge(msys.dkimsign_config.defaults, msys.dkimsign_config.domains[sending_domain[1]]);
-- Sign. Note that if a key isn’t found, this will just silently fail
msys.validate.opendkim.sign(msg, vctx, options);
-- Check if we’ve got an also_sign_domain
if msys.dkimsign_config.domains["__also_sign_domain__"] then
options = table_merge(msys.dkimsign_config.defaults, msys.dkimsign_config.domains["__also_sign_domain__"]);
msys.validate.opendkim.sign(msg, vctx, options);
end;
return msys.core.VALIDATE_CONT;
end;
msys.registerModule("dkimsign", mod);
| apache-2.0 |
vince06fr/prosody-modules | mod_muc_log_http/muc_log_http/mod_muc_log_http.lua | 32 | 22311 | module:depends("http");
local prosody = prosody;
local hosts = prosody.hosts;
local my_host = module:get_host();
local strchar = string.char;
local strformat = string.format;
local split_jid = require "util.jid".split;
local config_get = require "core.configmanager".get;
local urldecode = require "net.http".urldecode;
local http_event = require "net.http.server".fire_event;
local datamanager = require"core.storagemanager".olddm;
local data_load, data_getpath = datamanager.load, datamanager.getpath;
local datastore = "muc_log";
local url_base = "muc_log";
local config = nil;
local table, tostring, tonumber = table, tostring, tonumber;
local os_date, os_time = os.date, os.time;
local str_format = string.format;
local io_open = io.open;
local themes_parent = (module.path and module.path:gsub("[/\\][^/\\]*$", "") or (prosody.paths.plugins or "./plugins") .. "/muc_log_http") .. "/themes";
local lom = require "lxp.lom";
local lfs = require "lfs";
local html = {};
local theme;
-- Helper Functions
local p_encode = datamanager.path_encode;
local function store_exists(node, host, today)
if lfs.attributes(data_getpath(node, host, datastore .. "/" .. today), "mode") then return true; else return false; end
end
-- Module Definitions
local function html_escape(t)
if t then
t = t:gsub("<", "<");
t = t:gsub(">", ">");
t = t:gsub("(http://[%a%d@%.:/&%?=%-_#%%~]+)", function(h)
h = urlunescape(h)
return "<a href='" .. h .. "'>" .. h .. "</a>";
end);
t = t:gsub("\n", "<br />");
t = t:gsub("%%", "%%%%");
else
t = "";
end
return t;
end
function create_doc(body, title)
if not body then return "" end
body = body:gsub("%%", "%%%%");
return html.doc:gsub("###BODY_STUFF###", body)
:gsub("<title>muc_log</title>", "<title>"..(title and html_escape(title) or "Chatroom logs").."</title>");
end
function urlunescape (url)
url = url:gsub("+", " ")
url = url:gsub("%%(%x%x)", function(h) return strchar(tonumber(h,16)) end)
url = url:gsub("\r\n", "\n")
return url
end
local function urlencode(s)
return s and (s:gsub("[^a-zA-Z0-9.~_-]", function (c) return ("%%%02x"):format(c:byte()); end));
end
local function get_room_from_jid(jid)
local node, host = split_jid(jid);
local component = hosts[host];
if component then
local muc = component.modules.muc
if muc and rawget(muc,"rooms") then
-- We're running 0.9.x or 0.10 (old MUC API)
return muc.rooms[jid];
elseif muc and rawget(muc,"get_room_from_jid") then
-- We're running >0.10 (new MUC API)
return muc.get_room_from_jid(jid);
else
return
end
end
end
local function get_room_list(host)
local component = hosts[host];
local list = {};
if component then
local muc = component.modules.muc
if muc and rawget(muc,"rooms") then
-- We're running 0.9.x or 0.10 (old MUC API)
for _, room in pairs(muc.rooms) do
list[room.jid] = room;
end
return list;
elseif muc and rawget(muc,"each_room") then
-- We're running >0.10 (new MUC API)
for room, _ in muc.each_room() do
list[room.jid] = room;
end
return list;
end
end
end
local function generate_room_list(host)
local rooms;
for jid, room in pairs(get_room_list(host)) do
local node = split_jid(jid);
if not room._data.hidden and room._data.logging and node then
rooms = (rooms or "") .. html.rooms.bit:gsub("###ROOM###", urlencode(node)):gsub("###COMPONENT###", host);
end
end
if rooms then
return html.rooms.body:gsub("###ROOMS_STUFF###", rooms):gsub("###COMPONENT###", host), "Chatroom logs for "..host;
end
end
-- Calendar stuff
local function get_days_for_month(month, year)
if month == 2 then
local is_leap_year = (year % 4 == 0 and year % 100 ~= 0) or year % 400 == 0;
return is_leap_year and 29 or 28;
elseif (month < 8 and month%2 == 1) or (month >= 8 and month%2 == 0) then
return 31;
end
return 30;
end
local function create_month(month, year, callback)
local html_str = html.month.header;
local days = get_days_for_month(month, year);
local time = os_time{year=year, month=month, day=1};
local dow = tostring(os_date("%a", time))
local title = tostring(os_date("%B", time));
local week_days = {"Mon", "Tue", "Wed", "Thu", "Fri", "Sat", "Sun"};
local week_day = 0;
local weeks = 1;
local _available_for_one_day = false;
local week_days_html = "";
for _, tmp in ipairs(week_days) do
week_days_html = week_days_html .. html.month.weekDay:gsub("###DAY###", tmp) .. "\n";
end
html_str = html_str:gsub("###TITLE###", title):gsub("###WEEKDAYS###", week_days_html);
for i = 1, 31 do
week_day = week_day + 1;
if week_day == 1 then html_str = html_str .. "<tr>\n"; end
if i == 1 then
for _, tmp in ipairs(week_days) do
if dow ~= tmp then
html_str = html_str .. html.month.emptyDay .. "\n";
week_day = week_day + 1;
else
break;
end
end
end
if i < days + 1 then
local tmp = tostring(i);
if callback and callback.callback then
tmp = callback.callback(callback.path, i, month, year, callback.room, callback.webpath);
end
if tmp == nil then
tmp = tostring(i);
else
_available_for_one_day = true;
end
html_str = html_str .. html.month.day:gsub("###DAY###", tmp) .. "\n";
end
if i >= days then
break;
end
if week_day == 7 then
week_day = 0;
weeks = weeks + 1;
html_str = html_str .. "</tr>\n";
end
end
if week_day + 1 < 8 or weeks < 6 then
week_day = week_day + 1;
if week_day > 7 then
week_day = 1;
end
if week_day == 1 then
weeks = weeks + 1;
end
for y = weeks, 6 do
if week_day == 1 then
html_str = html_str .. "<tr>\n";
end
for i = week_day, 7 do
html_str = html_str .. html.month.emptyDay .. "\n";
end
week_day = 1
html_str = html_str .. "</tr>\n";
end
end
html_str = html_str .. html.month.footer;
if _available_for_one_day then
return html_str;
end
end
local function create_year(year, callback)
local year = year;
local tmp;
if tonumber(year) <= 99 then
year = year + 2000;
end
local html_str = "";
for i=1, 12 do
tmp = create_month(i, year, callback);
if tmp then
html_str = html_str .. "<div style='float: left; padding: 5px;'>\n" .. tmp .. "</div>\n";
end
end
if html_str ~= "" then
return "<div name='yearDiv' style='padding: 40px; text-align: center;'>" .. html.year.title:gsub("###YEAR###", tostring(year)) .. html_str .. "</div><br style='clear:both;'/> \n";
end
return "";
end
local function day_callback(path, day, month, year, room, webpath)
local webpath = webpath or ""
local year = year;
if year > 2000 then
year = year - 2000;
end
local bare_day = str_format("20%.02d-%.02d-%.02d", year, month, day);
room = p_encode(room);
local attributes, err = lfs.attributes(path.."/"..str_format("%.02d%.02d%.02d", year, month, day).."/"..room..".dat");
if attributes ~= nil and attributes.mode == "file" then
local s = html.days.bit;
s = s:gsub("###BARE_DAY###", webpath .. bare_day);
s = s:gsub("###DAY###", day);
return s;
end
return;
end
local function generate_day_room_content(bare_room_jid)
local days = "";
local days_array = {};
local tmp;
local node, host = split_jid(bare_room_jid);
local path = data_getpath(node, host, datastore);
local room = nil;
local next_room = "";
local previous_room = "";
local rooms = "";
local attributes = nil;
local since = "";
local to = "";
local topic = "";
local component = hosts[host];
if not(get_room_from_jid(bare_room_jid)) then
return;
end
path = path:gsub("/[^/]*$", "");
attributes = lfs.attributes(path);
do
local found = 0;
module:log("debug", generate_room_list(host));
for jid, room in pairs(get_room_list(host)) do
local node = split_jid(jid)
if not room._data.hidden and room._data.logging and node then
if found == 0 then
previous_room = node
elseif found == 1 then
next_room = node
found = -1
end
if jid == bare_room_jid then
found = 1
end
rooms = rooms .. html.days.rooms.bit:gsub("###ROOM###", urlencode(node));
end
end
room = get_room_from_jid(bare_room_jid);
if room._data.hidden or not room._data.logging then
room = nil;
end
end
if attributes and room then
local already_done_years = {};
topic = room._data.subject or "(no subject)"
if topic:len() > 135 then
topic = topic:sub(1, topic:find(" ", 120)) .. " ..."
end
local folders = {};
for folder in lfs.dir(path) do table.insert(folders, folder); end
table.sort(folders);
for _, folder in ipairs(folders) do
local year, month, day = folder:match("^(%d%d)(%d%d)(%d%d)");
if year then
to = tostring(os_date("%B %Y", os_time({ day=tonumber(day), month=tonumber(month), year=2000+tonumber(year) })));
if since == "" then since = to; end
if not already_done_years[year] then
module:log("debug", "creating overview for: %s", to);
days = create_year(year, {callback=day_callback, path=path, room=node}) .. days;
already_done_years[year] = true;
end
end
end
end
tmp = html.days.body:gsub("###DAYS_STUFF###", days);
tmp = tmp:gsub("###PREVIOUS_ROOM###", previous_room == "" and node or previous_room);
tmp = tmp:gsub("###NEXT_ROOM###", next_room == "" and node or next_room);
tmp = tmp:gsub("###ROOMS###", rooms);
tmp = tmp:gsub("###ROOMTOPIC###", topic);
tmp = tmp:gsub("###SINCE###", since);
tmp = tmp:gsub("###TO###", to);
return tmp:gsub("###JID###", bare_room_jid), "Chatroom logs for "..bare_room_jid;
end
local function parse_iq(stanza, time, nick)
local text = nil;
local victim = nil;
if(stanza.attr.type == "set") then
for _,tag in ipairs(stanza) do
if tag.tag == "query" then
for _,item in ipairs(tag) do
if item.tag == "item" and item.attr.nick ~= nil and item.attr.role == 'none' then
victim = item.attr.nick;
for _,reason in ipairs(item) do
if reason.tag == "reason" then
text = reason[1];
break;
end
end
break;
end
end
break;
end
end
if victim then
if text then
text = html.day.reason:gsub("###REASON###", html_escape(text));
else
text = "";
end
return html.day.kick:gsub("###TIME_STUFF###", time):gsub("###VICTIM###", victim):gsub("###REASON_STUFF###", text);
end
end
return;
end
local function parse_presence(stanza, time, nick)
local ret = "";
local show_join = "block"
if config and not config.show_join then
show_join = "none";
end
if stanza.attr.type == nil then
local show_status = "block"
if config and not config.show_status then
show_status = "none";
end
local show, status = nil, "";
local already_joined = false;
for _, tag in ipairs(stanza) do
if tag.tag == "alreadyJoined" then
already_joined = true;
elseif tag.tag == "show" then
show = tag[1];
elseif tag.tag == "status" and tag[1] ~= nil then
status = tag[1];
end
end
if already_joined == true then
if show == nil then
show = "online";
end
ret = html.day.presence.statusChange:gsub("###TIME_STUFF###", time);
if status ~= "" then
status = html.day.presence.statusText:gsub("###STATUS###", html_escape(status));
end
ret = ret:gsub("###SHOW###", show):gsub("###NICK###", nick):gsub("###SHOWHIDE###", show_status):gsub("###STATUS_STUFF###", status);
else
ret = html.day.presence.join:gsub("###TIME_STUFF###", time):gsub("###SHOWHIDE###", show_join):gsub("###NICK###", nick);
end
elseif stanza.attr.type == "unavailable" then
ret = html.day.presence.leave:gsub("###TIME_STUFF###", time):gsub("###SHOWHIDE###", show_join):gsub("###NICK###", nick);
end
return ret;
end
local function parse_message(stanza, time, nick)
local body, title, ret = nil, nil, "";
for _,tag in ipairs(stanza) do
if tag.tag == "body" then
body = tag[1];
if nick then
break;
end
elseif tag.tag == "nick" and nick == nil then
nick = html_escape(tag[1]);
if body or title then
break;
end
elseif tag.tag == "subject" then
title = tag[1];
if nick then
break;
end
end
end
if nick and body then
body = html_escape(body);
local me = body:find("^/me");
local template = "";
if not me then
template = html.day.message;
else
template = html.day.messageMe;
body = body:gsub("^/me ", "");
end
ret = template:gsub("###TIME_STUFF###", time):gsub("###NICK###", nick):gsub("###MSG###", body);
elseif nick and title then
title = html_escape(title);
ret = html.day.titleChange:gsub("###TIME_STUFF###", time):gsub("###NICK###", nick):gsub("###TITLE###", title);
end
return ret;
end
local function increment_day(bare_day)
local year, month, day = bare_day:match("^20(%d%d)-(%d%d)-(%d%d)$");
local leapyear = false;
module:log("debug", tostring(day).."/"..tostring(month).."/"..tostring(year))
day = tonumber(day);
month = tonumber(month);
year = tonumber(year);
if year%4 == 0 and year%100 == 0 then
if year%400 == 0 then
leapyear = true;
else
leapyear = false; -- turn of the century but not a leapyear
end
elseif year%4 == 0 then
leapyear = true;
end
if (month == 2 and leapyear and day + 1 > 29) or
(month == 2 and not leapyear and day + 1 > 28) or
(month < 8 and month%2 == 1 and day + 1 > 31) or
(month < 8 and month%2 == 0 and day + 1 > 30) or
(month >= 8 and month%2 == 0 and day + 1 > 31) or
(month >= 8 and month%2 == 1 and day + 1 > 30)
then
if month + 1 > 12 then
year = year + 1;
month = 1;
day = 1;
else
month = month + 1;
day = 1;
end
else
day = day + 1;
end
return strformat("20%.02d-%.02d-%.02d", year, month, day);
end
local function find_next_day(bare_room_jid, bare_day)
local node, host = split_jid(bare_room_jid);
local day = increment_day(bare_day);
local max_trys = 7;
module:log("debug", day);
while(not store_exists(node, host, day)) do
max_trys = max_trys - 1;
if max_trys == 0 then
break;
end
day = increment_day(day);
end
if max_trys == 0 then
return nil;
else
return day;
end
end
local function decrement_day(bare_day)
local year, month, day = bare_day:match("^20(%d%d)-(%d%d)-(%d%d)$");
local leapyear = false;
module:log("debug", tostring(day).."/"..tostring(month).."/"..tostring(year))
day = tonumber(day);
month = tonumber(month);
year = tonumber(year);
if year%4 == 0 and year%100 == 0 then
if year%400 == 0 then
leapyear = true;
else
leapyear = false; -- turn of the century but not a leapyear
end
elseif year%4 == 0 then
leapyear = true;
end
if day - 1 == 0 then
if month - 1 == 0 then
year = year - 1;
month = 12;
day = 31;
else
month = month - 1;
if (month == 2 and leapyear) then day = 29
elseif (month == 2 and not leapyear) then day = 28
elseif (month < 8 and month%2 == 1) or (month >= 8 and month%2 == 0) then day = 31
else day = 30
end
end
else
day = day - 1;
end
return strformat("20%.02d-%.02d-%.02d", year, month, day);
end
local function find_previous_day(bare_room_jid, bare_day)
local node, host = split_jid(bare_room_jid);
local day = decrement_day(bare_day);
local max_trys = 7;
module:log("debug", day);
while(not store_exists(node, host, day)) do
max_trys = max_trys - 1;
if max_trys == 0 then
break;
end
day = decrement_day(day);
end
if max_trys == 0 then
return nil;
else
return day;
end
end
local function parse_day(bare_room_jid, room_subject, bare_day)
local ret = "";
local year;
local month;
local day;
local tmp;
local node, host = split_jid(bare_room_jid);
local year, month, day = bare_day:match("^20(%d%d)-(%d%d)-(%d%d)$");
local previous_day = find_previous_day(bare_room_jid, bare_day);
local next_day = find_next_day(bare_room_jid, bare_day);
local temptime = {day=0, month=0, year=0};
local path = data_getpath(node, host, datastore);
path = path:gsub("/[^/]*$", "");
local calendar = ""
if tonumber(year) <= 99 then
year = year + 2000;
end
temptime.day = tonumber(day)
temptime.month = tonumber(month)
temptime.year = tonumber(year)
calendar = create_month(temptime.month, temptime.year, {callback=day_callback, path=path, room=node, webpath="../"}) or ""
if bare_day then
local data = data_load(node, host, datastore .. "/" .. bare_day:match("^20(.*)"):gsub("-", ""));
if data then
for i=1, #data, 1 do
local stanza = lom.parse(data[i]);
if stanza and stanza.attr and stanza.attr.time then
local timeStuff = html.day.time:gsub("###TIME###", stanza.attr.time):gsub("###UTC###", stanza.attr.utc or stanza.attr.time);
if stanza[1] ~= nil then
local nick;
local tmp;
-- grep nick from "from" resource
if stanza[1].attr.from then -- presence and messages
nick = html_escape(stanza[1].attr.from:match("/(.+)$"));
elseif stanza[1].attr.to then -- iq
nick = html_escape(stanza[1].attr.to:match("/(.+)$"));
end
if stanza[1].tag == "presence" and nick then
tmp = parse_presence(stanza[1], timeStuff, nick);
elseif stanza[1].tag == "message" then
tmp = parse_message(stanza[1], timeStuff, nick);
elseif stanza[1].tag == "iq" then
tmp = parse_iq(stanza[1], timeStuff, nick);
else
module:log("info", "unknown stanza subtag in log found. room: %s; day: %s", bare_room_jid, year .. "/" .. month .. "/" .. day);
end
if tmp then
ret = ret .. tmp
tmp = nil;
end
end
end
end
end
if ret ~= "" then
if next_day then
next_day = html.day.dayLink:gsub("###DAY###", next_day):gsub("###TEXT###", ">")
end
if previous_day then
previous_day = html.day.dayLink:gsub("###DAY###", previous_day):gsub("###TEXT###", "<");
end
ret = ret:gsub("%%", "%%%%");
if config.show_presences then
tmp = html.day.body:gsub("###DAY_STUFF###", ret):gsub("###JID###", bare_room_jid);
else
tmp = html.day.bodynp:gsub("###DAY_STUFF###", ret):gsub("###JID###", bare_room_jid);
end
tmp = tmp:gsub("###CALENDAR###", calendar);
tmp = tmp:gsub("###DATE###", tostring(os_date("%A, %B %d, %Y", os_time(temptime))));
tmp = tmp:gsub("###TITLE_STUFF###", html.day.title:gsub("###TITLE###", room_subject));
tmp = tmp:gsub("###STATUS_CHECKED###", config.show_status and "checked='checked'" or "");
tmp = tmp:gsub("###JOIN_CHECKED###", config.show_join and "checked='checked'" or "");
tmp = tmp:gsub("###NEXT_LINK###", next_day or "");
tmp = tmp:gsub("###PREVIOUS_LINK###", previous_day or "");
return tmp, "Chatroom logs for "..bare_room_jid.." ("..tostring(os_date("%A, %B %d, %Y", os_time(temptime)))..")";
end
end
end
local function handle_error(code, err) return http_event("http-error", { code = code, message = err }); end
function handle_request(event)
local response = event.response;
local request = event.request;
local room;
local node, day, more = request.url.path:match("^/"..url_base.."/+([^/]*)/*([^/]*)/*(.*)$");
if more ~= "" then
response.status_code = 404;
return response:send(handle_error(response.status_code, "Unknown URL."));
end
if node == "" then node = nil; end
if day == "" then day = nil; end
node = urldecode(node);
if not html.doc then
response.status_code = 500;
return response:send(handle_error(response.status_code, "Muc Theme is not loaded."));
end
if node then room = get_room_from_jid(node.."@"..my_host); end
if node and not room then
response.status_code = 404;
return response:send(handle_error(response.status_code, "Room doesn't exist."));
end
if room and (room._data.hidden or not room._data.logging) then
response.status_code = 404;
return response:send(handle_error(response.status_code, "There're no logs for this room."));
end
if not node then -- room list for component
return response:send(create_doc(generate_room_list(my_host)));
elseif not day then -- room's listing
return response:send(create_doc(generate_day_room_content(node.."@"..my_host)));
else
if not day:match("^20(%d%d)-(%d%d)-(%d%d)$") then
local y,m,d = day:match("^(%d%d)(%d%d)(%d%d)$");
if not y then
response.status_code = 404;
return response:send(handle_error(response.status_code, "No entries for that year."));
end
response.status_code = 301;
response.headers = { ["Location"] = request.url.path:match("^/"..url_base.."/+[^/]*").."/20"..y.."-"..m.."-"..d.."/" };
return response:send();
end
local body = create_doc(parse_day(node.."@"..my_host, room._data.subject or "", day));
if body == "" then
response.status_code = 404;
return response:send(handle_error(response.status_code, "Day entry doesn't exist."));
end
return response:send(body);
end
end
local function read_file(filepath)
local f,err = io_open(filepath, "r");
if not f then return f,err; end
local t = f:read("*all");
f:close()
return t;
end
local function load_theme(path)
for file in lfs.dir(path) do
if file:match("%.html$") then
module:log("debug", "opening theme file: " .. file);
local content,err = read_file(path .. "/" .. file);
if not content then return content,err; end
-- html.a.b.c = content of a_b_c.html
local tmp = html;
for idx in file:gmatch("([^_]*)_") do
tmp[idx] = tmp[idx] or {};
tmp = tmp[idx];
end
tmp[file:match("([^_]*)%.html$")] = content;
end
end
return true;
end
function module.load()
config = module:get_option("muc_log_http", {});
if module:get_option_boolean("muc_log_presences", true) then config.show_presences = true end
if config.show_status == nil then config.show_status = true; end
if config.show_join == nil then config.show_join = true; end
if config.url_base and type(config.url_base) == "string" then url_base = config.url_base; end
theme = config.theme or "prosody";
local theme_path = themes_parent .. "/" .. tostring(theme);
local attributes, err = lfs.attributes(theme_path);
if attributes == nil or attributes.mode ~= "directory" then
module:log("error", "Theme folder of theme \"".. tostring(theme) .. "\" isn't existing. expected Path: " .. theme_path);
return false;
end
local themeLoaded,err = load_theme(theme_path);
if not themeLoaded then
module:log("error", "Theme \"%s\" is missing something: %s", tostring(theme), err);
return false;
end
module:provides("http", {
default_path = url_base,
route = {
["GET /*"] = handle_request;
}
});
end
| mit |
metal-bot/metal | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
terinux/ahhhh | plugins/banhammer.lua | 1085 | 11557 |
local function pre_process(msg)
-- SERVICE MESSAGE
if msg.action and msg.action.type then
local action = msg.action.type
-- Check if banned user joins chat by link
if action == 'chat_add_user_link' then
local user_id = msg.from.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] is banned and kicked ! ")-- Save to logs
kick_user(user_id, msg.to.id)
end
end
-- Check if banned user joins chat
if action == 'chat_add_user' then
local user_id = msg.action.user.id
print('Checking invited user '..user_id)
local banned = is_banned(user_id, msg.to.id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('User is banned!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a banned user >"..msg.action.user.id)-- Save to logs
kick_user(user_id, msg.to.id)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:incr(banhash)
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
local banaddredis = redis:get(banhash)
if banaddredis then
if tonumber(banaddredis) == 4 and not is_owner(msg) then
kick_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 3 times
end
if tonumber(banaddredis) == 8 and not is_owner(msg) then
ban_user(msg.from.id, msg.to.id)-- Kick user who adds ban ppl more than 7 times
local banhash = 'addedbanuser:'..msg.to.id..':'..msg.from.id
redis:set(banhash, 0)-- Reset the Counter
end
end
end
if data[tostring(msg.to.id)] then
if data[tostring(msg.to.id)]['settings'] then
if data[tostring(msg.to.id)]['settings']['lock_bots'] then
bots_protection = data[tostring(msg.to.id)]['settings']['lock_bots']
end
end
end
if msg.action.user.username ~= nil then
if string.sub(msg.action.user.username:lower(), -3) == 'bot' and not is_momod(msg) and bots_protection == "yes" then --- Will kick bots added by normal users
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] added a bot > @".. msg.action.user.username)-- Save to logs
kick_user(msg.action.user.id, msg.to.id)
end
end
end
-- No further checks
return msg
end
-- banned user is talking !
if msg.to.type == 'chat' then
local data = load_data(_config.moderation.data)
local group = msg.to.id
local texttext = 'groups'
--if not data[tostring(texttext)][tostring(msg.to.id)] and not is_realm(msg) then -- Check if this group is one of my groups or not
--chat_del_user('chat#id'..msg.to.id,'user#id'..our_id,ok_cb,false)
--return
--end
local user_id = msg.from.id
local chat_id = msg.to.id
local banned = is_banned(user_id, chat_id)
if banned or is_gbanned(user_id) then -- Check it with redis
print('Banned user talking!')
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] banned user is talking !")-- Save to logs
kick_user(user_id, chat_id)
msg.text = ''
end
end
return msg
end
local function kick_ban_res(extra, success, result)
--vardump(result)
--vardump(extra)
local member_id = result.id
local user_id = member_id
local member = result.username
local chat_id = extra.chat_id
local from_id = extra.from_id
local get_cmd = extra.get_cmd
local receiver = "chat#id"..chat_id
if get_cmd == "kick" then
if member_id == from_id then
return send_large_msg(receiver, "You can't kick yourself")
end
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't kick mods/owner/admins")
end
return kick_user(member_id, chat_id)
elseif get_cmd == 'ban' then
if is_momod2(member_id, chat_id) and not is_admin2(sender) then
return send_large_msg(receiver, "You can't ban mods/owner/admins")
end
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] banned')
return ban_user(member_id, chat_id)
elseif get_cmd == 'unban' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] unbanned')
local hash = 'banned:'..chat_id
redis:srem(hash, member_id)
return 'User '..user_id..' unbanned'
elseif get_cmd == 'banall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] globally banned')
return banall_user(member_id, chat_id)
elseif get_cmd == 'unbanall' then
send_large_msg(receiver, 'User @'..member..' ['..member_id..'] un-globally banned')
return unbanall_user(member_id, chat_id)
end
end
local function run(msg, matches)
if matches[1]:lower() == 'id' then
if msg.to.type == "user" then
return "Bot ID: "..msg.to.id.. "\n\nYour ID: "..msg.from.id
end
if type(msg.reply_id) ~= "nil" then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
id = get_message(msg.reply_id,get_message_callback_id, false)
elseif matches[1]:lower() == 'id' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] used /id ")
return "Group ID for " ..string.gsub(msg.to.print_name, "_", " ").. ":\n\n"..msg.to.id
end
end
if matches[1]:lower() == 'kickme' then-- /kickme
local receiver = get_receiver(msg)
if msg.to.type == 'chat' then
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] left using kickme ")-- Save to logs
chat_del_user("chat#id"..msg.to.id, "user#id"..msg.from.id, ok_cb, false)
end
end
if not is_momod(msg) then -- Ignore normal users
return
end
if matches[1]:lower() == "banlist" then -- Ban list !
local chat_id = msg.to.id
if matches[2] and is_admin(msg) then
chat_id = matches[2]
end
return ban_list(chat_id)
end
if matches[1]:lower() == 'ban' then-- /ban
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,ban_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,ban_by_reply, false)
end
end
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't ban mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't ban your self !"
end
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] baned user ".. matches[2])
ban_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'ban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unban' then -- /unban
if type(msg.reply_id)~="nil" and is_momod(msg) then
local msgr = get_message(msg.reply_id,unban_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
local user_id = targetuser
local hash = 'banned:'..chat_id
redis:srem(hash, user_id)
local name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] unbaned user ".. matches[2])
return 'User '..user_id..' unbanned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unban',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'kick' then
if type(msg.reply_id)~="nil" and is_momod(msg) then
if is_admin(msg) then
local msgr = get_message(msg.reply_id,Kick_by_reply_admins, false)
else
msgr = get_message(msg.reply_id,Kick_by_reply, false)
end
end
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return
end
if not is_admin(msg) and is_momod2(matches[2], msg.to.id) then
return "you can't kick mods/owner/admins"
end
if tonumber(matches[2]) == tonumber(msg.from.id) then
return "You can't kick your self !"
end
local user_id = matches[2]
local chat_id = msg.to.id
name = user_print_name(msg.from)
savelog(msg.to.id, name.." ["..msg.from.id.."] kicked user ".. matches[2])
kick_user(user_id, chat_id)
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'kick',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if not is_admin(msg) then
return
end
if matches[1]:lower() == 'banall' then -- Global ban
if type(msg.reply_id) ~="nil" and is_admin(msg) then
return get_message(msg.reply_id,banall_by_reply, false)
end
local user_id = matches[2]
local chat_id = msg.to.id
local targetuser = matches[2]
if string.match(targetuser, '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
banall_user(targetuser)
return 'User ['..user_id..' ] globally banned'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'banall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == 'unbanall' then -- Global unban
local user_id = matches[2]
local chat_id = msg.to.id
if string.match(matches[2], '^%d+$') then
if tonumber(matches[2]) == tonumber(our_id) then
return false
end
unbanall_user(user_id)
return 'User ['..user_id..' ] removed from global ban list'
else
local cbres_extra = {
chat_id = msg.to.id,
get_cmd = 'unbanall',
from_id = msg.from.id
}
local username = matches[2]
local username = string.gsub(matches[2], '@', '')
res_user(username, kick_ban_res, cbres_extra)
end
end
if matches[1]:lower() == "gbanlist" then -- Global ban list
return banall_list()
end
end
return {
patterns = {
"^[!/]([Bb]anall) (.*)$",
"^[!/]([Bb]anall)$",
"^[!/]([Bb]anlist) (.*)$",
"^[!/]([Bb]anlist)$",
"^[!/]([Gg]banlist)$",
"^[!/]([Bb]an) (.*)$",
"^[!/]([Kk]ick)$",
"^[!/]([Uu]nban) (.*)$",
"^[!/]([Uu]nbanall) (.*)$",
"^[!/]([Uu]nbanall)$",
"^[!/]([Kk]ick) (.*)$",
"^[!/]([Kk]ickme)$",
"^[!/]([Bb]an)$",
"^[!/]([Uu]nban)$",
"^[!/]([Ii]d)$",
"^!!tgservice (.+)$"
},
run = run,
pre_process = pre_process
}
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Lower_Jeuno/npcs/Miladi-Nildi.lua | 5 | 1035 | -----------------------------------
-- Area: Lower Jeuno
-- NPC: Miladi-Nildi
-- Type: Standard NPC
-- @zone: 245
-- @pos: 39.898 -5.999 77.190
--
-- Auto-Script: Requires Verification (Verfied by Brawndo)
-----------------------------------
package.loaded["scripts/zones/Lower_Jeuno/TextIDs"] = nil;
-----------------------------------
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
player:startEvent(0x0061);
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 |
Lleafll/sws-lleaf | libs/LibBabble-Inventory-3.0/LibBabble-Inventory-3.0.lua | 1 | 52946 | --[[
Name: LibBabble-Inventory-3.0
Revision: $Rev: 191 $
Maintainers: ckknight, nevcairiel, Ackis
Website: http://www.wowace.com/projects/libbabble-inventory-3-0/
Dependencies: None
License: MIT
]]
local MAJOR_VERSION = "LibBabble-Inventory-3.0"
local MINOR_VERSION = 90000 + tonumber(("$Rev: 191 $"):match("%d+"))
if not LibStub then error(MAJOR_VERSION .. " requires LibStub.") end
local lib = LibStub("LibBabble-3.0"):New(MAJOR_VERSION, MINOR_VERSION)
if not lib then return end
local GAME_LOCALE = GetLocale()
lib:SetBaseTranslations {
Alchemy = "Alchemy",
["Ammo Pouch"] = "Ammo Pouch",
Aquatic = "Aquatic",
Archaeology = "Archaeology",
Armor = "Armor",
["Armor Enchantment"] = "Armor Enchantment",
Arrow = "Arrow",
Axe = "Axe",
Back = "Back",
Bag = "Bag",
Bandage = "Bandage",
Beast = "Beast",
Blacksmithing = "Blacksmithing",
Blue = "Blue",
Book = "Book",
Bow = "Bow",
Bows = "Bows",
Bullet = "Bullet",
Chest = "Chest",
Cloth = "Cloth",
Cogwheel = "Cogwheel",
Companion = "Companion",
["Companion Pets"] = "Companion Pets",
Companions = "Companions",
Consumable = "Consumable",
Container = "Container",
Cooking = "Cooking",
["Cooking Bag"] = "Cooking Bag",
Cosmetic = "Cosmetic",
Critter = "Critter",
Crossbow = "Crossbow",
Crossbows = "Crossbows",
Dagger = "Dagger",
Daggers = "Daggers",
["Death Knight"] = "Death Knight",
Devices = "Devices",
Dragonkin = "Dragonkin",
Drink = "Drink",
Druid = "Druid",
Elemental = "Elemental",
Elixir = "Elixir",
Enchant = "Enchant",
Enchanting = "Enchanting",
["Enchanting Bag"] = "Enchanting Bag",
Engineering = "Engineering",
["Engineering Bag"] = "Engineering Bag",
Explosives = "Explosives",
Feet = "Feet",
["First Aid"] = "First Aid",
Fish = "Fish",
Fishing = "Fishing",
["Fishing Lure"] = "Fishing Lure",
["Fishing Pole"] = "Fishing Pole",
["Fishing Poles"] = "Fishing Poles",
["Fist Weapon"] = "Fist Weapon",
["Fist Weapons"] = "Fist Weapons",
Flask = "Flask",
Flying = "Flying",
["Flying Mount"] = "Flying Mount",
Food = "Food",
["Food & Drink"] = "Food & Drink",
Gem = "Gem",
["Gem Bag"] = "Gem Bag",
Glyph = "Glyph",
Green = "Green",
["Ground Mount"] = "Ground Mount",
Gun = "Gun",
Guns = "Guns",
Hands = "Hands",
Head = "Head",
["Held in Off-Hand"] = "Held in Off-Hand",
Herb = "Herb",
Herbalism = "Herbalism",
["Herb Bag"] = "Herb Bag",
Holiday = "Holiday",
Humanoid = "Humanoid",
Hunter = "Hunter",
Hydraulic = "Hydraulic",
Idol = "Idol",
Idols = "Idols",
Inscription = "Inscription",
["Inscription Bag"] = "Inscription Bag",
["Item Enchantment"] = "Item Enchantment",
["Item Enhancement"] = "Item Enhancement",
Jewelcrafting = "Jewelcrafting",
Junk = "Junk",
Key = "Key",
Leather = "Leather",
Leatherworking = "Leatherworking",
["Leatherworking Bag"] = "Leatherworking Bag",
Legs = "Legs",
Libram = "Libram",
Librams = "Librams",
Mace = "Mace",
Mage = "Mage",
Magic = "Magic",
Mail = "Mail",
["Main Hand"] = "Main Hand",
Materials = "Materials",
Meat = "Meat",
Mechanical = "Mechanical",
Meta = "Meta",
["Metal & Stone"] = "Metal & Stone",
Mining = "Mining",
["Mining Bag"] = "Mining Bag",
Miscellaneous = "Miscellaneous",
Money = "Money",
Monk = "Monk",
Mount = "Mount",
Mounts = "Mounts",
Neck = "Neck",
["Off Hand"] = "Off Hand",
["One-Hand"] = "One-Hand",
["One-Handed Axes"] = "One-Handed Axes",
["One-Handed Maces"] = "One-Handed Maces",
["One-Handed Swords"] = "One-Handed Swords",
Orange = "Orange",
Other = "Other",
Paladin = "Paladin",
Parts = "Parts",
Pet = "Pet",
Plate = "Plate",
Polearm = "Polearm",
Polearms = "Polearms",
Potion = "Potion",
Priest = "Priest",
Prismatic = "Prismatic",
Projectile = "Projectile",
Purple = "Purple",
Quest = "Quest",
Quiver = "Quiver",
Ranged = "Ranged",
Reagent = "Reagent",
Recipe = "Recipe",
Red = "Red",
Relic = "Relic",
Riding = "Riding",
Ring = "Ring",
Rogue = "Rogue",
Scroll = "Scroll",
Shaman = "Shaman",
Shield = "Shield",
Shields = "Shields",
Shirt = "Shirt",
Shoulder = "Shoulder",
Sigils = "Sigils",
Simple = "Simple",
Skinning = "Skinning",
["Soul Bag"] = "Soul Bag",
Staff = "Staff",
Staves = "Staves",
Sword = "Sword",
Tabard = "Tabard",
Tabards = "Tabards",
["Tackle Box"] = "Tackle Box",
Tailoring = "Tailoring",
Thrown = "Thrown",
Totem = "Totem",
Totems = "Totems",
["Trade Goods"] = "Trade Goods",
Trinket = "Trinket",
["Two-Hand"] = "Two-Hand",
["Two-Handed Axes"] = "Two-Handed Axes",
["Two-Handed Maces"] = "Two-Handed Maces",
["Two-Handed Swords"] = "Two-Handed Swords",
Undead = "Undead",
Waist = "Waist",
Wand = "Wand",
Wands = "Wands",
Warlock = "Warlock",
Warrior = "Warrior",
Weapon = "Weapon",
["Weapon Enchantment"] = "Weapon Enchantment",
Wrist = "Wrist",
Yellow = "Yellow",
}
if GAME_LOCALE == "enUS" then
lib:SetCurrentTranslations(true)
elseif GAME_LOCALE == "deDE" then
lib:SetCurrentTranslations {
Alchemy = "Alchemie",
["Ammo Pouch"] = "Munitionsbeutel",
Aquatic = "Aquatisch",
Archaeology = "Archäologie",
Armor = "Rüstung",
["Armor Enchantment"] = "Rüstungsverzauberung",
Arrow = "Pfeil",
Axe = "Axt",
Back = "Rücken",
Bag = "Behälter",
Bandage = "Verband",
Beast = "Wildtier",
Blacksmithing = "Schmiedekunst",
Blue = "Blau",
Book = "Buch",
Bow = "Bogen",
Bows = "Bögen",
Bullet = "Kugel",
Chest = "Brust",
Cloth = "Stoff",
Cogwheel = "Zahnrad",
Companion = "Haustier",
["Companion Pets"] = "Haustiere",
Companions = "Haustiere",
Consumable = "Verbrauchbar",
Container = "Behälter",
Cooking = "Kochkunst",
["Cooking Bag"] = "Küchentasche",
Cosmetic = "Kosmetisch",
Critter = "Kleintier",
Crossbow = "Armbrust",
Crossbows = "Armbrüste",
Dagger = "Dolch",
Daggers = "Dolche",
["Death Knight"] = "Todesritter",
Devices = "Geräte",
Dragonkin = "Drachkin",
Drink = "Getränk",
Druid = "Druide",
Elemental = "Elementar",
Elixir = "Elixier",
Enchant = "Verzauberung",
Enchanting = "Verzauberkunst",
["Enchanting Bag"] = "Verzauberertasche",
Engineering = "Ingenieurskunst",
["Engineering Bag"] = "Ingenieurstasche",
Explosives = "Sprengstoff",
Feet = "Füße",
["First Aid"] = "Erste Hilfe",
Fish = "Fisch",
Fishing = "Angeln",
["Fishing Lure"] = "Köder",
["Fishing Pole"] = "Angelrute",
["Fishing Poles"] = "Angelruten",
["Fist Weapon"] = "Faustwaffe",
["Fist Weapons"] = "Faustwaffen",
Flask = "Fläschchen",
Flying = "Fliegend",
["Flying Mount"] = "Flugreittier",
Food = "Essen",
["Food & Drink"] = "Speis & Trank",
Gem = "Edelstein",
["Gem Bag"] = "Edelsteintasche",
Glyph = "Glyphe",
Green = "Grün",
["Ground Mount"] = "Bodenreittier",
Gun = "Schusswaffe",
Guns = "Schusswaffen",
Hands = "Hände",
Head = "Kopf",
["Held in Off-Hand"] = "In Schildhand geführt",
Herb = "Kräuter",
Herbalism = "Kräuterkunde",
["Herb Bag"] = "Kräutertasche",
Holiday = "Festtag",
Humanoid = "Humanoid",
Hunter = "Jäger",
Hydraulic = "Hydraulisch",
Idol = "Götze",
Idols = "Götzen",
Inscription = "Inschriftenkunde",
["Inscription Bag"] = "Schreibertasche",
["Item Enchantment"] = "Gegenstandsverzauberung",
["Item Enhancement"] = "Gegenstandsverbesserung",
Jewelcrafting = "Juwelierskunst",
Junk = "Plunder",
Key = "Schlüssel",
Leather = "Leder",
Leatherworking = "Lederverarbeitung",
["Leatherworking Bag"] = "Lederertasche",
Legs = "Beine",
Libram = "Buchband",
Librams = "Buchbände",
Mace = "Streitkolben",
Mage = "Magier",
Magic = "Magisch",
Mail = "Kette",
["Main Hand"] = "Waffenhand",
Materials = "Materialien",
Meat = "Fleisch",
Mechanical = "Mechanisch",
Meta = "Meta",
["Metal & Stone"] = "Metall & Stein",
Mining = "Bergbau",
["Mining Bag"] = "Bergbautasche",
Miscellaneous = "Verschiedenes",
Money = "Geld",
Monk = "Mönch",
Mount = "Reittier",
Mounts = "Reittiere",
Neck = "Hals",
["Off Hand"] = "Schildhand",
["One-Hand"] = "Einhändig",
["One-Handed Axes"] = "Einhandäxte",
["One-Handed Maces"] = "Einhandstreitkolben",
["One-Handed Swords"] = "Einhandschwerter",
Orange = "Orange",
Other = "Sonstige",
Paladin = "Paladin",
Parts = "Teile",
Pet = "Begleiter",
Plate = "Platte",
Polearm = "Stangenwaffe",
Polearms = "Stangenwaffen",
Potion = "Trank",
Priest = "Priester",
Prismatic = "Prismatisch",
Projectile = "Projektil",
Purple = "Violett",
Quest = "Quest",
Quiver = "Köcher",
Ranged = "Distanz",
Reagent = "Reagenz",
Recipe = "Rezept",
Red = "Rot",
Relic = "Relikt",
Riding = "Reiten",
Ring = "Finger",
Rogue = "Schurke",
Scroll = "Rolle",
Shaman = "Schamane",
Shield = "Schild",
Shields = "Schilde",
Shirt = "Hemd",
Shoulder = "Schulter",
Sigils = "Siegel",
Simple = "Einfach",
Skinning = "Kürschnerei",
["Soul Bag"] = "Seelentasche",
Staff = "Stab",
Staves = "Stäbe",
Sword = "Schwert",
Tabard = "Wappenrock",
Tabards = "Wappenröcke",
["Tackle Box"] = "Werkzeugkasten",
Tailoring = "Schneiderei",
Thrown = "Wurfwaffe",
Totem = "Totem",
Totems = "Totems",
["Trade Goods"] = "Handwerkswaren",
Trinket = "Schmuck",
["Two-Hand"] = "Zweihändig",
["Two-Handed Axes"] = "Zweihandäxte",
["Two-Handed Maces"] = "Zweihandstreitkolben",
["Two-Handed Swords"] = "Zweihandschwerter",
Undead = "Untot",
Waist = "Taille",
Wand = "Zauberstab",
Wands = "Zauberstäbe",
Warlock = "Hexenmeister",
Warrior = "Krieger",
Weapon = "Waffe",
["Weapon Enchantment"] = "Waffenverzauberung",
Wrist = "Handgelenke",
Yellow = "Gelb",
}
elseif GAME_LOCALE == "frFR" then
lib:SetCurrentTranslations {
Alchemy = "Alchimie",
["Ammo Pouch"] = "Giberne",
Aquatic = "Aquatique", -- Needs review
Archaeology = "Archéologie",
Armor = "Armure",
["Armor Enchantment"] = "Enchantement d'armure",
Arrow = "Flèche",
Axe = "Hache",
Back = "Dos",
Bag = "Sac",
Bandage = "Bandage",
Beast = "Bête", -- Needs review
Blacksmithing = "Forge",
Blue = "Bleu",
Book = "Livre",
Bow = "Arc",
Bows = "Arcs",
Bullet = "Balle",
Chest = "Torse",
Cloth = "Tissu",
Cogwheel = "Crémaillère",
Companion = "Compagnon",
["Companion Pets"] = "Mascottes", -- Needs review
Companions = "Compagnons",
Consumable = "Consommable",
Container = "Conteneur",
Cooking = "Cuisine",
["Cooking Bag"] = "Sac de cuisinier", -- Needs review
Cosmetic = "Cosmétique", -- Needs review
Critter = "Bestiole", -- Needs review
Crossbow = "Arbalète",
Crossbows = "Arbalètes",
Dagger = "Dague",
Daggers = "Dagues",
["Death Knight"] = "Chevalier de la mort",
Devices = "Appareils",
Dragonkin = "Draconien", -- Needs review
Drink = "Breuvage",
Druid = "Druide",
Elemental = "Élémentaire",
Elixir = "Élixir",
Enchant = "Enchantement",
Enchanting = "Enchantement",
["Enchanting Bag"] = "Sac d'enchanteur",
Engineering = "Ingénierie",
["Engineering Bag"] = "Sac d'ingénieur",
Explosives = "Explosifs",
Feet = "Pieds",
["First Aid"] = "Secourisme",
Fish = "Pêche",
Fishing = "Pêche",
["Fishing Lure"] = "Appât de pêche",
["Fishing Pole"] = "Canne à pêche",
["Fishing Poles"] = "Cannes à pêche",
["Fist Weapon"] = "Arme de pugilat",
["Fist Weapons"] = "Armes de pugilat",
Flask = "Flacon",
Flying = "Volant", -- Needs review
["Flying Mount"] = "Monture volante",
Food = "Ration",
["Food & Drink"] = "Nourriture & boissons",
Gem = "Gemme",
["Gem Bag"] = "Sac de gemmes",
Glyph = "Glyphe",
Green = "Verte",
["Ground Mount"] = "Monture terrestre",
Gun = "Arme à feu",
Guns = "Fusils",
Hands = "Mains",
Head = "Tête",
["Held in Off-Hand"] = "Tenu(e) en main gauche",
Herb = "Herbes",
Herbalism = "Herboristerie",
["Herb Bag"] = "Sac d'herbes",
Holiday = "Vacances",
Humanoid = "Humanoïde", -- Needs review
Hunter = "Chasseur",
Hydraulic = "Hydraulique",
Idol = "Idole",
Idols = "Idoles",
Inscription = "Calligraphie",
["Inscription Bag"] = "Sac de calligraphie",
["Item Enchantment"] = "Enchantement d'objet",
["Item Enhancement"] = "Amélioration d'objet",
Jewelcrafting = "Joaillerie",
Junk = "Camelote",
Key = "Clé",
Leather = "Cuir",
Leatherworking = "Travail du cuir",
["Leatherworking Bag"] = "Sac de travail du cuir",
Legs = "Jambes",
Libram = "Libram",
Librams = "Librams",
Mace = "Masse",
Mage = "Mage",
Magic = "Magique", -- Needs review
Mail = "Mailles",
["Main Hand"] = "Main droite",
Materials = "Matériaux",
Meat = "Viande",
Mechanical = "Mécanique", -- Needs review
Meta = "Méta",
["Metal & Stone"] = "Métal & pierre",
Mining = "Minage",
["Mining Bag"] = "Sac de mineur",
Miscellaneous = "Divers",
Money = "Argent",
Monk = "Moine", -- Needs review
Mount = "Monture",
Mounts = "Montures",
Neck = "Cou",
["Off Hand"] = "Main gauche",
["One-Hand"] = "A une main",
["One-Handed Axes"] = "Haches à une main",
["One-Handed Maces"] = "Masses à une main",
["One-Handed Swords"] = "Epées à une main",
Orange = "Orange",
Other = "Autre",
Paladin = "Paladin",
Parts = "Eléments",
Pet = "Familier",
Plate = "Plaques",
Polearm = "Arme d'hast",
Polearms = "Armes d'hast",
Potion = "Potion",
Priest = "Prêtre",
Prismatic = "Prismatique",
Projectile = "Projectile",
Purple = "Violette",
Quest = "Quête",
Quiver = "Carquois",
Ranged = "À distance",
Reagent = "Réactif",
Recipe = "Recette",
Red = "Rouge",
Relic = "Relique",
Riding = "Monte",
Ring = "Anneau",
Rogue = "Voleur",
Scroll = "Parchemin",
Shaman = "Chaman",
Shield = "Bouclier",
Shields = "Boucliers",
Shirt = "Chemise",
Shoulder = "Epaule",
Sigils = "Glyphes",
Simple = "Simple",
Skinning = "Dépeçage",
["Soul Bag"] = "Sac d'âme",
Staff = "Bâton",
Staves = "Bâtons",
Sword = "Epée",
Tabard = "Tabard",
Tabards = "Tabards",
["Tackle Box"] = "Tackle Box",
Tailoring = "Couture",
Thrown = "Armes de jets",
Totem = "Totem",
Totems = "Totems",
["Trade Goods"] = "Artisanat",
Trinket = "Bijou",
["Two-Hand"] = "Deux mains",
["Two-Handed Axes"] = "Haches à deux mains",
["Two-Handed Maces"] = "Masses à deux mains",
["Two-Handed Swords"] = "Epées à deux mains",
Undead = "Mort-vivant", -- Needs review
Waist = "Taille",
Wand = "Baguette",
Wands = "Baguettes",
Warlock = "Démoniste",
Warrior = "Guerrier",
Weapon = "Arme",
["Weapon Enchantment"] = "Enchantement d'arme",
Wrist = "Poignets",
Yellow = "Jaune",
}
elseif GAME_LOCALE == "koKR" then
lib:SetCurrentTranslations {
Alchemy = "연금술",
["Ammo Pouch"] = "탄환 주머니",
Aquatic = "물", -- Needs review
Archaeology = "고고학",
Armor = "방어구",
["Armor Enchantment"] = "방어구 마법부여",
Arrow = "화살",
Axe = "도끼",
Back = "등",
Bag = "가방",
Bandage = "붕대",
Beast = "야수", -- Needs review
Blacksmithing = "대장기술",
Blue = "푸른색",
Book = "책",
Bow = "활",
Bows = "활류",
Bullet = "탄환",
Chest = "가슴",
Cloth = "천",
Cogwheel = "맞물림 톱니", -- Needs review
Companion = "친구",
["Companion Pets"] = "애완동물", -- Needs review
Companions = "친구",
Consumable = "소비용품",
Container = "가방",
Cooking = "요리",
["Cooking Bag"] = "요리 가방", -- Needs review
Cosmetic = "장식", -- Needs review
Critter = "동물", -- Needs review
Crossbow = "석궁",
Crossbows = "석궁류",
Dagger = "단검",
Daggers = "단검류",
["Death Knight"] = "죽음의 기사",
Devices = "기계 장치",
Dragonkin = "용족", -- Needs review
Drink = "음료",
Druid = "드루이드",
Elemental = "원소",
Elixir = "비약",
Enchant = "마법부여",
Enchanting = "마법부여",
["Enchanting Bag"] = "마법부여 가방",
Engineering = "기계공학",
["Engineering Bag"] = "기계공학 가방",
Explosives = "폭발물",
Feet = "발",
["First Aid"] = "응급치료",
Fish = "물고기",
Fishing = "낚시",
["Fishing Lure"] = "낚시 미끼",
["Fishing Pole"] = "낚싯대",
["Fishing Poles"] = "낚싯대",
["Fist Weapon"] = "장착 무기",
["Fist Weapons"] = "장착 무기류",
Flask = "영약",
Flying = "비행", -- Needs review
["Flying Mount"] = "나는 탈것",
Food = "음식",
["Food & Drink"] = "음식과 음료",
Gem = "보석",
["Gem Bag"] = "보석 가방",
Glyph = "문양",
Green = "녹색 (노란+푸른)",
["Ground Mount"] = "지상 탈것",
Gun = "총기",
Guns = "총기류",
Hands = "손",
Head = "머리",
["Held in Off-Hand"] = "보조장비",
Herb = "약초",
Herbalism = "약초채집",
["Herb Bag"] = "약초 가방",
Holiday = "축제용품",
Humanoid = "인간형", -- Needs review
Hunter = "사냥꾼",
Hydraulic = "Hydraulic", -- Needs review
Idol = "우상",
Idols = "우상",
Inscription = "주문각인",
["Inscription Bag"] = "주문각인 가방",
["Item Enchantment"] = "아이템 강화",
["Item Enhancement"] = "아이템 강화",
Jewelcrafting = "보석세공",
Junk = "잡동사니",
Key = "열쇠",
Leather = "가죽",
Leatherworking = "가죽세공",
["Leatherworking Bag"] = "가죽세공 가방",
Legs = "다리",
Libram = "성서",
Librams = "성서",
Mace = "둔기",
Mage = "마법사",
Magic = "마법", -- Needs review
Mail = "사슬",
["Main Hand"] = "주장비",
Materials = "재료",
Meat = "고기",
Mechanical = "기계", -- Needs review
Meta = "얼개",
["Metal & Stone"] = "광물",
Mining = "채광",
["Mining Bag"] = "채광 가방",
Miscellaneous = "기타",
Money = "돈", -- Needs review
Monk = "수도사", -- Needs review
Mount = "탈것",
Mounts = "탈것",
Neck = "목",
["Off Hand"] = "보조장비",
["One-Hand"] = "한손",
["One-Handed Axes"] = "한손 도끼류",
["One-Handed Maces"] = "한손 둔기류",
["One-Handed Swords"] = "한손 도검류",
Orange = "주황색 (노란+붉은)",
Other = "기타",
Paladin = "성기사",
Parts = "부품",
Pet = "애완동물",
Plate = "판금",
Polearm = "장창",
Polearms = "장창류",
Potion = "물약",
Priest = "사제",
Prismatic = "다색",
Projectile = "투사체",
Purple = "보라색 (붉은+푸른)",
Quest = "퀘스트",
Quiver = "화살통",
Ranged = "원거리 장비",
Reagent = "재료",
Recipe = "제조법",
Red = "붉은색",
Relic = "유물",
Riding = "탈것 타기",
Ring = "손가락",
Rogue = "도적",
Scroll = "두루마리",
Shaman = "주술사",
Shield = "방패",
Shields = "방패",
Shirt = "속옷",
Shoulder = "어깨",
Sigils = "인장",
Simple = "일반",
Skinning = "무두질",
["Soul Bag"] = "영혼의 가방",
Staff = "지팡이",
Staves = "지팡이류",
Sword = "도검",
Tabard = "휘장",
Tabards = "휘장",
["Tackle Box"] = "낚시상자",
Tailoring = "재봉술",
Thrown = "투척 무기",
Totem = "토템",
Totems = "토템",
["Trade Goods"] = "직업용품",
Trinket = "장신구",
["Two-Hand"] = "양손",
["Two-Handed Axes"] = "양손 도끼류",
["Two-Handed Maces"] = "양손 둔기류",
["Two-Handed Swords"] = "양손 도검류",
Undead = "언데드", -- Needs review
Waist = "허리",
Wand = "마법봉",
Wands = "마법봉류",
Warlock = "흑마법사",
Warrior = "전사",
Weapon = "무기",
["Weapon Enchantment"] = "무기 마법부여",
Wrist = "손목",
Yellow = "노란색 (노란+푸른)",
}
elseif GAME_LOCALE == "esES" then
lib:SetCurrentTranslations {
Alchemy = "Alquimia",
["Ammo Pouch"] = "Bolsa de munición",
Aquatic = "Agua",
Archaeology = "Arqueología",
Armor = "Armadura",
["Armor Enchantment"] = "Encantamiento de Armadura",
Arrow = "Flecha",
Axe = "Hacha",
Back = "Espalda",
Bag = "Bolsa",
Bandage = "Venda",
Beast = "Bestia",
Blacksmithing = "Herrería",
Blue = "Azul",
Book = "Libro",
Bow = "Arco",
Bows = "Arcos",
Bullet = "Bala",
Chest = "Torso",
Cloth = "Tela",
Cogwheel = "Engranaje",
Companion = "Comapñero",
["Companion Pets"] = "Mascotas",
Companions = "Compañeros",
Consumable = "Consumible",
Container = "Contenedor",
Cooking = "Cocina",
["Cooking Bag"] = "Bolsa de cocina", -- Needs review
Cosmetic = "Cosmetico", -- Needs review
Critter = "Alimaña",
Crossbow = "Ballesta",
Crossbows = "Ballestas",
Dagger = "Daga",
Daggers = "Dagas",
["Death Knight"] = "Caballero de la Muerte",
Devices = "Dispositivos",
Dragonkin = "Dragonante",
Drink = "Bebida",
Druid = "Druída",
Elemental = "Elemental",
Elixir = "Elixir",
Enchant = "Encantamiento",
Enchanting = "Encantamiento",
["Enchanting Bag"] = "Bolsa de encantamiento",
Engineering = "Ingeniería",
["Engineering Bag"] = "Bolsa de ingeniería",
Explosives = "Explosivos",
Feet = "Pies",
["First Aid"] = "Primeros auxilios",
Fish = [=[Pescado
]=],
Fishing = "Pesca",
["Fishing Lure"] = "Cebo de pesca",
["Fishing Pole"] = "Caña de pescar",
["Fishing Poles"] = "Cañas de pescar",
["Fist Weapon"] = "Arma de Puño",
["Fist Weapons"] = "Armas de Puño",
Flask = "Frasco",
Flying = "Volador",
["Flying Mount"] = "Montura Voladora",
Food = "Comida",
["Food & Drink"] = "Comida y bebida",
Gem = "Gema",
["Gem Bag"] = "Bolsa de gemas",
Glyph = "Glifo",
Green = "Verde",
["Ground Mount"] = "Montura Terrestre",
Gun = "Pistola",
Guns = "Pistolas",
Hands = "Manos",
Head = "Cabeza",
["Held in Off-Hand"] = "Sostener con la mano izquierda",
Herb = "Herbalísmo",
Herbalism = "Hebalismo",
["Herb Bag"] = "Bolsa de hierbas",
Holiday = "Festivo",
Humanoid = "Humanoide",
Hunter = "Cazador",
Hydraulic = "Hidráulico",
Idol = "Ídolo",
Idols = "Ídolos",
Inscription = "Inscripción",
["Inscription Bag"] = "Bolsa de inscripción",
["Item Enchantment"] = "Encantamiento de Objeto",
["Item Enhancement"] = "Mejora de Objeto",
Jewelcrafting = "Joyería",
Junk = "Basura",
Key = "Llave",
Leather = "Cuero",
Leatherworking = "Peletería",
["Leatherworking Bag"] = "Bolsa de peletería",
Legs = "Piernas",
Libram = "Tratado",
Librams = "Tratados",
Mace = "Maza",
Mage = "Mago",
Magic = "Magico",
Mail = "Mallas",
["Main Hand"] = "Mano Derecha",
Materials = "Materiales",
Meat = "Carne",
Mechanical = "Mecanico",
Meta = "Meta",
["Metal & Stone"] = "Metal y Piedra",
Mining = "Minería",
["Mining Bag"] = "Bolsa de minería",
Miscellaneous = "Misceláneas",
Money = "Dinero",
Monk = "Monje",
Mount = "Montura",
Mounts = "Monturas",
Neck = "Cuello",
["Off Hand"] = "Mano Izquierda",
["One-Hand"] = "Una Mano",
["One-Handed Axes"] = "Hachas de Una Mano",
["One-Handed Maces"] = "Mazas de Una Mano",
["One-Handed Swords"] = "Espadas de Una Mano",
Orange = "Naranja",
Other = "Otro",
Paladin = "Paladín",
Parts = "Partes",
Pet = "Mascota",
Plate = "Placas",
Polearm = "Arma de asta",
Polearms = "Armas de asta",
Potion = "Poción",
Priest = "Sacerdote",
Prismatic = "Prismático",
Projectile = "Proyectil",
Purple = "Morado",
Quest = "Misión",
Quiver = "Carcaj",
Ranged = "Rango",
Reagent = "Reactivo",
Recipe = "Receta",
Red = "Rojo",
Relic = "Reliquia",
Riding = "Equitación",
Ring = "Anillo",
Rogue = "Pícaro",
Scroll = "Pergamino",
Shaman = "Chamán",
Shield = "Escudo",
Shields = "Escudos",
Shirt = "Camisa",
Shoulder = "Hombros",
Sigils = "Sigilos",
Simple = "Simple",
Skinning = "Desuello",
["Soul Bag"] = "Bolsa de almas",
Staff = "Bastón",
Staves = "Bastones",
Sword = "Espada",
Tabard = "Tabardo",
Tabards = "Tabardo",
["Tackle Box"] = "Maestro del Cebo",
Tailoring = "Sastrería",
Thrown = "Arrojadiza",
Totem = "Tótem",
Totems = "Tótems",
["Trade Goods"] = "Objeto comerciable",
Trinket = "Abalorio",
["Two-Hand"] = "Dos Manos",
["Two-Handed Axes"] = "Hachas a Dos Manos",
["Two-Handed Maces"] = "Mazas a Dos Manos",
["Two-Handed Swords"] = "Espadas a Dos Manos",
Undead = "No-Muerto",
Waist = "Cintura",
Wand = "Varita",
Wands = "Varitas",
Warlock = "Brujo",
Warrior = "Guerrero",
Weapon = "Arma",
["Weapon Enchantment"] = "Encantamiento de Armas",
Wrist = "Muñeca",
Yellow = "Amarillo",
}
elseif GAME_LOCALE == "esMX" then
lib:SetCurrentTranslations {
Alchemy = "Alquímia", -- Needs review
["Ammo Pouch"] = "Bolsa de Munición",
Aquatic = "Acuático", -- Needs review
Archaeology = "Arqueología", -- Needs review
Armor = "Armadura",
["Armor Enchantment"] = "Encantamiento de Armadura",
Arrow = "Flecha",
Axe = "Hacha",
Back = "Espalda",
Bag = "Bolsa",
Bandage = "Venda",
Beast = "Bestia", -- Needs review
Blacksmithing = "Herrería",
Blue = "Azul",
Book = "Libro",
Bow = "Arco",
Bows = "Arcos",
Bullet = "Bala",
Chest = "Torso",
Cloth = "Tela",
Cogwheel = "Engranaje", -- Needs review
Companion = "Compañero", -- Needs review
["Companion Pets"] = "Mascotas de Companía", -- Needs review
Companions = "Compañeros", -- Needs review
Consumable = "Consumible",
Container = "Contenedor",
Cooking = "Cocina",
["Cooking Bag"] = "Bolsa de Cocina", -- Needs review
Cosmetic = "Cosmético", -- Needs review
Critter = "Alimaña", -- Needs review
Crossbow = "Ballesta",
Crossbows = "Ballestas",
Dagger = "Daga",
Daggers = "Dagas",
["Death Knight"] = "Caballero de la Muerte",
Devices = "Dispositivos",
Dragonkin = "Dragonante", -- Needs review
Drink = "Bebida",
Druid = "Druída",
Elemental = "Elemental",
Elixir = "Elixir",
Enchant = "Enchant", -- Needs review
Enchanting = "Encantamiento",
["Enchanting Bag"] = "Bolsa de encantamiento",
Engineering = "Ingeniería",
["Engineering Bag"] = "Bolsa de ingeniería",
Explosives = "Explosivos",
Feet = "Pies",
["First Aid"] = "Primeros auxilios",
Fish = "Fish", -- Needs review
Fishing = "Pesca",
["Fishing Lure"] = "Fishing Lure", -- Needs review
["Fishing Pole"] = "Caña de pescar",
["Fishing Poles"] = "Cañas de pescar",
["Fist Weapon"] = "Arma de Puño",
["Fist Weapons"] = "Armas de Puño",
Flask = "Frasco",
Flying = "Volador", -- Needs review
["Flying Mount"] = "Flying Mount", -- Needs review
Food = "Comida",
["Food & Drink"] = "Comida y bebida",
Gem = "Gema",
["Gem Bag"] = "Bolsa de Gemas",
Glyph = "Glifo",
Green = "Verde",
["Ground Mount"] = "Ground Mount", -- Needs review
Gun = "Pistola",
Guns = "Pistolas",
Hands = "Manos",
Head = "Cabeza",
["Held in Off-Hand"] = "Sostener con la mano izquierda",
Herb = "Herbalísmo",
Herbalism = "Herbalismo", -- Needs review
["Herb Bag"] = "Bolsa de hierbas",
Holiday = "Festivo",
Humanoid = "Humanoide", -- Needs review
Hunter = "Cazador",
Hydraulic = "Hydraulic", -- Needs review
Idol = "Ídolo", -- Needs review
Idols = "Ídolos", -- Needs review
Inscription = "Inscripción", -- Needs review
["Inscription Bag"] = "Bolsa de inscripción",
["Item Enchantment"] = "Item Enchantment", -- Needs review
["Item Enhancement"] = "Mejora de Objeto",
Jewelcrafting = "Joyería",
Junk = "Basura",
Key = "Llave",
Leather = "Cuero",
Leatherworking = "Peletería",
["Leatherworking Bag"] = "Bolsa de Peletería",
Legs = "Piernas",
Libram = "Tratado",
Librams = "Tratados",
Mace = "Maza",
Mage = "Mago",
Magic = "Mágico", -- Needs review
Mail = "Mallas",
["Main Hand"] = "Mano Derecha",
Materials = "Materiales",
Meat = "Carne",
Mechanical = "Mecánico", -- Needs review
Meta = "Meta",
["Metal & Stone"] = "Metal y Piedra",
Mining = "Minería", -- Needs review
["Mining Bag"] = "Bolsa de Minería",
Miscellaneous = "Miscelánea",
Money = "Dinero", -- Needs review
Monk = "Monje", -- Needs review
Mount = "Montura",
Mounts = "Mounts", -- Needs review
Neck = "Cuello",
["Off Hand"] = "Mano Izquierda",
["One-Hand"] = "Una Mano",
["One-Handed Axes"] = "Hachas de Una Mano",
["One-Handed Maces"] = "Mazas de Una Mano",
["One-Handed Swords"] = "Espadas de Una Mano",
Orange = "Naranja",
Other = "Otro",
Paladin = "Paladín",
Parts = "Partes",
Pet = "Mascota",
Plate = "Placas",
Polearm = "Arma de asta",
Polearms = "Armas de asta",
Potion = "Poción",
Priest = "Sacerdote",
Prismatic = "Prismático",
Projectile = "Proyectil",
Purple = "Morado",
Quest = "Misión",
Quiver = "Carcaj",
Ranged = "Rango",
Reagent = "Reactivo",
Recipe = "Receta",
Red = "Rojo",
Relic = "Relíquia", -- Needs review
Riding = "Equitación", -- Needs review
Ring = "Anillo",
Rogue = "Pícaro",
Scroll = "Pergamino",
Shaman = "Chamán",
Shield = "Escudo",
Shields = "Escudos",
Shirt = "Camisa",
Shoulder = "Hombros",
Sigils = "Sigilos",
Simple = "Simple",
Skinning = "Desuello", -- Needs review
["Soul Bag"] = "Bolsa de Almas",
Staff = "Bastón",
Staves = "Bastones",
Sword = "Espada",
Tabard = "Tabardo",
Tabards = "Tabards", -- Needs review
["Tackle Box"] = "Tackle Box", -- Needs review
Tailoring = "Sastrería",
Thrown = "Arrojadiza",
Totem = "Tótem",
Totems = "Tótems",
["Trade Goods"] = "Objeto comerciable",
Trinket = "Abalorio",
["Two-Hand"] = "Dos Manos",
["Two-Handed Axes"] = "Hachas a Dos Manos",
["Two-Handed Maces"] = "Mazas a Dos Manos",
["Two-Handed Swords"] = "Espadas a Dos Manos",
Undead = "No-muerto", -- Needs review
Waist = "Cintura",
Wand = "Varita",
Wands = "Varitas",
Warlock = "Brujo",
Warrior = "Guerrero",
Weapon = "Arma",
["Weapon Enchantment"] = "Encantamiento de Armas",
Wrist = "Muñeca",
Yellow = "Amarillo",
}
elseif GAME_LOCALE == "ptBR" then
lib:SetCurrentTranslations {
Alchemy = "Alquimia",
["Ammo Pouch"] = "Bolsa de Munição", -- Needs review
Aquatic = "Aquático", -- Needs review
Archaeology = "Arqueologia",
Armor = "Armadura",
["Armor Enchantment"] = "Encantamento de Armadura", -- Needs review
Arrow = "Flecha",
Axe = "Machado",
Back = "Costas",
Bag = "Bolsa",
Bandage = "Bandagem",
Beast = "Besta", -- Needs review
Blacksmithing = "Ferraria",
Blue = "Azul",
Book = "Livro",
Bow = "Arco",
Bows = "Arcos",
Bullet = "Bala",
Chest = "Torso",
Cloth = "Tecido",
Cogwheel = "Engrenagem",
Companion = "Mascote",
["Companion Pets"] = "Mascotes", -- Needs review
Companions = "Mascotes",
Consumable = "Consumível",
Container = "Recipiente",
Cooking = "Culinária",
["Cooking Bag"] = "Bolsa de Cozinhar", -- Needs review
Cosmetic = "Cosmético", -- Needs review
Critter = "Bicho", -- Needs review
Crossbow = "Besta",
Crossbows = "Bestas",
Dagger = "Adaga",
Daggers = "Adagas",
["Death Knight"] = "Cavaleiro da Morte",
Devices = "Dispositivos",
Dragonkin = "Draconiano", -- Needs review
Drink = "Bebida",
Druid = "Druida",
Elemental = "Elemental",
Elixir = "Elixir",
Enchant = "Encantamento",
Enchanting = "Encantamento",
["Enchanting Bag"] = "Bolsa de Encantamento",
Engineering = "Engenharia",
["Engineering Bag"] = "Bolsa de Engenharia",
Explosives = "Explosivos",
Feet = "Pés",
["First Aid"] = "Primeiros Socorros",
Fish = "Peixe",
Fishing = "Pescaria",
["Fishing Lure"] = "Isca",
["Fishing Pole"] = "Vara de Pescar",
["Fishing Poles"] = "Varas de Pescar",
["Fist Weapon"] = "Arma de Punho",
["Fist Weapons"] = "Armas de Punho",
Flask = "Frasco",
Flying = "Voador", -- Needs review
["Flying Mount"] = "montaria voadora",
Food = "Comida",
["Food & Drink"] = "Comida e Bebida",
Gem = "Gema",
["Gem Bag"] = "Bolsa de Gemas",
Glyph = "Glifo",
Green = "Verde",
["Ground Mount"] = "montaria terrestre",
Gun = "Arma de fogo",
Guns = "Armas de fogo",
Hands = "Mãos",
Head = "Cabeça",
["Held in Off-Hand"] = "Empunhado na mão secundária",
Herb = "Planta",
Herbalism = "Herborismo",
["Herb Bag"] = "Bolsa de Herborismo",
Holiday = "Feriado",
Humanoid = "Humanoide", -- Needs review
Hunter = "Caçador",
Hydraulic = "Hidráulico",
Idol = "ídolo",
Idols = "ídolos",
Inscription = "Escrivania",
["Inscription Bag"] = "Bolsa de Escrivania",
["Item Enchantment"] = "encantamento de item",
["Item Enhancement"] = "Aperfeiçoamento de Item",
Jewelcrafting = "Joalheria",
Junk = "Sucata",
Key = "Chave",
Leather = "Couro",
Leatherworking = "Couraria",
["Leatherworking Bag"] = "Bolsa de Couraria",
Legs = "Pernas",
Libram = "Incunábulo",
Librams = "Incunábulos",
Mace = "Maça",
Mage = "Mago",
Magic = "Magia", -- Needs review
Mail = "Malha",
["Main Hand"] = "Mão principal",
Materials = "Materiais",
Meat = "Carne",
Mechanical = "Mecânico", -- Needs review
Meta = "Meta",
["Metal & Stone"] = "Metal e Pedra",
Mining = "Mineração",
["Mining Bag"] = "Bolsa de Mineração",
Miscellaneous = "Diversos",
Money = "Dinheiro", -- Needs review
Monk = "Monge", -- Needs review
Mount = "Montaria",
Mounts = "Montarias",
Neck = "Pescoço",
["Off Hand"] = "Mão Secundária",
["One-Hand"] = "Uma Mão",
["One-Handed Axes"] = "Machados de Uma Mão",
["One-Handed Maces"] = "Maças de Uma Mão",
["One-Handed Swords"] = "Espadas de Uma Mão",
Orange = "Laranja",
Other = "Outro",
Paladin = "Paladino",
Parts = "Peças",
Pet = "Mascote",
Plate = "Placas",
Polearm = "Arma de Haste",
Polearms = "Armas de Haste",
Potion = "Poção",
Priest = "Sacerdote",
Prismatic = "Prismática",
Projectile = "Projétil",
Purple = "Roxa",
Quest = "Missão",
Quiver = "Aljava",
Ranged = "Longo alcance",
Reagent = "Reagente",
Recipe = "Receita",
Red = "Vermelha",
Relic = "Relíquia",
Riding = "cavalgar",
Ring = "Anel",
Rogue = "Ladino",
Scroll = "Pergaminho",
Shaman = "Xamã",
Shield = "Escudo",
Shields = "Escudos",
Shirt = "Camisa",
Shoulder = "Ombros",
Sigils = "Signos",
Simple = "Simples",
Skinning = "Esfolamento",
["Soul Bag"] = "Bolsa de Almas",
Staff = "Cajado",
Staves = "Báculos",
Sword = "Espada",
Tabard = "Tabardo",
Tabards = "Tabardos",
["Tackle Box"] = "Caixa de Apetrechos",
Tailoring = "Alfaiataria",
Thrown = "Arremesso",
Totem = "totem",
Totems = "totens",
["Trade Goods"] = "Mercadorias",
Trinket = "Berloque",
["Two-Hand"] = "Duas Mãos",
["Two-Handed Axes"] = "Machados de Duas Mãos",
["Two-Handed Maces"] = "Maças de Duas Mãos",
["Two-Handed Swords"] = "Espadas de Duas Mãos",
Undead = "Morto-Vivo", -- Needs review
Waist = "Cintura",
Wand = "Varinha",
Wands = "Varinhas",
Warlock = "Bruxo",
Warrior = "Guerreiro",
Weapon = "Arma",
["Weapon Enchantment"] = "Encantamento de arma",
Wrist = "Pulso",
Yellow = "Amarela",
}
elseif GAME_LOCALE == "itIT" then
lib:SetCurrentTranslations {
Alchemy = "Alchimia",
["Ammo Pouch"] = "Sacca per munizioni",
Aquatic = "Acquatico",
Archaeology = "Archeologia",
Armor = "Armatura",
["Armor Enchantment"] = "Incantamento Armatura",
Arrow = "Freccia",
Axe = "Ascia",
Back = "Schiena",
Bag = "Sacca",
Bandage = "Benda",
Beast = "Bestiale",
Blacksmithing = "Forgiatura",
Blue = "Blu",
Book = "Libro",
Bow = "Arco",
Bows = "Archi",
Bullet = "Proiettile",
Chest = "Torso",
Cloth = "Stoffa",
Cogwheel = "Ingranaggio",
Companion = "Mascotte",
["Companion Pets"] = "Mascotte da Compagnia",
Companions = "Mascottes",
Consumable = "Consumabile",
Container = "Contenitore",
Cooking = "Cucina",
["Cooking Bag"] = "Sacca da Cuoco",
Cosmetic = "Cosmetico",
Critter = "Animale",
Crossbow = "Balestra",
Crossbows = "Balestre",
Dagger = "Pugnale",
Daggers = "Pugnali",
["Death Knight"] = "Cavaliere della Morte",
Devices = "Dispositivi",
Dragonkin = "Dragoide",
Drink = "Bevanda",
Druid = "Druido",
Elemental = "Elementale",
Elixir = "Elisir",
Enchant = "Incantamento",
Enchanting = "Incantamento",
["Enchanting Bag"] = "Sacca da Incantatore",
Engineering = "Ingegneria",
["Engineering Bag"] = "Sacca da Ingegnere",
Explosives = "Esplosivi",
Feet = "Piedi",
["First Aid"] = "Primo Soccorso",
Fish = "Pesce",
Fishing = "Pesca",
["Fishing Lure"] = "Amo da Pesca",
["Fishing Pole"] = "Canna da Pesca",
["Fishing Poles"] = "Canne da Pesca",
["Fist Weapon"] = "Tirapugni",
["Fist Weapons"] = "Tirapugni",
Flask = "Tonico",
Flying = "Volante",
["Flying Mount"] = "Cavalcatura Volante",
Food = "Cibo",
["Food & Drink"] = "Cibi e bevande",
Gem = "Gemma",
["Gem Bag"] = "Borsa per Gemme",
Glyph = "Glifo",
Green = "Verde",
["Ground Mount"] = "Cavalcatura da Terra",
Gun = "Arma da fuoco",
Guns = "Armi da fuoco",
Hands = "Mani",
Head = "Testa",
["Held in Off-Hand"] = "da Tenere con Mano Secondaria",
Herb = "Erba",
Herbalism = "Erbalismo",
["Herb Bag"] = "Sacca da Erbalista",
Holiday = "Festività",
Humanoid = "Umanoide",
Hunter = "Cacciatore",
Hydraulic = "Idraulico",
Idol = "Idolo",
Idols = "Idoli",
Inscription = "Runografia",
["Inscription Bag"] = "Sacca da Runografo",
["Item Enchantment"] = "Incantamento per Oggetti",
["Item Enhancement"] = "Incanto per Oggetto",
Jewelcrafting = "Oreficeria",
Junk = "Cianfrusaglia",
Key = "Chiave",
Leather = "Cuoio",
Leatherworking = "Conceria",
["Leatherworking Bag"] = "Sacca da Conciatore",
Legs = "Gambe",
Libram = "Tomo",
Librams = "Tomi",
Mace = "Mazza",
Mage = "Mago",
Magic = "Magico",
Mail = "Maglia",
["Main Hand"] = "Mano Principale",
Materials = "Materiali",
Meat = "Carne",
Mechanical = "Meccanico",
Meta = "Meta",
["Metal & Stone"] = "Metallo e Pietra",
Mining = "Estrazione",
["Mining Bag"] = "Sacca da Minatore",
Miscellaneous = "Varie",
Money = "Denaro",
Monk = "Monaco",
Mount = "Cavalcatura",
Mounts = "Cavalcature",
Neck = "Collo",
["Off Hand"] = "Mano Secondaria",
["One-Hand"] = "Ad Una Mano",
["One-Handed Axes"] = "Asce ad una mano",
["One-Handed Maces"] = "Mazze ad una mano",
["One-Handed Swords"] = "Spade ad una mano",
Orange = "Arancione",
Other = "Altro",
Paladin = "Paladino",
Parts = "Componenti",
Pet = "Famiglio",
Plate = "Piastre",
Polearm = "Asta",
Polearms = "Armi ad Asta",
Potion = "Pozione",
Priest = "Prete",
Prismatic = "Prismatico",
Projectile = "Proiettile",
Purple = "Viola",
Quest = "Missione",
Quiver = "Faretra",
Ranged = "a Distanza",
Reagent = "Reagente",
Recipe = "Ricetta",
Red = "Rosso",
Relic = "Reliquia",
Riding = "Equitazione",
Ring = "Anello",
Rogue = "Ladro",
Scroll = "Pergamena",
Shaman = "Sciamano",
Shield = "Scudo",
Shields = "Scudi",
Shirt = "Maglietta",
Shoulder = "Spalle",
Sigils = "Sigilli",
Simple = "Semplice",
Skinning = "Scuoiatura",
["Soul Bag"] = "Sacca per Anima",
Staff = "Bastone",
Staves = "Bastoni",
Sword = "Spada",
Tabard = "Insegna",
Tabards = "Insegne",
["Tackle Box"] = "Cassetta",
Tailoring = "Sartoria",
Thrown = "da Lancio",
Totem = "Totem",
Totems = "Totems",
["Trade Goods"] = "Beni commerciali",
Trinket = "Orecchino",
["Two-Hand"] = "a Due Mani",
["Two-Handed Axes"] = "Asce a Due Mani",
["Two-Handed Maces"] = "Mazze a Due Mani",
["Two-Handed Swords"] = "Spade a Due Mani",
Undead = "Non Morto",
Waist = "Cintura",
Wand = "Bacchetta",
Wands = "Bacchette",
Warlock = "Stregone",
Warrior = "Guerriero",
Weapon = "Arma",
["Weapon Enchantment"] = "Incantamento per Arma",
Wrist = "Polsi",
Yellow = "Giallo",
}
elseif GAME_LOCALE == "ruRU" then
lib:SetCurrentTranslations {
Alchemy = "Алхимия",
["Ammo Pouch"] = "Подсумок",
Aquatic = "Водный",
Archaeology = "Археология",
Armor = "Доспехи",
["Armor Enchantment"] = "Чары для оружия",
Arrow = "Стрелы",
Axe = "Топор",
Back = "Спина",
Bag = "Сумка",
Bandage = "Бинты",
Beast = "Звери",
Blacksmithing = "Кузнечное дело",
Blue = "Синий",
Book = "Книга",
Bow = "Лук",
Bows = "Луки",
Bullet = "Пули",
Chest = "Грудь",
Cloth = "Ткань",
Cogwheel = "Зубчатое колесо",
Companion = "Спутник",
["Companion Pets"] = "Петомцы",
Companions = "Спутники",
Consumable = "Расходуемые",
Container = "Сумки",
Cooking = "Кулинария",
["Cooking Bag"] = "Сумка повара",
Cosmetic = "Косметика",
Critter = "Существа",
Crossbow = "Арбалет",
Crossbows = "Арбалеты",
Dagger = "Кинжал",
Daggers = "Кинжалы",
["Death Knight"] = "Рыцарь смерти",
Devices = "Устройства",
Dragonkin = "Драконий",
Drink = "Питье",
Druid = "Друид",
Elemental = "Стихии",
Elixir = "Эликсир",
Enchant = "Чары",
Enchanting = "Наложение чар",
["Enchanting Bag"] = "Сумка зачаровывателя",
Engineering = "Инженерное дело",
["Engineering Bag"] = "Сумка инженера",
Explosives = "Взрывчатка",
Feet = "Ступни",
["First Aid"] = "Первая помощь",
Fish = "Рыба",
Fishing = "Рыбная ловля",
["Fishing Lure"] = "Рыбацкая приманка",
["Fishing Pole"] = "Удочка",
["Fishing Poles"] = "Удочки",
["Fist Weapon"] = "Кистевое",
["Fist Weapons"] = "Кистевое",
Flask = "Фляга",
Flying = "Летающий",
["Flying Mount"] = "Летающий транспорт",
Food = "Еда",
["Food & Drink"] = "Еда и напитки",
Gem = "Самоцветы",
["Gem Bag"] = "Сумка ювелира",
Glyph = "Символ",
Green = "Зеленый",
["Ground Mount"] = "Наземный транспорт",
Gun = "Огнестрельное",
Guns = "Огнестрельное",
Hands = "Кисти рук",
Head = "Голова",
["Held in Off-Hand"] = "Левая рука",
Herb = "Трава",
Herbalism = "Травничество",
["Herb Bag"] = "Сумка травника",
Holiday = "Праздник",
Humanoid = "Гуманоид",
Hunter = "Охотник",
Hydraulic = "Оскверненный ша",
Idol = "Идол",
Idols = "Идолы",
Inscription = "Начертание",
["Inscription Bag"] = "Сумка начертателя",
["Item Enchantment"] = "Улучшение",
["Item Enhancement"] = "Улучшение",
Jewelcrafting = "Ювелирное дело",
Junk = "Мусор",
Key = "Ключ",
Leather = "Кожа",
Leatherworking = "Кожевничество",
["Leatherworking Bag"] = "Сумка кожевника",
Legs = "Ноги",
Libram = "Манускрипт",
Librams = "Манускрипты",
Mace = "Дробящее",
Mage = "Маг",
Magic = "Магичский",
Mail = "Кольчуга",
["Main Hand"] = "Правая рука",
Materials = "Материалы",
Meat = "Мясо",
Mechanical = "Механический",
Meta = "Особый",
["Metal & Stone"] = "Металл и камень",
Mining = "Горное дело",
["Mining Bag"] = "Сумка шахтера",
Miscellaneous = "Разное",
Money = "Деньги",
Monk = "Монах",
Mount = "Верховые животные",
Mounts = "Верховые животные",
Neck = "Шея",
["Off Hand"] = "Левая рука",
["One-Hand"] = "Одноручное",
["One-Handed Axes"] = "Одноручные топоры",
["One-Handed Maces"] = "Одноручное дробящее",
["One-Handed Swords"] = "Одноручные мечи",
Orange = "Оранжевый",
Other = "Другое",
Paladin = "Паладин",
Parts = "Детали",
Pet = "Питомцы",
Plate = "Латы",
Polearm = "Древковое",
Polearms = "Древковое",
Potion = "Зелье",
Priest = "Жрец",
Prismatic = "Радужный",
Projectile = "Боеприпасы",
Purple = "Фиолетовый",
Quest = "Задания",
Quiver = "Амуниция",
Ranged = "Для оружия дальнего боя",
Reagent = "Реагенты",
Recipe = "Рецепты",
Red = "Красный",
Relic = "Реликвия",
Riding = "Верховая езда",
Ring = "Палец",
Rogue = "Разбойник",
Scroll = "Свиток",
Shaman = "Шаман",
Shield = "Щит",
Shields = "Щиты",
Shirt = "Рубашка",
Shoulder = "Плечо",
Sigils = "Печати",
Simple = "Простой",
Skinning = "Снятие шкур",
["Soul Bag"] = "Сумка душ",
Staff = "Посох",
Staves = "Посохи",
Sword = "Меч",
Tabard = "Гербовая накидка",
Tabards = "Накидки",
["Tackle Box"] = "Ящик для рыболовной снасти",
Tailoring = "Портняжное дело",
Thrown = "Метательное",
Totem = "Тотем",
Totems = "Тотемы",
["Trade Goods"] = "Хозяйственные товары",
Trinket = "Аксессуар",
["Two-Hand"] = "Двуручное",
["Two-Handed Axes"] = "Двуручные топоры",
["Two-Handed Maces"] = "Двуручное дробящее",
["Two-Handed Swords"] = "Двуручные мечи",
Undead = "Нежить",
Waist = "Пояс",
Wand = "Жезл",
Wands = "Жезлы",
Warlock = "Чернокнижник",
Warrior = "Воин",
Weapon = "Оружие",
["Weapon Enchantment"] = "Чары для доспехов",
Wrist = "Запястья",
Yellow = "Желтый",
}
elseif GAME_LOCALE == "zhCN" then
lib:SetCurrentTranslations {
Alchemy = "炼金术",
["Ammo Pouch"] = "弹药袋",
Aquatic = "水栖",
Archaeology = "考古学",
Armor = "护甲",
["Armor Enchantment"] = "护甲强化",
Arrow = "箭",
Axe = "斧",
Back = "背部",
Bag = "容器",
Bandage = "绷带",
Beast = "野兽",
Blacksmithing = "锻造",
Blue = "蓝色",
Book = "书籍",
Bow = "弓",
Bows = "弓",
Bullet = "子弹",
Chest = "胸部",
Cloth = "布甲",
Cogwheel = "齿轮",
Companion = "小伙伴",
["Companion Pets"] = "小伙伴",
Companions = "小伙伴",
Consumable = "消耗品",
Container = "容器",
Cooking = "烹饪",
["Cooking Bag"] = "烹饪包",
Cosmetic = "装饰品",
Critter = "小动物",
Crossbow = "弩",
Crossbows = "弩",
Dagger = "匕首",
Daggers = "匕首",
["Death Knight"] = "死亡骑士",
Devices = "装置",
Dragonkin = "龙类",
Drink = "饮料",
Druid = "德鲁伊",
Elemental = "元素",
Elixir = "药剂",
Enchant = "附魔",
Enchanting = "附魔",
["Enchanting Bag"] = "附魔材料袋",
Engineering = "工程学",
["Engineering Bag"] = "工程学材料袋",
Explosives = "爆炸物",
Feet = "脚",
["First Aid"] = "急救",
Fish = "魚",
Fishing = "钓鱼",
["Fishing Lure"] = "鱼饵",
["Fishing Pole"] = "鱼竿",
["Fishing Poles"] = "鱼竿",
["Fist Weapon"] = "拳套",
["Fist Weapons"] = "拳套",
Flask = "合剂",
Flying = "飞行",
["Flying Mount"] = "飞行坐骑",
Food = "食物",
["Food & Drink"] = "食物和饮料",
Gem = "宝石",
["Gem Bag"] = "宝石袋",
Glyph = "雕文",
Green = "绿色",
["Ground Mount"] = "地面坐骑",
Gun = "枪械",
Guns = "枪械",
Hands = "手",
Head = "头部",
["Held in Off-Hand"] = "副手物品",
Herb = "草药",
Herbalism = "草药学",
["Herb Bag"] = "草药袋",
Holiday = "节日",
Humanoid = "人型",
Hunter = "猎人",
Hydraulic = "液压",
Idol = "神像",
Idols = "神像",
Inscription = "铭文",
["Inscription Bag"] = "铭文包",
["Item Enchantment"] = "物品强化",
["Item Enhancement"] = "物品强化",
Jewelcrafting = "珠宝加工",
Junk = "垃圾",
Key = "钥匙",
Leather = "皮甲",
Leatherworking = "制皮",
["Leatherworking Bag"] = "制皮材料袋",
Legs = "腿部",
Libram = "圣契",
Librams = "圣契",
Mace = "锤",
Mage = "法师",
Magic = "魔法",
Mail = "锁甲",
["Main Hand"] = "主手",
Materials = "原料",
Meat = "肉类",
Mechanical = "机械",
Meta = "多彩",
["Metal & Stone"] = "金属和矿石",
Mining = "采矿",
["Mining Bag"] = "矿石袋",
Miscellaneous = "其它",
Money = "金钱",
Monk = "武僧",
Mount = "坐骑",
Mounts = "坐骑",
Neck = "颈部",
["Off Hand"] = "副手",
["One-Hand"] = "单手",
["One-Handed Axes"] = "单手斧",
["One-Handed Maces"] = "单手锤",
["One-Handed Swords"] = "单手剑",
Orange = "橙色",
Other = "其它",
Paladin = "圣骑士",
Parts = "零件",
Pet = "宠物",
Plate = "板甲",
Polearm = "长柄武器",
Polearms = "长柄武器",
Potion = "药水",
Priest = "牧师",
Prismatic = "棱彩",
Projectile = "弹药",
Purple = "紫色",
Quest = "任务",
Quiver = "箭袋",
Ranged = "远程",
Reagent = "材料",
Recipe = "配方",
Red = "红色",
Relic = "圣物",
Riding = "骑术",
Ring = "手指",
Rogue = "潜行者",
Scroll = "卷轴",
Shaman = "萨满祭司",
Shield = "盾牌",
Shields = "盾牌",
Shirt = "衬衫",
Shoulder = "肩部",
Sigils = "魔印",
Simple = "简易",
Skinning = "剥皮",
["Soul Bag"] = "灵魂袋",
Staff = "法杖",
Staves = "法杖",
Sword = "剑",
Tabard = "战袍",
Tabards = "战袍",
["Tackle Box"] = "工具箱 ",
Tailoring = "裁缝",
Thrown = "投掷武器",
Totem = "图腾",
Totems = "图腾",
["Trade Goods"] = "商品",
Trinket = "饰品",
["Two-Hand"] = "双手",
["Two-Handed Axes"] = "双手斧",
["Two-Handed Maces"] = "双手锤",
["Two-Handed Swords"] = "双手剑",
Undead = "亡灵",
Waist = "腰部",
Wand = "魔杖",
Wands = "魔杖",
Warlock = "术士",
Warrior = "战士",
Weapon = "武器",
["Weapon Enchantment"] = "武器强化",
Wrist = "手腕",
Yellow = "黄色",
}
elseif GAME_LOCALE == "zhTW" then
lib:SetCurrentTranslations {
Alchemy = "鍊金術",
["Ammo Pouch"] = "彈藥包",
Aquatic = "水棲生物",
Archaeology = "考古學",
Armor = "護甲",
["Armor Enchantment"] = "護甲附魔",
Arrow = "箭",
Axe = "斧",
Back = "背部",
Bag = "容器",
Bandage = "繃帶",
Beast = "野獸",
Blacksmithing = "鍛造",
Blue = "藍色",
Book = "書籍",
Bow = "弓",
Bows = "弓",
Bullet = "子彈",
Chest = "胸部",
Cloth = "布甲",
Cogwheel = "榫輪",
Companion = "夥伴",
["Companion Pets"] = "寵物",
Companions = "夥伴們",
Consumable = "消耗品",
Container = "容器",
Cooking = "烹飪",
["Cooking Bag"] = "烹飪包",
Cosmetic = "造型",
Critter = "小動物",
Crossbow = "弩",
Crossbows = "弩",
Dagger = "匕首",
Daggers = "匕首",
["Death Knight"] = "死亡騎士",
Devices = "裝置",
Dragonkin = "龍類生物",
Drink = "飲料",
Druid = "德魯伊",
Elemental = "元素材料",
Elixir = "藥劑",
Enchant = "附魔",
Enchanting = "附魔",
["Enchanting Bag"] = "附魔包",
Engineering = "工程學",
["Engineering Bag"] = "工程包",
Explosives = "爆炸物",
Feet = "腳",
["First Aid"] = "急救",
Fish = "釣魚",
Fishing = "釣魚",
["Fishing Lure"] = "魚餌",
["Fishing Pole"] = "魚竿",
["Fishing Poles"] = "魚竿",
["Fist Weapon"] = "拳套",
["Fist Weapons"] = "拳套",
Flask = "精煉藥劑",
Flying = "飛行生物",
["Flying Mount"] = "飛行坐騎",
Food = "食物",
["Food & Drink"] = "食物和飲料",
Gem = "寶石",
["Gem Bag"] = "寶石包",
Glyph = "雕紋",
Green = "綠色",
["Ground Mount"] = "陸行座騎",
Gun = "槍械",
Guns = "槍械",
Hands = "手",
Head = "頭部",
["Held in Off-Hand"] = "副手物品",
Herb = "草藥",
Herbalism = "草藥學",
["Herb Bag"] = "草藥包",
Holiday = "節慶用品",
Humanoid = "人形生物",
Hunter = "獵人",
Hydraulic = "液壓",
Idol = "塑像",
Idols = "塑像",
Inscription = "銘文學",
["Inscription Bag"] = "銘文包",
["Item Enchantment"] = "物品附魔",
["Item Enhancement"] = "物品強化",
Jewelcrafting = "珠寶設計",
Junk = "垃圾",
Key = "鑰匙",
Leather = "皮甲",
Leatherworking = "製皮",
["Leatherworking Bag"] = "製皮包",
Legs = "腿部",
Libram = "聖契",
Librams = "聖契",
Mace = "錘",
Mage = "法師",
Magic = "魔法生物",
Mail = "鎖甲",
["Main Hand"] = "主手",
Materials = "原料",
Meat = "肉類",
Mechanical = "機械生物",
Meta = "變換",
["Metal & Stone"] = "金屬與石頭",
Mining = "採礦",
["Mining Bag"] = "礦石包",
Miscellaneous = "其他",
Money = "金錢",
Monk = "武僧",
Mount = "座騎",
Mounts = "座騎",
Neck = "頸部",
["Off Hand"] = "副手",
["One-Hand"] = "單手",
["One-Handed Axes"] = "單手斧",
["One-Handed Maces"] = "單手錘",
["One-Handed Swords"] = "單手劍",
Orange = "橘色",
Other = "其他",
Paladin = "聖騎士",
Parts = "零件",
Pet = "寵物",
Plate = "鎧甲",
Polearm = "長柄武器",
Polearms = "長柄武器",
Potion = "藥水",
Priest = "牧師",
Prismatic = "稜彩",
Projectile = "彈藥",
Purple = "紫色",
Quest = "任務",
Quiver = "箭袋",
Ranged = "遠程",
Reagent = "施法材料",
Recipe = "配方",
Red = "紅色",
Relic = "聖物",
Riding = "騎術",
Ring = "手指",
Rogue = "盜賊",
Scroll = "卷軸",
Shaman = "薩滿",
Shield = "盾牌",
Shields = "盾牌",
Shirt = "襯衣",
Shoulder = "肩部",
Sigils = "符印",
Simple = "簡單",
Skinning = "剝皮",
["Soul Bag"] = "靈魂裂片包",
Staff = "法杖",
Staves = "法杖",
Sword = "劍",
Tabard = "外袍",
Tabards = "外袍",
["Tackle Box"] = "工具箱",
Tailoring = "裁縫",
Thrown = "投擲武器",
Totem = "圖騰",
Totems = "圖騰",
["Trade Goods"] = "商品",
Trinket = "飾品",
["Two-Hand"] = "雙手",
["Two-Handed Axes"] = "雙手斧",
["Two-Handed Maces"] = "雙手錘",
["Two-Handed Swords"] = "雙手劍",
Undead = "不死生物",
Waist = "腰部",
Wand = "魔杖",
Wands = "魔杖",
Warlock = "術士",
Warrior = "戰士",
Weapon = "武器",
["Weapon Enchantment"] = "武器附魔",
Wrist = "手腕",
Yellow = "黃色",
}
else
error(("%s: Locale %q not supported"):format(MAJOR_VERSION, GAME_LOCALE))
end
| mit |
TerminalShell/zombiesurvival | entities/entities/projectile_poisonspit/init.lua | 1 | 1755 | AddCSLuaFile("cl_init.lua")
AddCSLuaFile("shared.lua")
include("shared.lua")
function ENT:Initialize()
self.DeathTime = CurTime() + 30
self:SetModel("models/props/cs_italy/orange.mdl")
self:PhysicsInitSphere(1)
self:SetSolid(SOLID_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_PROJECTILE)
self:SetColor(Color(0, 255, 0, 255))
self:SetCustomCollisionCheck(true)
local phys = self:GetPhysicsObject()
if phys:IsValid() then
phys:SetMass(4)
phys:SetBuoyancyRatio(0.002)
phys:EnableMotion(true)
phys:Wake()
end
end
function ENT:Think()
if self.PhysicsData then
self:Explode(self.PhysicsData.HitPos, self.PhysicsData.HitNormal, self.PhysicsData.HitEntity)
end
if self.DeathTime <= CurTime() then
self:Remove()
end
end
function ENT:Explode(vHitPos, vHitNormal, eHitEntity)
if self.Exploded then return end
self.Exploded = true
self.DeathTime = 0
local owner = self:GetOwner()
if not owner:IsValid() then owner = self end
vHitPos = vHitPos or self:GetPos()
vHitNormal = vHitNormal or Vector(0, 0, 1)
if eHitEntity:IsValid() then
eHitEntity:PoisonDamage(15, owner, self)
if eHitEntity:IsPlayer() and eHitEntity:Team() ~= owner:Team() then
local attach = eHitEntity:GetAttachment(1)
if attach then
if vHitPos:Distance(attach.Pos) <= 18 then
eHitEntity:PlayEyePoisonedSound()
local status = eHitEntity:GiveStatus("confusion")
if status then
status.EyeEffect = true
end
end
end
end
end
local effectdata = EffectData()
effectdata:SetOrigin(vHitPos)
effectdata:SetNormal(vHitNormal)
util.Effect("spithit", effectdata)
end
function ENT:PhysicsCollide(data, phys)
if not self:HitFence(data, phys) then
self.PhysicsData = data
end
self:NextThink(CurTime())
end
| gpl-3.0 |
RyMarq/Zero-K | scripts/planeheavyfighter.lua | 1 | 3803 | include "constants.lua"
--pieces
local base = piece "base"
local wingR, wingL, wingtipR, wingtipL = piece("wingr", "wingl", "wingtip1", "wingtip2")
local engineR, engineL, thrust1, thrust2, thrust3 = piece("jetr", "jetl", "thrust1", "thrust2", "thrust3")
local missR, missL = piece("m1", "m2")
local smokePiece = {base, engineL, engineR}
--constants
--variables
local gun = false
local RESTORE_DELAY = 250
local FIRE_SLOWDOWN = tonumber(UnitDef.customParams.combat_slowdown)
--signals
local SIG_Aim = 1
local SIG_RESTORE = 2
----------------------------------------------------------
local function getState()
local state = Spring.GetUnitStates(unitID)
return state and state.active
end
function script.Create()
Turn(thrust1, x_axis, -math.rad(90), 1)
Turn(thrust2, x_axis, -math.rad(90), 1)
StartThread(GG.Script.SmokeUnit, unitID, smokePiece)
end
function script.StartMoving()
Turn(engineL, z_axis, -1.57, 1)
Turn(engineR, z_axis, 1.57, 1)
Turn(engineL, y_axis, -1.57, 1)
Turn(engineR, y_axis, 1.57, 1)
Turn(engineL, x_axis, 0, 1)
Turn(engineR, x_axis, 0, 1)
end
function script.StopMoving()
Turn(engineL, z_axis, 0, 1)
Turn(engineR, z_axis, 0, 1)
Turn(engineL, y_axis, 0, 1)
Turn(engineR, y_axis, 0, 1)
Turn(engineL, x_axis, 0, 1)
Turn(engineR, x_axis, 0, 1)
end
function script.QueryWeapon(num)
if gun then
return missR
else
return missL
end
end
function script.AimFromWeapon(num)
return base
end
function script.AimWeapon(num, heading, pitch)
return not (GetUnitValue(COB.CRASHING) == 1)
end
function script.EndBurst(num)
gun = not gun
end
local function RestoreAfterDelay()
Signal(SIG_RESTORE)
SetSignalMask(SIG_RESTORE)
if getState() then
Turn(engineL, z_axis, -1.2, 1)
Turn(engineR, z_axis, 1.2, 1)
Turn(engineL, y_axis, -1.2, 1)
Turn(engineR, y_axis, 1.2, 1)
Turn(engineL, x_axis, 0.6, 1)
Turn(engineR, x_axis, 0.6, 1)
end
Sleep(RESTORE_DELAY)
Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", 1)
Spring.SetUnitRulesParam(unitID, "selfTurnSpeedChange", 1)
-- Don't ask me why this must be called twice for planes, Spring is crazy
GG.UpdateUnitAttributes(unitID)
GG.UpdateUnitAttributes(unitID)
if getState() then
script.StartMoving()
else
script.StopMoving()
end
end
function script.BlockShot(num)
if GetUnitValue(GG.Script.CRASHING) == 1 then
return true
else
if Spring.GetUnitRulesParam(unitID, "selfMoveSpeedChange") ~= FIRE_SLOWDOWN then
Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", FIRE_SLOWDOWN)
Spring.SetUnitRulesParam(unitID, "selfTurnSpeedChange", 1/FIRE_SLOWDOWN)
GG.UpdateUnitAttributes(unitID)
end
StartThread(RestoreAfterDelay)
return false
end
end
function OnLoadGame()
Spring.SetUnitRulesParam(unitID, "selfMoveSpeedChange", 1)
Spring.SetUnitRulesParam(unitID, "selfTurnSpeedChange", 1)
GG.UpdateUnitAttributes(unitID)
end
function script.Killed(recentDamage, maxHealth)
local severity = recentDamage/maxHealth
if severity < 0.25 then
Explode(base, SFX.NONE)
Explode(wingL, SFX.NONE)
Explode(wingR, SFX.NONE)
return 1
elseif severity < 0.5 or (Spring.GetUnitMoveTypeData(unitID).aircraftState == "crashing") then
Explode(base, SFX.NONE)
Explode(engineL, SFX.SMOKE)
Explode(engineR, SFX.SMOKE)
Explode(wingL, SFX.NONE)
Explode(wingR, SFX.NONE)
return 1
elseif severity < 0.75 then
Explode(engineL, SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
Explode(engineR, SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
Explode(wingL, SFX.FALL + SFX.SMOKE)
Explode(wingR, SFX.FALL + SFX.SMOKE)
return 2
else
Explode(base, SFX.SHATTER)
Explode(engineL, SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
Explode(engineR, SFX.SMOKE + SFX.FIRE + SFX.EXPLODE)
Explode(wingL, SFX.SMOKE + SFX.EXPLODE)
Explode(wingR, SFX.SMOKE + SFX.EXPLODE)
return 2
end
end
| gpl-2.0 |
NPLPackages/paracraft | script/kids/3DMapSystemData/Item_App.lua | 1 | 2383 | --[[
Title: an unknown item
Author(s): LiXizhi
Date: 2009/2/3
Desc:
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/kids/3DMapSystemData/Item_App.lua");
local dummyItem = Map3DSystem.Item.Item_App:new({appkey=Map3DSystem.App.appkeys["Creator"]});
Map3DSystem.Item.ItemManager:AddItem(dummyItem);
------------------------------------------------------------
]]
NPL.load("(gl)script/kids/3DMapSystemData/ItemBase.lua");
local Item_App = commonlib.inherit(Map3DSystem.Item.ItemBase, {type=Map3DSystem.Item.Types.App});
commonlib.setfield("Map3DSystem.Item.Item_App", Item_App)
---------------------------------
-- functions
---------------------------------
-- Get the Icon of this object
-- @param callbackFunc: function (filename) end. if nil, it will return the icon texture path. otherwise it will use the callback,since the icon may not be immediately available at call time.
function Item_App:GetIcon(callbackFunc)
if(self.icon) then
return self.icon;
elseif(self.appkey or self.app) then
self.app = self.app or Map3DSystem.App.AppManager.GetApp(self.appkey);
if(self.app) then
self.icon = self.app.icon or self.app.Icon;
return self.icon;
end
else
return Map3DSystem.Item.ItemBase:GetIcon(callbackFunc);
end
end
-- When this item is clicked
function Item_App:OnClick(mouseButton)
Map3DSystem.App.Commands.Call(Map3DSystem.options.SwitchAppCommand, self.appkey);
end
-- Get the tooltip of this object
-- @param callbackFunc: function (text) end. if nil, it will return the text. otherwise it will use the callback,since the icon may not be immediately available at call time.
function Item_App:GetTooltip(callbackFunc)
if(self.tooltip) then
return self.tooltip;
elseif(self.appkey or self.app) then
self.app = self.app or Map3DSystem.App.AppManager.GetApp(self.appkey);
if(self.app) then
self.tooltip = self.app.Title;
return self.tooltip;
end
else
return Map3DSystem.Item.ItemBase:GetTooltip(callbackFunc);
end
end
function Item_App:GetSubTitle()
if(self.subtitle) then
return self.subtitle;
elseif(self.appkey or self.app) then
self.app = self.app or Map3DSystem.App.AppManager.GetApp(self.appkey);
if(self.app) then
self.subtitle = self.app.SubTitle;
return self.subtitle;
end
else
return Map3DSystem.Item.ItemBase:GetSubTitle(callbackFunc);
end
end | gpl-2.0 |
pakoito/ToME---t-engine4 | game/engines/default/engine/ui/List.lua | 3 | 6958 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
local Base = require "engine.ui.Base"
local Focusable = require "engine.ui.Focusable"
local Slider = require "engine.ui.Slider"
--- A generic UI list
module(..., package.seeall, class.inherit(Base, Focusable))
function _M:init(t)
self.list = assert(t.list, "no list list")
self.w = assert(t.width, "no list width")
self.h = t.height
self.nb_items = t.nb_items
assert(self.h or self.nb_items, "no list height/nb_items")
self.fct = t.fct
self.on_select = t.select
self.on_drag = t.on_drag
self.display_prop = t.display_prop or "name"
self.scrollbar = t.scrollbar
self.all_clicks = t.all_clicks
Base.init(self, t)
end
function _M:generate()
self.mouse:reset()
self.key:reset()
self.sel = 1
self.scroll = 1
self.max = #self.list
local fw, fh = self.w, self.font_h + 6
self.fw, self.fh = fw, fh
if not self.surf then self.surf = core.display.newSurface(fw, fh) end
local s = self.surf
self.frame = self:makeFrame(nil, fw, fh)
self.frame_sel = self:makeFrame("ui/selector-sel", fw, fh)
self.frame_usel = self:makeFrame("ui/selector", fw, fh)
if not self.h then self.h = self.nb_items * fh end
self.max_display = math.floor(self.h / fh)
-- Draw the scrollbar
if self.scrollbar then
self.scrollbar = Slider.new{size=self.h - fh, max=self.max}
end
-- Draw the list items
for i, item in ipairs(self.list) do
self:drawItem(item)
end
-- Add UI controls
self.mouse:registerZone(0, 0, self.w, self.h, function(button, x, y, xrel, yrel, bx, by, event)
if button == "wheelup" and event == "button" then self.scroll = util.bound(self.scroll - 1, 1, self.max - self.max_display + 1)
elseif button == "wheeldown" and event == "button" then self.scroll = util.bound(self.scroll + 1, 1, self.max - self.max_display + 1) end
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = util.bound(self.scroll + math.floor(by / self.fh), 1, self.max)
if (self.all_clicks or button == "left") and event == "button" then self:onUse(button) end
if event == "motion" and button == "left" and self.on_drag then self.on_drag(self.list[self.sel], self.sel) end
self:onSelect()
end)
self.key:addBinds{
ACCEPT = function() self:onUse() end,
MOVE_UP = function()
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = util.boundWrap(self.sel - 1, 1, self.max) self.scroll = util.scroll(self.sel, self.scroll, self.max_display)
self:onSelect()
end,
MOVE_DOWN = function()
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = util.boundWrap(self.sel + 1, 1, self.max) self.scroll = util.scroll(self.sel, self.scroll, self.max_display)
self:onSelect()
end,
}
self.key:addCommands{
[{"_UP","ctrl"}] = function() self.key:triggerVirtual("MOVE_UP") end,
[{"_DOWN","ctrl"}] = function() self.key:triggerVirtual("MOVE_DOWN") end,
_HOME = function()
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = 1
self.scroll = util.scroll(self.sel, self.scroll, self.max_display)
self:onSelect()
end,
_END = function()
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = self.max
self.scroll = util.scroll(self.sel, self.scroll, self.max_display)
self:onSelect()
end,
_PAGEUP = function()
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = util.bound(self.sel - self.max_display, 1, self.max)
self.scroll = util.scroll(self.sel, self.scroll, self.max_display)
self:onSelect()
end,
_PAGEDOWN = function()
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = util.bound(self.sel + self.max_display, 1, self.max)
self.scroll = util.scroll(self.sel, self.scroll, self.max_display)
self:onSelect()
end,
}
self:onSelect()
end
function _M:drawItem(item)
local s = self.surf
local color = item.color or {255,255,255}
local text = item[self.display_prop]
s:erase(0, 0, 0, 0)
s:drawColorStringBlended(self.font, text, 0, (self.fh - self.font_h) / 2, color[1], color[2], color[3], true, fw)
item._tex = {s:glTexture()}
end
function _M:select(i)
if self.sel and self.list[self.sel] then self.list[self.sel].focus_decay = self.focus_decay_max end
self.sel = util.bound(i, 1, #self.list)
self.scroll = util.scroll(self.sel, self.scroll, self.max_display)
self:onSelect()
end
function _M:onSelect()
local item = self.list[self.sel]
if not item then return end
if rawget(self, "on_select") then self.on_select(item, self.sel) end
end
function _M:onUse(...)
local item = self.list[self.sel]
if not item then return end
self:sound("button")
if item.fct then item:fct(item, self.sel, ...)
else self.fct(item, self.sel, ...) end
end
function _M:display(x, y, nb_keyframes)
local bx, by = x, y
local max = math.min(self.scroll + self.max_display - 1, self.max)
for i = self.scroll, max do
local item = self.list[i]
if not item then break end
if self.sel == i then
if self.focused then self:drawFrame(self.frame_sel, x, y)
else self:drawFrame(self.frame_usel, x, y) end
else
self:drawFrame(self.frame, x, y)
if item.focus_decay then
if self.focused then self:drawFrame(self.frame_sel, x, y, 1, 1, 1, item.focus_decay / self.focus_decay_max_d)
else self:drawFrame(self.frame_usel, x, y, 1, 1, 1, item.focus_decay / self.focus_decay_max_d) end
item.focus_decay = item.focus_decay - nb_keyframes
if item.focus_decay <= 0 then item.focus_decay = nil end
end
end
if self.text_shadow then item._tex[1]:toScreenFull(x+1 + self.frame_sel.b4.w, y+1, self.fw, self.fh, item._tex[2], item._tex[3], 0, 0, 0, self.text_shadow) end
item._tex[1]:toScreenFull(x + self.frame_sel.b4.w, y, self.fw, self.fh, item._tex[2], item._tex[3])
y = y + self.fh
end
if self.focused and self.scrollbar then
self.scrollbar.pos = self.sel
self.scrollbar:display(bx + self.w - self.scrollbar.w, by, by + self.fh)
end
end
| gpl-3.0 |
RyMarq/Zero-K | units/shipheavyarty.lua | 1 | 4080 | return { shipheavyarty = {
unitname = [[shipheavyarty]],
name = [[Shogun]],
description = [[Battleship (Heavy Artillery)]],
acceleration = 0.195,
activateWhenBuilt = true,
brakeRate = 0.475,
buildCostMetal = 5000,
builder = false,
buildPic = [[shipheavyarty.png]],
canGuard = true,
canMove = true,
canPatrol = true,
cantBeTransported = true,
category = [[SHIP]],
collisionVolumeOffsets = [[0 5 0]],
collisionVolumeScales = [[45 45 260]],
collisionVolumeType = [[cylZ]],
corpse = [[DEAD]],
customParams = {
modelradius = [[80]],
},
explodeAs = [[BIG_UNITEX]],
floater = true,
footprintX = 5,
footprintZ = 5,
highTrajectory = 2,
iconType = [[shipheavyarty]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 8000,
maxVelocity = 1.9,
minCloakDistance = 75,
minWaterDepth = 15,
movementClass = [[BOAT5]],
moveState = 0,
noAutoFire = false,
noChaseCategory = [[FIXEDWING SATELLITE GUNSHIP SUB]],
objectName = [[shipheavyarty.s3o]],
script = [[shipheavyarty.lua]],
selfDestructAs = [[BIG_UNITEX]],
sfxtypes = {
explosiongenerators = {
[[custom:xamelimpact]],
[[custom:ROACHPLOSION]],
[[custom:shellshockflash]],
},
},
sightDistance = 660,
sonarDistance = 660,
turninplace = 0,
turnRate = 216,
waterLine = 4,
workerTime = 0,
weapons = {
{
def = [[PLASMA]],
mainDir = [[0 0 1]],
maxAngleDif = 330,
badTargetCategory = [[GUNSHIP]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]],
},
{
def = [[PLASMA]],
mainDir = [[0 0 -1]],
maxAngleDif = 330,
badTargetCategory = [[GUNSHIP]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]],
},
{
def = [[PLASMA]],
mainDir = [[0 0 -1]],
maxAngleDif = 330,
badTargetCategory = [[GUNSHIP]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]],
},
},
weaponDefs = {
PLASMA = {
name = [[Long-Range Plasma Battery]],
areaOfEffect = 96,
avoidFeature = false,
avoidGround = false,
burst = 3,
burstrate = 0.2,
craterBoost = 1,
craterMult = 2,
damage = {
default = 501.1,
planes = 501.1,
subs = 25,
},
explosionGenerator = [[custom:PLASMA_HIT_96]],
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
projectiles = 1,
range = 1600,
reloadtime = 12.5,
soundHit = [[explosion/ex_large4]],
soundStart = [[explosion/ex_large5]],
sprayAngle = 768,
tolerance = 4096,
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 475,
},
},
featureDefs = {
DEAD = {
blocking = false,
featureDead = [[HEAP]],
footprintX = 6,
footprintZ = 6,
object = [[shipheavyarty_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 7,
footprintZ = 7,
object = [[debris4x4c.s3o]],
},
},
} }
| gpl-2.0 |
kellabyte/snabbswitch | src/lib/protocol/icmp/nd/na.lua | 7 | 1235 | module(..., package.seeall)
local ffi = require("ffi")
local C = ffi.C
local bitfield = require("core.lib").bitfield
local nd_header = require("lib.protocol.icmp.nd.header")
local na = subClass(nd_header)
local na_t = ffi.typeof[[
struct {
uint32_t flags;
uint8_t target[16];
} __attribute__((packed))
]]
-- Class variables
na._name = "neighbor advertisement"
na._header_type = na_t
na._header_ptr_type = ffi.typeof("$*", na_t)
na._ulp = { method = nil }
-- Class methods
function na:new (target, router, solicited, override)
local o = na:superClass().new(self)
o:target(target)
o:router(router)
o:solicited(solicited)
o:override(override)
return o
end
-- Instance methods
function na:target (target)
if target ~= nil then
ffi.copy(self:header().target, target, 16)
end
return self:header().target
end
function na:target_eq (target)
return C.memcmp(target, self:header().target, 16) == 0
end
function na:router (r)
return bitfield(32, self:header(), 'flags', 0, 1, r)
end
function na:solicited (s)
return bitfield(32, self:header(), 'flags', 1, 1, s)
end
function na:override (o)
return bitfield(32, self:header(), 'flags', 2, 1, o)
end
return na
| apache-2.0 |
adde88/Nerdpack-Zylla | rotations/rogue/assassination.lua | 1 | 10009 | local _, Zylla = ...
local unpack = _G.unpack
local NeP = _G.NeP
local Mythic_Plus = _G.Zylla.Mythic_Plus
local GUI = {
unpack(Zylla.Logo_GUI),
-- Header
{type = 'header', size = 16, text = 'Keybinds', align = 'center'},
{type = 'checkbox', text = 'Left Shift: '..Zylla.ClassColor..'Pause|r', align = 'left', key = 'lshift', default = true},
{type = 'checkbox', text = 'Left Ctrl: '..Zylla.ClassColor..'|r', align = 'left', key = 'lcontrol', default = true},
{type = 'checkbox', text = 'Left Alt: '..Zylla.ClassColor..'|r', align = 'left', key = 'lalt', default = true},
{type = 'checkbox', text = 'Right Alt: '..Zylla.ClassColor..'|r', align = 'left', key = 'ralt', default = true},
{type = 'spacer'},
{type = 'checkbox', text = 'Enable Chatoverlay', key = 'chat', width = 55, default = true, desc = Zylla.ClassColor..'This will enable some messages as an overlay!|r'},
unpack(Zylla.PayPal_GUI),
{type = 'spacer'},
unpack(Zylla.PayPal_IMG),
{type = 'spacer'}, {type = 'ruler'}, {type = 'spacer'},
--TODO: Targetting: Use, or NOT use?! We'll see....
{type = 'header', size = 16, text = 'Targetting:', align = 'center'},
{type = 'combo', default = 'target', key = 'target', list = Zylla.faketarget, width = 75},
{type = 'spacer'},
{type = 'text', text = Zylla.ClassColor..'Only one can be enabled.\nChose between normal targetting, or hitting the highest/lowest enemy.|r'},
{type = 'spacer'}, {type = 'ruler'}, {type = 'spacer'},
-- Settings
{type = 'header', size = 16, text = 'Class Settings', align = 'center'},
{type = 'spinner', size = 11, text = 'Interrupt at percentage:', key = 'intat', default = 60, step = 5, shiftStep = 10, max = 100, min = 1},
{type = 'checkbox', text = 'Enable DBM Integration', key = 'kDBM', default = true},
{type = 'checkbox', text = 'Enable \'pre-potting\', flasks and Legion-rune', key = 'prepot', default = false},
{type = 'combo', default = '1', key = 'list', list = Zylla.prepots, width = 175},
{type = 'spacer'}, {type = 'spacer'},
{type = 'checkspin',text = 'Light\'s Judgment - Units', key = 'LJ', spin = 4, step = 1, max = 20, min = 1, check = true, desc = Zylla.ClassColor..'World Spell usable on Argus.|r'},
{type='checkbox', text = 'AoE-Dotting', key='multi', default=true},
{type='ruler'}, {type='spacer'},
-- Survival
{type = 'header', size = 16, text = 'Survival', align = 'center'},
{type = 'checkspin',text = 'Crimson Vial', key='cv', spin = 65, step = 5, shiftStep = 10, max = 100, min = 1, check = true},
{type = 'checkspin',text = 'Evasion)', key='evasion', spin = 42, step = 5, shiftStep = 10, max = 100, min = 1, check = true},
{type = 'checkspin',text = 'Healthstone', key = 'HS', spin = 45, step = 5, shiftStep = 10, max = 100, min = 1, check = true},
{type = 'checkspin',text = 'Healing Potion', key = 'AHP', spin = 45, step = 5, shiftStep = 10, max = 100, min = 1, check = true},
{type='ruler'}, {type='spacer'},
--Cooldowns
{type = 'header', size = 16, text = 'Cooldowns', align = 'center'},
{type='checkbox', text = 'Vanish', key='van', default=true},
{type='checkbox', text = 'Vendetta', key='ven', default=true},
{type='ruler'}, {type='spacer'},
unpack(Zylla.Mythic_GUI),
}
local exeOnLoad=function()
Zylla.ExeOnLoad()
Zylla.AFKCheck()
print('|cffADFF2F ---------------------------------------------------------------------------|r')
print('|cffADFF2F --- |Rogue |cffADFF2FAssassination|r')
print('|cffADFF2F ---')
print('|cffADFF2F --- |rRecommended Talents: 1,1 / 2,1 / 3,3 / any / any / 6,1 or 6,2 / 7,1')
print('|cffADFF2F ----------------------------------------------------------------------|r')
print('|cffFFFB2F Configuration: |rRight-click MasterToggle and go to Combat Routines Settings!|r')
NeP.Interface:AddToggle({
key='xStealth',
name='Auto Stealth',
text = 'If Enabled we will automatically maintain Stealth out of combat.',
icon='Interface\\Icons\\ability_stealth',
})
NeP.Interface:AddToggle({
key='CS',
name='Cheap Shot',
text = 'If Enabled we will open with Cheap Shot.',
icon='Interface\\Icons\\ability_cheapshot',
})
NeP.Interface:AddToggle({
key='xPickPock',
name='Pick Pocket',
text = 'If Enabled we will automatically Pick Pocket enemies out of combat.',
icon='Interface\\Icons\\inv_misc_bag_11',
})
end
local PreCombat = {
{'Tricks of the Trade', '!buff&dbm(pull_in)<5', {'tank', 'focus'}},
-- Pots
{'#127844', 'UI(list)==1&item(127844).usable&item(127844).count>0&UI(kDBM)&UI(prepot)&!buff(Potion of the Old War)&dbm(pull in)<3'}, --XXX: Potion of the Old War
{'#127843', 'UI(list)==2&item(127843).usable&item(127843).count>0&UI(kDBM)&UI(prepot)&!buff(Potion of Deadly Grace)&dbm(pull in)<3'}, --XXX: Potion of Deadly Grace
{'#142117', 'UI(list)==3&item(142117).usable&item(142117).count>0&UI(kDBM)&UI(prepot)&!buff(Potion of Prolonged Power)&dbm(pull in)<3'}, --XXX: Potion of Prolonged Power
-- Flasks
{'#127848', 'ingroup&item(127848).usable&item(127848).count>0&UI(prepot)&!buff(Flask of the Seventh Demon)'}, --XXX: Flask of the Seventh Demon
{'#153023', 'ingroup&item(153023).usable&item(153023).count>0&UI(prepot)&!buff(Defiled Augmentation)'} --XXX: Lightforged Augment Rune
}
local Keybinds = {
{'%pause', 'keybind(lshift)&UI(lshift)'},
}
local Interrupts = {
{'&Kick', 'inMelee&inFront'},
{'!Kidney Shot', 'inMelee&&inFront&cooldown(Kick).remains>gcd&!player.lastgcd(Kick)&player.combopoints>0'},
{'!Arcane Torrent', 'inMelee&spell(Kick).cooldown>gcd&!player.lastgcd(Kick)'},
}
local Survival = {
--{'Feint', ''},
{'Crimson Vial', 'UI(cv_check)&health<=UI(cv_spin)&energy>25'},
{'Evasion', 'UI(evasion_check)&health<=UI(evasion_spin)'},
{'#152615', 'item(152615).usable&item(152615).count>0&health<=UI(AHP_spin)&UI(AHP_check)'}, --XXX: Astral Healing Potion
{'#127834', 'item(152615).count==0&item(127834).usable&item(127834).count>0&health<=UI(AHP_spin)&UI(AHP_check)'}, --XXX: Ancient Healing Potion
{'#5512', 'item(5512).usable&item(5512).count>0&health<=UI(HS_spin)&UI(HS_check)'}, --XXX: Health Stone
{'Cloak of Shadows', 'incdmg(3).magic>health.max*0.25'},
}
local Cooldowns= {
{'Vendetta', 'player.energy<60'},
{'Vanish', '!player.buff(Stealth)&player.combopoints>3&UI(van)'},
{'#trinket1', 'UI(trinket1)'},
{'#trinket2', 'UI(trinket2)'},
{'Light\'s Judgment', 'advanced&UI(LJ_check)&range<61&area(15).enemies>=UI(LJ_spin)', 'enemies.ground'},
{'𣎃', 'UI(kj_check)&range<=40&area(10).enemies>=UI(kj_spin)&equipped(144259)'}, --XXX: Kil'jaeden's Burning Wish (Legendary)
}
local Ranged = {
{'Poisoned Knife', 'player.energy>60&player.combopoints<5'},
{'Poisoned Knife', 'debuff(Agonizing Poison).duration<3'},
}
local Stealthed = {
{'Rupture', 'player.lastcast(Vanish)&player.combopoints>4&enemy'},
{'Garrote', 'player.buff(Stealth)&player.combopoints<5&debuff.duration<6.4&enemy'},
{'Cheap Shot', '!toggle(xPickPock)&toggle(CS)&inMelee&enemy&player.buff(Stealth)&enemy'},
{'Stealth', 'toggle(xStealth)&!player.buff&!player.buff(Vanish)&!nfly&!combat', 'player'},
{'Pick Pocket', 'toggle(xPickPock)&enemy&alive&range<=10&player.buff(Stealth)' ,'enemies'},
}
local Poisons = {
{'Deadly Poison', 'buff.duration<70&!player.lastcast&!talent(6,1)'},
{'Agonizing Poison', 'buff.duration<70&!player.lastcast&talent(6,1)'},
{'Leeching Poison', 'buff.duration<70&!player.lastcast&talent(4,1)'},
{'Crippling Poison', 'buff.duration<70&!player.lastcast&!talent(4,1)'},
}
local xCombat = {
{Interrupts, '@Zylla.InterruptAt(intat)&toggle(interrupts)'},
{Interrupts, '@Zylla.InterruptAt(intat)&toggle(interrupts)&toggle(xIntRandom)', 'enemies'},
{Ranged, '!inMelee&inRanged'},
{Cooldowns, 'toggle(cooldowns)'},
--XXX: Rupture
{'Rupture', 'player.buff(Vanish)'},
{'Rupture', 'debuff.duration<8.2&player.combopoints>3&spell(Vanish).cooldown>gcd&ttd>5'},
--XXX: Multi DoT Rupture
{'Rupture', 'debuff.duration<8.2&player.combopoints>3'},
{'Rupture', 'inMelee&combat&alive&enemy&debuff.duration<8.2&player.combopoints>3&enemy&UI(multi)', 'enemies'},
{'Garrote', 'inMelee&debuff.duration<6.4&player.combopoints<5'},
--XXX: Use Mutilate till 4/5 combopoints for rupture
{'Mutilate', '!debuff(Rupture)&player.combopoints<4'},
{'Kingsbane', '!talent(6,3)&player.buff(Envenom)&debuff(Vendetta)&debuff(Surge of Toxins)&ttd>10'},
{'Kingsbane', '!talent(6,3)&player.buff(Envenom)&spell(Vendetta).cooldown<6.8&ttd>10'},
{'Envenom', 'player.combopoints>2&debuff(Surge of Toxins).duration<=0.5&debuff(Vendetta)'},
{'Envenom', 'player.combopoints>3&debuff(Vendetta)'},
{'Envenom', 'player.combopoints>3&debuff(Surge of Toxins).duration<=0.5'},
{'Envenom', 'player.combopoints>3&player.energy>60'},
{'Fan of Knives', 'player.area(10).enemies>2&player.combopoints<5'},
{'Mutilate', 'player.combopoints<4&player.buff(Envenom)'},
{'Mutilate', 'spell(Vendetta).cooldown<6&player.combopoints<4'},
{'Mutilate', 'player.combopoints<4'},
}
local inCombat = {
{'Tricks of the Trade', '!buff&ingroup', {'tank', 'focus'}},
{Keybinds},
{Stealthed},
{Survival, nil, 'player'},
{Mythic_Plus, 'inMelee'},
{xCombat, 'combat&alive&inMelee&inFront', (function() return NeP.DSL:Get("UI")(nil, 'target') end)}, --TODO: TEST! ALOT MORE TESTING!
}
local outCombat= {
{PreCombat, nil, 'player'},
{Stealthed, nil, 'target'},
{Keybinds},
{Poisons, nil, 'player'},
}
NeP.CR:Add(259, {
name='[|cff'..Zylla.addonColor..'Zylla\'s|r] Rogue - Assassination',
ic = inCombat,
ooc = outCombat,
gui = GUI,
gui_st = Zylla.GuiSettings,
ids = Zylla.SpellIDs[Zylla.Class],
wow_ver = Zylla.wow_ver,
nep_ver = Zylla.nep_ver,
load = exeOnLoad
})
| mit |
rigeirani/sss | plugins/steam.lua | 645 | 2117 | -- See https://wiki.teamfortress.com/wiki/User:RJackson/StorefrontAPI
do
local BASE_URL = 'http://store.steampowered.com/api/appdetails/'
local DESC_LENTH = 200
local function unescape(str)
str = string.gsub( str, '<', '<' )
str = string.gsub( str, '>', '>' )
str = string.gsub( str, '"', '"' )
str = string.gsub( str, ''', "'" )
str = string.gsub( str, '&#(%d+);', function(n) return string.char(n) end )
str = string.gsub( str, '&#x(%d+);', function(n) return string.char(tonumber(n,16)) end )
str = string.gsub( str, '&', '&' ) -- Be sure to do this after all others
return str
end
local function get_steam_data (appid)
local url = BASE_URL
url = url..'?appids='..appid
url = url..'&cc=us'
local res,code = http.request(url)
if code ~= 200 then return nil end
local data = json:decode(res)[appid].data
return data
end
local function price_info (data)
local price = '' -- If no data is empty
if data then
local initial = data.initial
local final = data.final or data.initial
local min = math.min(data.initial, data.final)
price = tostring(min/100)
if data.discount_percent and initial ~= final then
price = price..data.currency..' ('..data.discount_percent..'% OFF)'
end
price = price..' (US)'
end
return price
end
local function send_steam_data(data, receiver)
local description = string.sub(unescape(data.about_the_game:gsub("%b<>", "")), 1, DESC_LENTH) .. '...'
local title = data.name
local price = price_info(data.price_overview)
local text = title..' '..price..'\n'..description
local image_url = data.header_image
local cb_extra = {
receiver = receiver,
url = image_url
}
send_msg(receiver, text, send_photo_from_url_callback, cb_extra)
end
local function run(msg, matches)
local appid = matches[1]
local data = get_steam_data(appid)
local receiver = get_receiver(msg)
send_steam_data(data, receiver)
end
return {
description = "Grabs Steam info for Steam links.",
usage = "",
patterns = {
"http://store.steampowered.com/app/([0-9]+)",
},
run = run
}
end
| gpl-2.0 |
knixeur/notion | contrib/styles/look_cleanwhite.lua | 7 | 1963 | -- Authors: René van Bevern <rvb@debian.org>
-- License: Unknown
-- Last Changed: Unknown
--
-- look_cleanwhite.lua a bright theme fitting white terminals
--
-- uses Terminus fonts
--
-- -- René van Bevern <rvb@debian.org>
if not gr.select_engine("de") then return end
de.reset()
de.defstyle("*", {
shadow_colour = "grey70",
highlight_colour = "grey70",
background_colour = "grey90",
foreground_colour = "black",
padding_pixels = 1,
highlight_pixels = 1,
shadow_pixels = 1,
spacing = 1,
border_style = "elevated",
font = "-xos4-terminus-medium-r-normal-*-12-*-72-72-*-60-iso10646-1",
text_align = "center",
})
de.defstyle("frame", {
based_on = "*",
de.substyle("active", {
padding_colour = "black",
}),
padding_colour = "grey70",
background_colour = "white",
shadow_colour = "white",
highlight_colour = "white",
transparent_background = false,
})
de.defstyle("tab", {
based_on = "*",
highlight_pixels = 1,
shadow_pixels = 1,
padding_pixels = 0,
highlight_colour = "grey70",
shadow_colour = "grey70",
de.substyle("active-selected", {
shadow_colour = "black",
highlight_colour = "black",
background_colour = "darkslategray",
foreground_colour = "white",
}),
de.substyle("inactive-unselected", {
background_colour = "#d8d8d8",
foreground_colour = "#606060",
}),
text_align = "center",
})
de.defstyle("tab-menuentry", {
based_on = "tab",
text_align = "left",
spacing = 1,
})
de.defstyle("tab-menuentry-big", {
based_on = "tab-menuentry",
padding_pixels = 10,
})
de.defstyle("input-edln", {
based_on = "*",
de.substyle("*-cursor", {
background_colour = "#000000",
foreground_colour = "#d8d8d8",
}),
de.substyle("*-selection", {
background_colour = "#f0c000",
foreground_colour = "#000000",
}),
})
gr.refresh()
| lgpl-2.1 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Tasks/BlockFileMonitorTask.lua | 1 | 7246 | --[[
Title: For files from blue tooth.
Author(s): LiXizhi
Date: 2013/1/26
Desc: Drag and drop *.block.xml block template file to game to create blocks where it is.
when the file changes, the block is automatically updated.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Tasks/BlockFileMonitorTask.lua");
local task = MyCompany.Aries.Game.Tasks.BlockFileMonitor:new({filename="worlds/DesignHouse/blockdisk/box.blocks.xml", cx=nil, cy=nil, cz = nil })
task:Run();
-------------------------------------------------------
]]
NPL.load("(gl)script/apps/Aries/Creator/Assets/AssetsCommon.lua");
local EntityManager = commonlib.gettable("MyCompany.Aries.Game.EntityManager");
local BlockEngine = commonlib.gettable("MyCompany.Aries.Game.BlockEngine")
local TaskManager = commonlib.gettable("MyCompany.Aries.Game.TaskManager")
local block_types = commonlib.gettable("MyCompany.Aries.Game.block_types")
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local BlockFileMonitor = commonlib.inherit(commonlib.gettable("MyCompany.Aries.Game.Task"), commonlib.gettable("MyCompany.Aries.Game.Tasks.BlockFileMonitor"));
-- this is always a top level task.
BlockFileMonitor.is_top_level = true;
local cur_instance;
function BlockFileMonitor:ctor()
end
function BlockFileMonitor.RegisterHooks()
local self = cur_instance;
self:LoadSceneContext();
end
function BlockFileMonitor.UnregisterHooks()
local self = cur_instance;
if(self) then
self:UnloadSceneContext();
end
end
function BlockFileMonitor:Run()
if(not TaskManager.AddTask(self)) then
-- ignore the task if there is other top-level tasks.
return;
end
cur_instance = self;
if(not self.filename or not ParaIO.DoesFileExist(self.filename)) then
return
end
local bx, by, bz = EntityManager.GetPlayer():GetBlockPos();
self.cx = self.cx or bx;
self.cy = self.cy or by;
self.cz = self.cz or bz;
BlockFileMonitor.mytimer = commonlib.Timer:new({callbackFunc = function(timer)
BlockFileMonitor.OnUpdateBlocks();
end})
BlockFileMonitor.mytimer:Change(0, 200);
BlockFileMonitor.finished = false;
BlockFileMonitor.RegisterHooks();
BlockFileMonitor.ShowPage();
end
function BlockFileMonitor:OnExit()
BlockFileMonitor.EndEditing();
end
-- @param bCommitChange: true to commit all changes made
function BlockFileMonitor.EndEditing(bCommitChange)
BlockFileMonitor.finished = true;
BlockFileMonitor.ClosePage()
BlockFileMonitor.UnregisterHooks();
if(cur_instance) then
local self = cur_instance;
cur_instance = nil
end
if(BlockFileMonitor.mytimer) then
BlockFileMonitor.mytimer:Change();
BlockFileMonitor.mytimer = nil;
end
end
function BlockFileMonitor:mousePressEvent(event)
end
function BlockFileMonitor:mouseMoveEvent(event)
end
function BlockFileMonitor:mouseReleaseEvent(event)
end
function BlockFileMonitor:keyPressEvent(event)
local dik_key = event.keyname;
if(dik_key == "DIK_ESCAPE")then
-- exit editing mode without commit any changes.
BlockFileMonitor.EndEditing(false);
elseif(dik_key == "DIK_DELETE" or dik_key == "DIK_DECIMAL")then
BlockFileMonitor.DeleteAll()
end
end
function BlockFileMonitor:FrameMove()
end
------------------------
-- page function
------------------------
local page;
function BlockFileMonitor.ShowPage()
System.App.Commands.Call("File.MCMLWindowFrame", {
url = "script/apps/Aries/Creator/Game/Tasks/BlockFileMonitorTask.html",
name = "BlockFileMonitorTask.ShowPage",
app_key = MyCompany.Aries.Creator.Game.Desktop.App.app_key,
isShowTitleBar = false,
DestroyOnClose = true, -- prevent many ViewProfile pages staying in memory
style = CommonCtrl.WindowFrame.ContainerStyle,
zorder = 1,
allowDrag = false,
click_through = true,
directPosition = true,
align = "_lt",
x = 0,
y = 80,
width = 128,
height = 512,
});
MyCompany.Aries.Creator.ToolTipsPage.ShowPage(false);
end
function BlockFileMonitor.ClosePage()
if(page) then
page:CloseWindow();
end
end
function BlockFileMonitor.OnInit()
page = document:GetPageCtrl();
end
function BlockFileMonitor.RefreshPage()
if(page) then
page:Refresh(0.01);
end
end
function BlockFileMonitor.DoClick(name)
local self = cur_instance;
if(not self) then
return
end
if(name == "camera_up") then
self.dy = 1;
BlockFileMonitor.OnUpdateBlocks()
elseif(name == "camera_down") then
self.dy = -1;
BlockFileMonitor.OnUpdateBlocks()
elseif(name == "delete") then
BlockFileMonitor.DeleteAll()
elseif(name == "save_template") then
if(self.blocks) then
NPL.load("(gl)script/apps/Aries/Creator/Game/Areas/BlockTemplatePage.lua");
local BlockTemplatePage = commonlib.gettable("MyCompany.Aries.Creator.Game.Desktop.BlockTemplatePage");
BlockTemplatePage.ShowPage(true, self.blocks);
end
end
end
function BlockFileMonitor.DeleteAll()
local self = cur_instance;
if(not self) then
return
end
self.filename = nil;
local cx, cy, cz = self.cx, self.cy, self.cz;
local blocks = self.blocks or {};
local _, b;
for _, b in ipairs(blocks) do
if(b[1]) then
local x, y, z = cx+b[1], cy+b[2], cz+b[3];
BlockEngine:SetBlock(x,y,z, 0);
end
end
BlockFileMonitor.EndEditing();
end
function BlockFileMonitor.OnUpdateBlocks()
local self = cur_instance;
if(not self) then
return
end
--[[ TODO: detect file change
local sInitDir = self.filename:gsub("([^/\\]+)$", "");
sInitDir = sInitDir:gsub("\\", "/");
local filename = self.filename:match("([^/\\]+)$");
if(not filename) then
return;
end
local search_result = ParaIO.SearchFiles(sInitDir,filename, "", 0, 1, 0);
local nCount = search_result:GetNumOfResult();
local i;
if(nCount>=1) then
local item = search_result:GetItemData(0, {});
local date = item.writedate;
end
]]
local xmlRoot = ParaXML.LuaXML_ParseFile(self.filename);
if(xmlRoot) then
local node = commonlib.XPath.selectNode(xmlRoot, "/pe:blocktemplate/pe:blocks");
if(node and node[1]) then
local blocks = NPL.LoadTableFromString(node[1]);
if(blocks and #blocks > 0) then
self.cy = self.cy + (self.dy or 0);
local cx, cy, cz = self.cx, self.cy, self.cz;
local last_blocks = self.blocks or {};
blocks.map = {};
last_blocks.map = last_blocks.map or {};
local _, b
for _, b in ipairs(blocks) do
if(b[1]) then
local x, y, z = cx+b[1], cy+b[2], cz+b[3];
local sparse_index =x*30000*30000+y*30000+z;
local new_id = b[4] or 96;
blocks.map[sparse_index] = new_id;
if(last_blocks.map[sparse_index] ~= new_id) then
BlockEngine:SetBlock(x,y,z, new_id, b[5], nil, b[6]);
end
end
end
if(self.dy) then
cy = cy - self.dy;
self.dy = nil;
end
for _, b in ipairs(last_blocks) do
if(b[1]) then
local x, y, z = cx+b[1], cy+b[2], cz+b[3];
local sparse_index =x*30000*30000+y*30000+z;
if(not blocks.map[sparse_index]) then
BlockEngine:SetBlock(x,y,z, 0);
end
end
end
self.blocks = blocks;
if(#blocks~=self.block_count) then
self.block_count = #blocks;
if(page) then
page:SetValue("blockcount", self.block_count);
end
end
end
end
end
end
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/general/objects/wizard-hat.lua | 3 | 1883 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
newEntity{
define_as = "BASE_WIZARD_HAT",
slot = "HEAD",
type = "armor", subtype="head",
add_name = " (#ARMOR#)",
display = "]", color=colors.BLUE, image = resolvers.image_material("wizardhat", "cloth"),
moddable_tile = resolvers.moddable_tile("wizard_hat"),
encumber = 2,
rarity = 6,
desc = [[A pointy cloth hat, very wizardly...]],
randart_able = "/data/general/objects/random-artifacts/generic.lua",
egos = "/data/general/objects/egos/wizard-hat.lua", egos_chance = { prefix=resolvers.mbonus(40, 5), suffix=resolvers.mbonus(40, 5) },
}
newEntity{ base = "BASE_WIZARD_HAT",
name = "linen wizard hat", short_name = "linen",
level_range = {1, 20},
cost = 2,
material_level = 1,
wielder = {
combat_def = 1,
},
}
newEntity{ base = "BASE_WIZARD_HAT",
name = "cashmere wizard hat", short_name = "cashmere",
level_range = {20, 40},
cost = 4,
material_level = 3,
wielder = {
combat_def = 2,
},
}
newEntity{ base = "BASE_WIZARD_HAT",
name = "elven-silk wizard hat", short_name = "e.silk",
level_range = {40, 50},
cost = 7,
material_level = 5,
wielder = {
combat_def = 3,
},
}
| gpl-3.0 |
TerminalShell/zombiesurvival | entities/weapons/weapon_zs_handyman.lua | 1 | 2815 | -- Read the weapon_real_base if you really want to know what each action does
if (CLIENT) then
SWEP.PrintName = "'Handyman' Handgun"
SWEP.Description = "A very cheap weapon designed for caders as a sidearm."
SWEP.ViewModelFOV = 70
SWEP.Slot = 1
SWEP.SlotPos = 1
SWEP.HUD3DBone = "slide"
SWEP.HUD3DPos = Vector(3.5, 0, -0.800)
SWEP.HUD3DAng = Angle(100, 0, 180)
killicon.AddFont("weapon_real_cs_sg550", "CSKillIcons", SWEP.IconLetter, Color( 255, 80, 0, 255 ))
end
/*---------------------------------------------------------
Muzzle Effect + Shell Effect
---------------------------------------------------------*/
SWEP.MuzzleEffect = "rg_muzzle_pistol" -- This is an extra muzzleflash effect
-- Available muzzle effects: rg_muzzle_grenade, rg_muzzle_highcal, rg_muzzle_hmg, rg_muzzle_pistol, rg_muzzle_rifle, rg_muzzle_silenced, none
SWEP.ShellEffect = "rg_shelleject" -- This is a shell ejection effect
-- Available shell eject effects: rg_shelleject, rg_shelleject_rifle, rg_shelleject_shotgun, none
SWEP.MuzzleAttachment = "1" -- Should be "1" for CSS models or "muzzle" for hl2 models
SWEP.ShellEjectAttachment = "2" -- Should be "2" for CSS models or "1" for hl2 models
/*-------------------------------------------------------*/
SWEP.Base = "weapon_zs_base"
SWEP.ViewModel = "models/weapons/v_makarov/v_pist_maka.mdl"
SWEP.WorldModel = "models/weapons/w_pist_maka.mdl"
SWEP.Category = "Handgun"
SWEP.Primary.Sound = Sound("weapons/handy/mak.wav")
SWEP.Primary.Damage = 16
SWEP.Primary.Recoil = 0.75
SWEP.Primary.NumShots = 1
SWEP.ConeMax = 0.07
SWEP.ConeMin = 0.02
SWEP.Primary.ClipSize = 8
SWEP.Primary.Delay = 0.14
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "pistol"
GAMEMODE:SetupDefaultClip(SWEP.Primary)
SWEP.data = {}
SWEP.Primary.Automatic = false
SWEP.data.semi = {}
SWEP.data.auto = {}
SWEP.IronSightsPos = Vector(2.599, 0, 1.44)
SWEP.IronSightsAng = Vector(0, 0, 0)
SWEP.WalkSpeed = 200
function SWEP:Reload()
self.Weapon:DefaultReload(ACT_VM_RELOAD)
-- Animation when you're reloading
if ( self.Weapon:Clip1() < self.Primary.ClipSize ) and self.Owner:GetAmmoCount(self.Primary.Ammo) > 0 then
-- When the current clip < full clip and the rest of your ammo > 0, then
self.Owner:SetFOV( 0, 0.15 )
-- Zoom = 0
self:SetIronsights(false)
-- Set the ironsight to false
end
end
function SWEP:Deploy()
self.Weapon:SendWeaponAnim( ACT_VM_DRAW )
self.Reloadaftershoot = CurTime() + 1
self.Weapon:SetNextPrimaryFire(CurTime() + 1)
self:SetDeploySpeed(1)
return true
end
function SWEP:PlayAttackSound()
self.Owner:EmitSound("weapons/handy/mak.wav")
end
function SWEP:Precache()
util.PrecacheSound("weapons/handy/mak.wav")
end
function SWEP:EmitFireSound()
self:EmitSound("weapons/handy/mak.wav")
end | gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/leremieu_taco.lua | 1 | 1802 | -----------------------------------------
-- ID: 5175
-- Item: leremieu_taco
-- Food Effect: 60Min, All Races
-----------------------------------------
-- Health 20
-- Magic 20
-- Dexterity 4
-- Agility 4
-- Vitality 6
-- Charisma 4
-- Health Regen While Healing 1
-- Magic Regen While Healing 1
-- Defense % 25
-- Defense Cap 160
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,3600,0,5175);
end;
-----------------------------------
-- onEffectGain Action
-----------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_HP, 20);
target:addMod(MOD_MP, 20);
target:addMod(MOD_DEX, 4);
target:addMod(MOD_AGI, 4);
target:addMod(MOD_VIT, 6);
target:addMod(MOD_CHR, 4);
target:addMod(MOD_HPHEAL, 1);
target:addMod(MOD_MPHEAL, 1);
target:addMod(MOD_FOOD_DEFP, 25);
target:addMod(MOD_FOOD_DEF_CAP, 160);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_HP, 20);
target:delMod(MOD_MP, 20);
target:delMod(MOD_DEX, 4);
target:delMod(MOD_AGI, 4);
target:delMod(MOD_VIT, 6);
target:delMod(MOD_CHR, 4);
target:delMod(MOD_HPHEAL, 1);
target:delMod(MOD_MPHEAL, 1);
target:delMod(MOD_FOOD_DEFP, 25);
target:delMod(MOD_FOOD_DEF_CAP, 160);
end;
| gpl-3.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/applications/luci-freifunk-policyrouting/luasrc/model/cbi/freifunk/policyrouting.lua | 76 | 1905 | --[[
LuCI - Lua Configuration Interface
Copyright 2011 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 uci = require "luci.model.uci".cursor()
m = Map("freifunk-policyrouting", translate("Policy Routing"), translate("These pages can be used to setup policy routing for certain firewall zones. "..
"This is useful if you need to use your own internet connection for yourself but you don't want to share it with others (thats why it can also be "..
"called 'Ego Mode'). Your own traffic is then sent via your internet connection while traffic originating from the mesh will use another gateway in the mesh. "))
m:chain("network")
c = m:section(NamedSection, "pr", "settings", "")
local pr = c:option(Flag, "enable", translate("Enable Policy Routing"))
pr.rmempty = false
local strict = c:option(Flag, "strict", translate("Strict Filtering"), translate("If no default route is received from the mesh network then traffic which belongs to "..
"the selected firewall zones is routed via your internet connection as a fallback. If you do not want this and instead block that traffic then you should "..
"select this option."))
strict.rmempty = false
local fallback = c:option(Flag, "fallback", translate("Fallback to mesh"),
translate("If your own gateway is not available then fallback to the mesh default gateway."))
strict.rmempty = false
local zones = c:option(MultiValue, "zones", translate("Firewall zones"), translate("All traffic from interfaces belonging to these zones will be sent via "..
"a gateway in the mesh network."))
uci:foreach("firewall", "zone", function(section)
local name = section.name
if not (name == "wan") then
zones:value(name)
end
end)
return m
| gpl-2.0 |
CerNerCompany/Anti-Spam | libs/XMLElement.lua | 569 | 4025 | -- Copyright 2009 Leo Ponomarev. Distributed under the BSD Licence.
-- updated for module-free world of lua 5.3 on April 2 2015
-- Not documented at all, but not interesting enough to warrant documentation anyway.
local setmetatable, pairs, ipairs, type, getmetatable, tostring, error = setmetatable, pairs, ipairs, type, getmetatable, tostring, error
local table, string = table, string
local XMLElement={}
local mt
XMLElement.new = function(lom)
return setmetatable({lom=lom or {}}, mt)
end
local function filter(filtery_thing, lom)
filtery_thing=filtery_thing or '*'
for i, thing in ipairs(type(filtery_thing)=='table' and filtery_thing or {filtery_thing}) do
if thing == "text()" then
if type(lom)=='string' then return true end
elseif thing == '*' then
if type(lom)=='table' then return true end
else
if type(lom)=='table' and string.lower(lom.tag)==string.lower(thing) then return true end
end
end
return nil
end
mt ={ __index = {
getAttr = function(self, attribute)
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
return self.lom.attr[attribute]
end,
setAttr = function(self, attribute, value)
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
if value == nil then return self:removeAttr(attribute) end
self.lom.attr[attribute]=tostring(value)
return self
end,
removeAttr = function(self, attribute)
local lom = self.lom
if type(attribute) ~= "string" then return nil, "attribute name must be a string." end
if not lom.attr[attribute] then return self end
for i,v in ipairs(lom.attr) do
if v == attribute then
table.remove(lom.attr, i)
break
end
end
lom.attr[attribute]=nil
end,
removeAllAttributes = function(self)
local attr = self.lom.attr
for i, v in pairs(self.lom.attr) do
attr[i]=nil
end
return self
end,
getAttributes = function(self)
local attr = {}
for i, v in ipairs(self.lom.attr) do
table.insert(attr,v)
end
return attr
end,
getXML = function(self)
local function getXML(lom)
local attr, inner = {}, {}
for i, attribute in ipairs(lom.attr) do
table.insert(attr, string.format('%s=%q', attribute, lom.attr[attribute]))
end
for i, v in ipairs(lom) do
local t = type(v)
if t == "string" then table.insert(inner, v)
elseif t == "table" then
table.insert(inner, getXML(v))
else
error("oh shit")
end
end
local tagcontents = table.concat(inner)
local attrstring = #attr>0 and (" " .. table.concat(attr, " ")) or ""
if #tagcontents>0 then
return string.format("<%s%s>%s</%s>", lom.tag, attrstring, tagcontents, lom.tag)
else
return string.format("<%s%s />", lom.tag, attrstring)
end
end
return getXML(self.lom)
end,
getText = function(self)
local function getText(lom)
local inner = {}
for i, v in ipairs(lom) do
local t = type(v)
if t == "string" then table.insert(inner, v)
elseif t == "table" then
table.insert(inner, getText(v))
end
end
return table.concat(inner)
end
return getText(self.lom)
end,
getChildren = function(self, filter_thing)
local res = {}
for i, node in ipairs(self.lom) do
if filter(filter_thing, node) then
table.insert(res, type(node)=='table' and XMLElement.new(node) or node)
end
end
return res
end,
getDescendants = function(self, filter_thing)
local res = {}
local function descendants(lom)
for i, child in ipairs(lom) do
if filter(filter_thing, child) then
table.insert(res, type(child)=='table' and XMLElement.new(child) or child)
if type(child)=='table' then descendants(child) end
end
end
end
descendants(self.lom)
return res
end,
getChild = function(self, filter_thing)
for i, node in ipairs(self.lom) do
if filter(filter_thing, node) then
return type(node)=='table' and XMLElement.new(node) or node
end
end
end,
getTag = function(self)
return self.lom.tag
end
}}
return XMLElement | lgpl-2.1 |
sirnuke/soup-kitchen-the-game | soup-kitchen/state/map.lua | 1 | 5339 | -- Soup Kitchen
-- Bryan DeGrendel (c) 2014
MapClass = {}
function MapClass.new()
local structure = {
{ 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'T', 'X' },
{ ' ', ' ', ' ', ' ', 'X', 'C', 'C', 'C', ' ', ' ', ' ', 'X' },
{ ' ', ' ', ' ', ' ', 'C', ' ', ' ', ' ', ' ', ' ', ' ', 'X' },
{ ' ', ' ', ' ', ' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ', 'X' },
{ ' ', ' ', ' ', ' ', 'F', ' ', ' ', 'P', ' ', ' ', 'S', 'S' },
{ ' ', ' ', ' ', ' ', 'F', ' ', ' ', 'P', ' ', ' ', 'S', 'S' },
{ ' ', ' ', ' ', ' ', 'F', ' ', ' ', 'P', ' ', ' ', 'S', 'S' },
{ ' ', ' ', ' ', ' ', 'F', ' ', ' ', 'P', ' ', ' ', 'S', 'S' },
{ ' ', ' ', ' ', ' ', 'X', ' ', ' ', ' ', ' ', ' ', ' ', 'X' },
{ ' ', ' ', 'T', 'D', 'X', ' ', ' ', ' ', ' ', ' ', ' ', 'X' },
{ ' ', ' ', ' ', ' ', ' ', ' ', ' ', ' ', 'C', 'C', 'C', 'X' },
{ 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X', 'X' }
}
local instance = {}
setmetatable(instance, MapClass)
instance.pawns = {}
instance.data = {}
for y,row in ipairs(structure) do
local data = {}
for x,v in ipairs(row) do
if v == ' ' then
table.insert(data, {coord=Coordinate.new(x, y), blocked=false, occupant=nil, equipment=nil})
else
table.insert(data, {coord=Coordinate.new(x, y), blocked=true, occupant=nil, equipment=nil})
end
end
table.insert(instance.data, data)
end
instance.equipment = {}
local equipment = {}
equipment.serving = {}
equipment.serving.drinks = {Coordinate.new(3,10), Coordinate.new(3,11)}
equipment.serving.salad = {Coordinate.new(4,9), Coordinate.new(5,9)}
equipment.serving.desert = {Coordinate.new(4,8), Coordinate.new(5,8)}
equipment.serving.side = {Coordinate.new(4,6), Coordinate.new(5,6)}
equipment.serving.dinner = {Coordinate.new(4,5), Coordinate.new(5,5)}
equipment.dispensing = {}
equipment.dispensing.trays = {Coordinate.new(2,10), Coordinate.new(2,9)}
equipment.dispensing.drinks = {Coordinate.new(3,10), Coordinate.new(3,9)}
equipment.dispensing.salad = {Coordinate.new(4,8), Coordinate.new(3,8)}
equipment.dispensing.desert = {Coordinate.new(4,7), Coordinate.new(3,7)}
equipment.dispensing.side = {Coordinate.new(4,6), Coordinate.new(3,6)}
equipment.dispensing.dinner = {Coordinate.new(4,5), Coordinate.new(3,5)}
for k,v in pairs(equipment) do
local class = nil
instance.equipment[k] = {}
if k == 'serving' then class = ServingClass
elseif k == 'dispensing' then class = DispensingClass
else assert(false, string.format("Unhandled equipment type of %s", k))
end
for id,data in pairs(v) do
instance.equipment[k][id] = class.new(id, data[1], data[2])
end
end
--self.equipment.cleaning = {}
--self.equipment.cleaning[1] = EquipmentClass.new(Coordinate.new(4,3), Coordinate.new(5,3))
--self.equipment.cleaning[2] = EquipmentClass.new(Coordinate.new(6,2), Coordinate.new(6,3))
--self.equipment.cleaning[3] = EquipmentClass.new(Coordinate.new(8,2), Coordinate.new(8,3))
--self.equipment.return = {}
--self.equipment.cook = {}
--self.equipment.cook[1] = EquipmentClass.new(Coordinate.new(8,4), Coordinate.new(9,4))
--self.equipment.cook[2] = EquipmentClass.new(Coordinate.new(8,5), Coordinate.new(9,5))
--self.equipment.cook[3] = EquipmentClass.new(Coordinate.new(8,6), Coordinate.new(9,6))
--self.equipment.cook[4] = EquipmentClass.new(Coordinate.new(8,7), Coordinate.new(9,7))
--self.equipment.cook[5] = EquipmentClass.new(Coordinate.new(8,8), Coordinate.new(9,8))
--self.equipment.staging = {}
--self.equipment.storage = {}
--self.equipment.storage[1] = EquipmentClass.new(Coordinate.new(11,4), Coordinate.new(10,4))
--self.equipment.storage[2] = EquipmentClass.new(Coordinate.new(11,5), Coordinate.new(10,5))
--self.equipment.storage[3] = EquipmentClass.new(Coordinate.new(11,6), Coordinate.new(10,6))
--self.equipment.storage[3] = EquipmentClass.new(Coordinate.new(11,7), Coordinate.new(10,7))
--self.equipment.storage[3] = EquipmentClass.new(Coordinate.new(11,8), Coordinate.new(10,8))
--self.equipment.trash = {}
--self.equipment.trash[1] = EquipmentClass.new(Coordinate.new(11,1), Coordinate.new(11,2))
end
function MapClass:add_pawn(pawn)
table.insert(self.pawns, pawn)
end
function MapClass:remove_pawn(pawn)
for k,v in pairs(self.pawns) do
if v == pawn then
table.remove(self.pawns, k)
return
end
end
end
function MapClass:update(dt)
for k,pawn in pairs(self.pawns) do
pawn:update(dt)
end
end
function MapClass:draw()
end
function MapClass:square(coord)
return self.data[coord.y][coord.x]
end
function MapClass:blocked(coord)
return self:square(coord).blocked
end
function MapClass:occupant(coord)
return self:square(coord).occupant
end
function MapClass:set_occupant(coord, occupant)
self:square(coord).occupant = occupant
end
function MapClass.equipment(coord)
return self:square(coord).equipment
end
function MapClass:get_neighbors(coord)
local result, poss = { }, { {x=-1,y=0}, {x=1,y=0}, {x=0,y=-1}, {x=0,y=1} }
local c = Coordinate.new(0, 0)
for k,v in ipairs(poss) do
c.x, c.y = coord.x + v.x, coord.y + v.y
if self:valid_coordinate(c) and not self:blocked(c) then
table.insert(result, Coordinate.new(c.x, c.y))
end
end
return result
end
| mit |
madpilot78/ntopng | scripts/lua/iface_flows_sankey.lua | 1 | 6816 | --
-- (C) 2013-21 - ntop.org
--
dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
sendHTTPHeader('application/json')
tracked_host = _GET["host"]
interface.select(ifname)
max_num_peers = 10
max_num_links = 32
peers = getTopFlowPeers(tracked_host, max_num_peers, true --[[ high details for cli2srv.last/srv2cli.last fields ]])
local is_pcap_dump = interface.isPcapDumpInterface()
local debug = false
-- 1. compute total traffic
total_traffic = 0
for _, values in ipairs(peers) do
local key
local bytes
if(values["cli.ip"] == tracked_host) then
key = hostinfo2hostkey(values, "srv")
else
key = hostinfo2hostkey(values, "cli")
end
if is_pcap_dump then
bytes = values["bytes"]
else
bytes = values["bytes.last"]
end
total_traffic = total_traffic + bytes
if(debug) then io.write("->"..key.."\t[".. (values["bytes.last"]) .."][".. values["duration"].."]" .. "\n") end
end
if(debug) then io.write("\n") end
-- 2. compute flow threshold under which we do not print any relation
if(tracked_host == nil) then
threshold = (total_traffic * 3) / 100
else
threshold = 1
end
if(debug) then io.write("\nThreshold: "..threshold.."\n") end
-- map host -> incremental number
hosts = {}
num = 0
print '{"nodes":[\n'
-- print(" >>>[" .. tracked_host .. "]\n")
-- fills hosts table with available hosts and prints out some json code
while(num == 0) do
for _, values in ipairs(peers) do
local key
if(values["cli.ip"] == tracked_host) then
key = hostinfo2hostkey(values, "srv")
else
key = hostinfo2hostkey(values, "cli")
end
-- print("[" .. key .. "][" .. values["client"] .. ",".. values["client.vlan_id"] .. "][" .. values["server"] .. ",".. values["client.vlan_id"] .. "]\n")
local bytes
if(values["bytes.last"] == 0 and values.duration < 3) or is_pcap_dump then
bytes = values["bytes"]
else
bytes = values["bytes.last"]
end
if(bytes > threshold) then
if(debug) then io.write("==>" .. key .. "\t[T:" .. tracked_host .. "][" .. values["duration"] .. "][" .. bytes .. "]\n") end
if((debug) and (findString(key, tracked_host) ~= nil))then io.write("findString(key, tracked_host)==>"..findString(key, tracked_host)) end
if((debug) and (findString(values["cli.ip"], tracked_host) ~= nil)) then io.write("findString(values[cli.ip], tracked_host)==>"..findString(values["cli.ip"], tracked_host)) end
if((debug) and (findString(values["srv.ip"], tracked_host) ~= nil)) then io.write("findString(values[srv.ip], tracked_host)==>"..findString(values["srv.ip"], tracked_host)) end
local k = {hostinfo2hostkey(values, "cli"), hostinfo2hostkey(values, "srv")} --string.split(key, " ")
-- Note some checks are redundant here, they are already performed in getFlowPeers
if((tracked_host == nil)
or findString(k[1], tracked_host)
or findString(k[2], tracked_host)
or findString(values["cli.ip"], tracked_host)
or findString(values["srv.ip"], tracked_host)) then
-- print("[" .. key .. "]")
-- print("[" .. tracked_host .. "]\n")
-- for each cli, srv
for key,word in pairs(k) do
if(hosts[word] == nil) then
hosts[word] = num
if(num > 0) then
print ",\n"
end
host_info = hostkey2hostinfo(word)
-- 3. print nodes
local hinfo = hostkey2hostinfo(word)
name = hostinfo2label(hinfo)
print ("\t{\"name\": \"" .. name .. "\", \"host\": \"" .. host_info["host"] .. "\", \"vlan\": \"" .. host_info["vlan"] .. "\"}")
num = num + 1
end
end
end
end
end
if(num == 0) then
-- Lower the threshold to hope finding hosts
threshold = threshold / 2
end
if(threshold <= 1) then
break
end
end
top_host = nil
top_value = 0
if ((num == 0) and (tracked_host == nil)) then
-- 2.1 It looks like in this network there are many flows with no clear predominant traffic
-- Then we take the host with most traffic and print flows belonging to it
hosts_stats = interface.getHostsInfo(true, "column_traffic", max_num_peers)
hosts_stats = hosts_stats["hosts"]
for key, value in pairs(hosts_stats) do
value = hosts_stats[key]["traffic"]
if((value ~= nil) and (value > top_value)) then
top_host = key
top_value = value
end -- if
end -- for
if(top_host ~= nil) then
-- We now have have to find this host and some peers
hosts[top_host] = 0
host_info = hostkey2hostinfo(top_host)
print ("{\"name\": \"" .. top_host .. "\", \"host\": \"" .. host_info["host"] .. "\", \"vlan\": \"" .. host_info["vlan"] .. "\"}")
num = num + 1
for _, values in ipairs(peers) do
local key
if(values["cli.ip"] == tracked_host) then
key = hostinfo2hostkey(values, "srv")
else
key = hostinfo2hostkey(values, "cli")
end
if(findString(key, ip) or findString(values["client"], ip) or findString(values["server"], ip)) then
for key,word in pairs(split(key, " ")) do
if(hosts[word] == nil) then
hosts[word] = num
host_info = hostkey2hostinfo(word)
-- 3. print nodes
print ("{\"name\": \"" .. word .. "\", \"host\": \"" .. host_info["host"] .. "\", \"vlan\": \"" .. host_info["vlan"] .. "\"}")
num = num + 1
end --if
end -- for
end -- if
end -- for
end -- if
end -- if
print "\n],\n"
print '"links" : [\n'
-- 4. print links
-- print (top_host)
num = 0
-- Avoid to have a link A->B, and B->A
reverse_nodes = {}
for _, values in ipairs(peers) do
key = {hostinfo2hostkey(values, "cli"), hostinfo2hostkey(values, "srv")} --string.split(key, " ")
local val
if is_pcap_dump then
val = values["bytes"]
else
val = values["bytes.last"]
end
if(((val == 0) or (val > threshold)) or ((top_host ~= nil) and (findString(table.concat(key, " "), top_host) ~= nil)) and (num < max_num_links)) then
e = {}
id = 0
--print("->"..key.."\n")
for key,word in pairs(key) do
--print(word .. "=" .. hosts[word].."\n")
e[id] = hosts[word]
id = id + 1
end
if((e[0] ~= nil) and (e[1] ~= nil) and (e[0] ~= e[1]) and (reverse_nodes[e[0]..":"..e[1]] == nil)) then
if(num > 0) then
print ",\n"
end
reverse_nodes[e[1]..":"..e[0]] = 1
if is_pcap_dump then
sentv = values["cli2srv.last"]
recvv = values["srv2cli.last"]
else
sentv = values["cli2srv.bytes"]
recvv = values["srv2cli.bytes"]
end
if(val == 0) then
val = 1
end
print ("\t{\"source\": " .. e[0] .. ", \"target\": " .. e[1] .. ", \"value\": " .. val .. ", \"sent\": " .. sentv .. ", \"rcvd\": ".. recvv .. "}")
num = num + 1
end
end
end
print ("\n]}\n")
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/gfx/particles/reproach.lua | 3 | 2003 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
base_size = 32
local distributionOffset = math.rad(rng.range(0, 360))
return { generator = function()
local life = rng.float(6, 10)
local size = 1
local angle = math.rad(rng.range(0, 360))
local distribution = (math.sin(angle + distributionOffset) + 1) / 2
local distance = engine.Map.tile_w * rng.float(0.3, 0.9)
local startX = distance * math.cos(angle) + dx * engine.Map.tile_w
local startY = distance * math.sin(angle) + dy * engine.Map.tile_h
local alpha = (80 - distribution * 50) / 255
local speed = 0.02
local dirv = math.pi * 2 * speed
local vel = math.pi * distance * speed
return {
trail = 1,
life = life,
size = size, sizev = size / life / 3, sizea = 0,
x = -size / 2 + startX, xv = -startX / life, xa = 0,
y = -size / 2 + startY, yv = -startY / life, ya = 0,
dir = angle + math.rad(90), dirv = dirv, dira = 0,
vel = vel, velv = -vel / life, vela = 0,
r = (100 + distribution * 100) / 255, rv = 0, ra = 0,
g = 64 / 255, gv = 0, ga = 0,
b = (200 - distribution * 100) / 255, bv = 0, ba = 0,
a = 20 / 255, av = alpha / life / 2, aa = 0,
}
end, },
function(self)
self.nb = (self.nb or 0) + 1
if self.nb <= 5 then
self.ps:emit(500 - 60 * self.nb)
end
end,
500 * 10
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/engines/default/engine/CharacterVaultSave.lua | 3 | 2173 | -- TE4 - T-Engine 4
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
require "engine.class"
local Savefile = require "engine.Savefile"
--- Handles a local characters vault saves
module(..., package.seeall, class.inherit(Savefile))
function _M:init(savefile, coroutine)
Savefile.init(self, savefile, coroutine)
fs.mkdir("/vault")
self.short_name = savefile:gsub("[^a-zA-Z0-9_-.]", "_")
self.save_dir = "/vault/"..self.short_name.."/"
self.quickbirth_file = "/vault/"..self.short_name..".quickbirth"
self.load_dir = "/tmp/loadsave/"
end
--- Get a savename for an entity
function _M:nameSaveEntity(e)
e.__version = game.__mod_info.version
return "character.teac"
end
--- Get a savename for an entity
function _M:nameLoadEntity(name)
return "character.teac"
end
--- Save an entity
function _M:saveEntity(e, no_dialog)
Savefile.saveEntity(self, e, no_dialog)
local desc = game:getVaultDescription(e)
local f = fs.open(self.save_dir.."desc.lua", "w")
f:write(("module = %q\n"):format(game.__mod_info.short_name))
f:write(("module_version = {%d,%d,%d}\n"):format(game.__mod_info.version[1], game.__mod_info.version[2], game.__mod_info.version[3]))
f:write(("name = %q\n"):format(desc.name))
f:write(("short_name = %q\n"):format(self.short_name))
f:write("descriptors = {\n")
for k, e in pairs(desc.descriptors or {}) do
f:write(("\t[%q] = %q,\n"):format(k, e))
end
f:write("}\n")
f:write(("description = %q\n"):format(desc.description))
f:close()
end
| gpl-3.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Bastok_Mines/npcs/Elki.lua | 1 | 2443 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Elki
-- Starts Quests: Hearts of Mythril, The Eleventh's Hour
-----------------------------------
package.loaded["scripts/globals/quests"] = nil;
require("scripts/globals/quests");
require("scripts/globals/settings");
require("scripts/globals/titles");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
Fame = player:getFameLevel(BASTOK);
Hearts = player:getQuestStatus(BASTOK,HEARTS_OF_MYTHRIL);
HeartsVar = player:getVar("HeartsOfMythril");
Elevenths = player:getQuestStatus(BASTOK,THE_ELEVENTH_S_HOUR);
EleventhsVar = player:getVar("EleventhsHour");
HasToolbox = player:hasKeyItem(0x18);
if (Hearts == QUEST_AVAILABLE) then
player:startEvent(0x0029);
elseif (Hearts == QUEST_ACCEPTED and HeartsVar == 1) then
player:startEvent(0x002a);
elseif (Hearts == QUEST_COMPLETED and Elevenths == QUEST_AVAILABLE and Fame >=2) then
player:startEvent(0x002b);
elseif (Elevenths == QUEST_ACCEPTED and HasToolbox) then
player:startEvent(0x002c);
else
player:startEvent(0x001f);
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 == 0x0029 and option == 0) then
player:addQuest(BASTOK,HEARTS_OF_MYTHRIL);
player:addKeyItem(0x17);
player:messageSpecial(KEYITEM_OBTAINED,0x17);
elseif (csid == 0x002a) then
player:setTitle(84);
player:addItem(12840);
player:messageSpecial(ITEM_OBTAINED,12840);
player:completeQuest(BASTOK,HEARTS_OF_MYTHRIL);
player:addFame(BASTOK,BAS_FAME*80);
player:setVar("HeartsOfMythril",0);
elseif (csid == 0x002b and option == 1) then
player:addQuest(BASTOK,THE_ELEVENTH_S_HOUR);
elseif (csid == 0x002c) then
player:setVar("EleventhsHour",1);
end
end;
| gpl-3.0 |
RyMarq/Zero-K | LuaRules/Gadgets/cmd_factory_stop_production.lua | 1 | 2978 | --------------------------------------------------------------------------------
--------------------------------------------------------------------------------
function gadget:GetInfo()
return {
name = "Factory Stop Production",
desc = "Adds a command to clear the factory queue",
author = "GoogleFrog",
date = "13 November 2016",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = true -- loaded by default?
}
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
if (not gadgetHandler:IsSyncedCode()) then
return false -- no unsynced code
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local spGetFactoryCommands = Spring.GetFactoryCommands
local spGiveOrderToUnit = Spring.GiveOrderToUnit
local spInsertUnitCmdDesc = Spring.InsertUnitCmdDesc
local CMD_OPT_CTRL = CMD.OPT_CTRL
local CMD_REMOVE = CMD.REMOVE
include("LuaRules/Configs/customcmds.h.lua")
local isFactory = {}
for udid = 1, #UnitDefs do
local ud = UnitDefs[udid]
if ud.isFactory and not ud.customParams.notreallyafactory then
isFactory[udid] = true
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
local stopProductionCmdDesc = {
id = CMD_STOP_PRODUCTION,
type = CMDTYPE.ICON,
name = 'Stop Production',
action = 'stopproduction',
cursor = 'Stop', -- Probably does nothing
tooltip = 'Clear the unit production queue.',
}
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Handle the command
function gadget:AllowCommand_GetWantedCommand()
return {[CMD_STOP_PRODUCTION] = true}
end
function gadget:AllowCommand_GetWantedUnitDefID()
return isFactory
end
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
if (cmdID ~= CMD_STOP_PRODUCTION) or (not isFactory[unitDefID]) then
return
end
local commands = spGetFactoryCommands(unitID, -1)
if not commands then
return
end
for i = 1, #commands do
spGiveOrderToUnit(unitID, CMD_REMOVE, commands[i].tag, CMD_OPT_CTRL)
end
end
--------------------------------------------------------------------------------
--------------------------------------------------------------------------------
-- Add the command to factories
function gadget:UnitCreated(unitID, unitDefID)
if isFactory[unitDefID] then
spInsertUnitCmdDesc(unitID, stopProductionCmdDesc)
end
end
function gadget:Initialize()
gadgetHandler:RegisterCMDID(CMD_STOP_PRODUCTION)
for _, unitID in pairs(Spring.GetAllUnits()) do
gadget:UnitCreated(unitID, Spring.GetUnitDefID(unitID))
end
end
| gpl-2.0 |
OpenMusicKontrollers/chimaera_tjost | plumber.lua | 1 | 2325 | #!/usr/bin/env tjost
--[[
* Copyright (c) 2015 Hanspeter Portner (dev@open-music-kontrollers.ch)
*
* This is free software: you can redistribute it and/or modify
* it under the terms of the Artistic License 2.0 as published by
* The Perl Foundation.
*
* This source 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
* Artistic License 2.0 for more details.
*
* You should have received a copy of the Artistic License 2.0
* along the source as a COPYING file. If not, obtain it from
* http://www.perlfoundation.org/artistic_license_2_0.
--]]
message = tjost.plugin({name='dump'})
graph = {}
rules = {
{'system:capture_1', 'system:playback_1'},
{'system:capture_2', 'system:playback_2'}
}
function update_plumbing()
for _, v in ipairs(rules) do
local a = v[1]
local b = v[2]
if graph[a] and graph[b] and (not graph[a][b]) then
uplink(0, '/jack/connect', 'ss', a, b)
end
end
end
function clone_graph()
graph = {}
uplink(0, '/jack/ports', '')
end
methods = {
['/jack/ports'] = function(time, fmt, ...)
for _, v in ipairs({...}) do
graph[v] = {}
uplink(0, '/jack/connections', 's', v)
end
end,
['/jack/connections'] = function(time, fmt, port, ...)
for _, v in ipairs({...}) do
graph[port][v] = true
end
update_plumbing()
end,
['/jack/client/registration'] = function(time, fmt, name, state)
--
end,
['/jack/port/registration'] = function(time, fmt, name, state)
if state then
graph[name] = {}
uplink(0, '/jack/connections', 's', name)
else
graph[name] = nil
end
end,
['/jack/port/connect'] = function(time, fmt, name_a, name_b, state)
graph[name_a][name_b] = state
if not state then
update_plumbing()
end
end,
['/jack/port/rename'] = function(time, fmt, name_old, name_new)
graph[name_new] = graph[name_old]
graph[name_old] = nil
for k, v in pairs(graph) do
if v[name_old] then
v[name_new] = v[name_old]
v[name_old] = nil
end
end
end,
['/jack/graph/order'] = function(time)
--
end
}
uplink = tjost.plugin({name='uplink'}, function(time, path, fmt, ...)
message(time, path, fmt, ...)
local cb = methods[path]
if cb then
cb(time, fmt, ...)
end
end)
clone_graph()
| artistic-2.0 |
RyMarq/Zero-K | lups/headers/nanoupdate.lua | 8 | 5407 | -- $Id: general.lua 3171 2008-11-06 09:06:29Z det $
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
--
-- file: nanoupdate.lua
-- brief: shared code between all nano particle effects
-- authors: jK
-- last updated: Feb. 2010
--
-- Copyright (C) 2010.
-- Licensed under the terms of the GNU GPL, v2 or later.
--
---------------------------------------------------------------------------------------------
---------------------------------------------------------------------------------------------
local GetMovetypeUnitDefID = Spring.Utilities.GetMovetypeUnitDefID
local function GetUnitMidPos(unitID)
local _,_,_, x, y, z = Spring.GetUnitPosition(unitID, true)
return x, y, z
end
local function GetFeatureMidPos(featureID)
local _,_,_, x, y, z = Spring.GetFeaturePosition(featureID, true)
return x, y, z
end
local function GetUnitIsMobile(self, unitID)
if self.inversed then
return false
end
local unitDefID = Spring.GetUnitDefID(unitID)
if not GetMovetypeUnitDefID(unitDefID) then
return false
end
local build = select(5, Spring.GetUnitHealth(unitID))
if (build or 0) < 1 then
return false
end
return true
end
local function GetCmdTag(unitID)
local cmdTag = 0
local cmds = Spring.GetFactoryCommands(unitID,1)
if (cmds) then
local cmd = cmds[1]
if cmd then
cmdTag = cmd.tag
end
end
if cmdTag == 0 then
local cmds = Spring.GetCommandQueue(unitID,1)
if (cmds) then
local cmd = cmds[1]
if cmd then
cmdTag = cmd.tag
end
end
end
return cmdTag
end
function UpdateNanoParticles(self)
if self.reuseLinger and self.frame and self.frame ~= 0 and self.frame + self.reuseLinger >= self.maxLife then
self.visibility = 0
return not self.reuseDead
end
--// UPDATE START- & FINALPOS
if (self._staticTarget ~= 1) and (not self._dead) and ((not self._lastupdate) or (thisGameFrame - self._lastupdate >= 1)) then
self._lastupdate = thisGameFrame
--// UPDATE STARTPOS
local uid = self.unitID
if Spring.ValidUnitID(uid) then
self.pos = {Spring.GetUnitPiecePosDir(uid,self.unitpiece)}
else
if (not self._dead) then
--// assigned source unit died
self._dead = true
return
end
end
--// UPDATE FINALPOS
local tid = self.targetID
if (tid >= 0) then
if (not self.isFeature) then
if Spring.ValidUnitID(tid) then
self.targetpos = {GetUnitMidPos(tid)}
if (not self._staticTarget) then
self._staticTarget = (GetUnitIsMobile(self,tid) and 0) or 1
end
else
self._staticTarget = 1
if (not self._dead) then
--// assigned target unit died
self._dead = true
return
end
end
else
self._staticTarget = 1
if Spring.ValidFeatureID(tid) then
self.targetpos = {GetFeatureMidPos(tid)}
self.targetpos[2] = self.targetpos[2] + 25
else
if (not self._dead) then
--// assigned target feature died
self._dead = 1
return
end
end
end
else
self._staticTarget = 1
end
local cmdTag = GetCmdTag(self.unitID)
if (cmdTag == 0 or cmdTag ~= self.cmdTag) then
self._dead = true
return
end
end
--// UPDATE LOS
local allied = (self.allyID==LocalAllyTeamID)or(LocalAllyTeamID==Script.ALL_ACCESS_TEAM)
local lastup_los = self._lastupdate_los or (thisGameFrame - 16)
if (not self._lastupdate_los) or ((thisGameFrame - lastup_los > 16)and(not allied)) then
self._lastupdate_los = thisGameFrame
local startPos = self.pos
local endPos = self.targetpos
if (not endPos) then
--//this just happens when the target feature/unit was already dead when the fx was created
self._dead = true
RemoveParticles(self.id)
return
end
if (allied) then
self.visibility = 1
else
self.visibility = 0
local _,startLos = Spring.GetPositionLosState(startPos[1],startPos[2],startPos[3], LocalAllyTeamID)
local _,endLos = Spring.GetPositionLosState( endPos[1], endPos[2], endPos[3], LocalAllyTeamID)
if (not startLos)and(not endLos) then
self.visibility = 0
elseif (startLos and endLos) then
self.visibility = 1
elseif (startLos) then
local dir = Vsub(endPos, startPos)
local losRayTile = math.ceil(Vlength(dir)/Game.squareSize)
for i=losRayTile,0,-1 do
local losPos = Vadd(self.pos,Vmul(dir,i/losRayTile))
local _,los = Spring.GetPositionLosState(losPos[1],losPos[2],losPos[3], LocalAllyTeamID)
if (los) then self.visibility = i/losRayTile; break end
end
endPos = Vadd(endPos,Vmul(dir,self.visibility-1))
self.targetpos = endPos
else --//if (endLos) then
local dir = Vsub(endPos, startPos)
local losRayTile = math.ceil(Vlength(dir)/Game.squareSize)
for i=0,losRayTile do
local losPos = Vadd(self.pos,Vmul(dir,i/losRayTile))
local _,los = Spring.GetPositionLosState(losPos[1],losPos[2],losPos[3], LocalAllyTeamID)
if (los) then self.visibility = -i/losRayTile; break end
end
startPos = Vadd(startPos,Vmul(dir,-self.visibility))
self.pos = startPos
end
end
local dir = Vsub(endPos, startPos)
local half_dir = Vmul(dir, 0.5)
local length = Vlength(dir)
self.dir = dir
self.normdir = Vmul( dir, 1/length )
self._midpos = Vadd(startPos, half_dir)
self._radius = length*0.5 + 200
end
end
| gpl-2.0 |
RyMarq/Zero-K | units/factoryship.lua | 1 | 2657 | return { factoryship = {
unitname = [[factoryship]],
name = [[Shipyard]],
description = [[Produces Naval Units, Builds at 10 m/s]],
acceleration = 0,
brakeRate = 0,
buildCostMetal = Shared.FACTORY_COST,
builder = true,
buildoptions = {
[[shipcon]],
[[shipscout]],
[[shiptorpraider]],
[[subraider]],
[[shipriot]],
[[shipskirm]],
[[shipassault]],
[[shiparty]],
[[shipaa]],
},
buildPic = [[FACTORYSHIP.png]],
canMove = true,
canPatrol = true,
category = [[UNARMED FLOAT]],
collisionVolumeOffsets = [[-22 5 0]],
collisionVolumeScales = [[48 48 184]],
collisionVolumeType = [[cylZ]],
selectionVolumeOffsets = [[18 0 0]],
selectionVolumeScales = [[130 50 184]],
selectionVolumeType = [[box]],
corpse = [[DEAD]],
customParams = {
sortName = [[7]],
unstick_help = 1,
aimposoffset = [[60 0 -15]],
midposoffset = [[0 0 -15]],
solid_factory = [[2]],
modelradius = [[100]],
solid_factory_rotation = [[1]], -- 90 degrees counter clockwise
default_spacing = 8,
selectionscalemult = 1,
factorytab = 1,
shared_energy_gen = 1,
cus_noflashlight = 1,
},
energyUse = 0,
explodeAs = [[LARGE_BUILDINGEX]],
footprintX = 8,
footprintZ = 12,
iconType = [[facship]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 6000,
maxSlope = 15,
maxVelocity = 0,
minCloakDistance = 150,
minWaterDepth = 15,
moveState = 1,
objectName = [[seafac.s3o]],
script = [[factoryship.lua]],
selfDestructAs = [[LARGE_BUILDINGEX]],
showNanoSpray = false,
sightDistance = 273,
turnRate = 0,
waterline = 0,
workerTime = Shared.FACTORY_BUILDPOWER,
yardMap = [[oocccccc oocccccc oocccccc oocccccc oocccccc oocccccc oocccccc oocccccc oocccccc oocccccc oocccccc oocccccc]],
featureDefs = {
DEAD = {
blocking = false,
featureDead = [[HEAP]],
footprintX = 9,
footprintZ = 14,
object = [[seafac_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 8,
footprintZ = 8,
object = [[debris4x4c.s3o]],
},
},
} }
| gpl-2.0 |
vince06fr/prosody-modules | mod_idlecompat/mod_idlecompat.lua | 35 | 1149 | -- Last User Interaction in Presence via Last Activity compatibility module
-- http://xmpp.org/extensions/xep-0319.html
-- http://xmpp.org/extensions/xep-0012.html
-- Copyright (C) 2014 Tobias Markmann
--
-- This file is MIT/X11 licensed.
local st = require "util.stanza";
local datetime = require "util.datetime";
local function on_presence(event)
local stanza = event.stanza;
local last_activity = stanza.name == "presence" and stanza:get_child("query", "jabber:iq:last") or false;
local has_idle = stanza:get_child("idle", "urn:xmpp:idle:1");
if last_activity and not has_idle then
module:log("debug", "Adding XEP-0319 tag from Last Activity.");
local seconds = last_activity.attr.seconds;
local last_userinteraction = datetime.datetime(os.time() - seconds);
stanza:tag("idle", { xmlns = "urn:xmpp:idle:1", since = last_userinteraction }):up();
end
end
-- incoming
module:hook("presence/full", on_presence, 900);
module:hook("presence/bare", on_presence, 900);
-- outgoing
module:hook("pre-presence/bare", on_presence, 900);
module:hook("pre-presence/full", on_presence, 900);
module:hook("pre-presence/host", on_presence, 900); | mit |
pyxenium/EasyAutoLoot | Libs/AceConfig-3.0/AceConfig-3.0.lua | 43 | 2183 | --- AceConfig-3.0 wrapper library.
-- Provides an API to register an options table with the config registry,
-- as well as associate it with a slash command.
-- @class file
-- @name AceConfig-3.0
-- @release $Id: AceConfig-3.0.lua 969 2010-10-07 02:11:48Z shefki $
--[[
AceConfig-3.0
Very light wrapper library that combines all the AceConfig subcomponents into one more easily used whole.
]]
local MAJOR, MINOR = "AceConfig-3.0", 2
local AceConfig = LibStub:NewLibrary(MAJOR, MINOR)
if not AceConfig then return end
local cfgreg = LibStub("AceConfigRegistry-3.0")
local cfgcmd = LibStub("AceConfigCmd-3.0")
--TODO: local cfgdlg = LibStub("AceConfigDialog-3.0", true)
--TODO: local cfgdrp = LibStub("AceConfigDropdown-3.0", true)
-- Lua APIs
local pcall, error, type, pairs = pcall, error, type, pairs
-- -------------------------------------------------------------------
-- :RegisterOptionsTable(appName, options, slashcmd, persist)
--
-- - appName - (string) application name
-- - options - table or function ref, see AceConfigRegistry
-- - slashcmd - slash command (string) or table with commands, or nil to NOT create a slash command
--- Register a option table with the AceConfig registry.
-- You can supply a slash command (or a table of slash commands) to register with AceConfigCmd directly.
-- @paramsig appName, options [, slashcmd]
-- @param appName The application name for the config table.
-- @param options The option table (or a function to generate one on demand). http://www.wowace.com/addons/ace3/pages/ace-config-3-0-options-tables/
-- @param slashcmd A slash command to register for the option table, or a table of slash commands.
-- @usage
-- local AceConfig = LibStub("AceConfig-3.0")
-- AceConfig:RegisterOptionsTable("MyAddon", myOptions, {"/myslash", "/my"})
function AceConfig:RegisterOptionsTable(appName, options, slashcmd)
local ok,msg = pcall(cfgreg.RegisterOptionsTable, self, appName, options)
if not ok then error(msg, 2) end
if slashcmd then
if type(slashcmd) == "table" then
for _,cmd in pairs(slashcmd) do
cfgcmd:CreateChatCommand(cmd, appName)
end
else
cfgcmd:CreateChatCommand(slashcmd, appName)
end
end
end
| mit |
RyMarq/Zero-K | LuaRules/Gadgets/start_teamnames.lua | 1 | 1097 | if not gadgetHandler:IsSyncedCode() then return end
function gadget:GetInfo()
return {
name = "Backup allyteam names",
layer = math.huge, -- last so that we only cover up holes; actual names are set by startbox handler (MP) or mission handlers (SP)
enabled = true,
}
end
local PUBLIC_VISIBLE = {public = true}
function gadget:Initialize()
local allyTeamList = Spring.GetAllyTeamList()
for i = 1, #allyTeamList do
local allyTeamID = allyTeamList[i]
if not Spring.GetGameRulesParam("allyteam_short_name_" .. allyTeamID) then
Spring.SetGameRulesParam("allyteam_short_name_" .. allyTeamID, "Team " .. allyTeamID)
Spring.SetGameRulesParam("allyteam_long_name_" .. allyTeamID, "Team " .. allyTeamID)
end
end
if Spring.GetGameFrame() < 1 then
local teamList = Spring.GetTeamList()
for i = 1, #teamList do
local teamID = teamList[i]
local _, leaderID, isDead, isAiTeam, _, allyTeamID = Spring.GetTeamInfo(teamID, false)
if leaderID >= 0 then
leaderID = Spring.SetTeamRulesParam(teamID, "initLeaderID", leaderID, PUBLIC_VISIBLE)
end
end
end
end
| gpl-2.0 |
matin-igdery/og | plugins/Feedback.lua | 1 | 1068 | do
function run(msg, matches)
local fuse = '#DearAdmin😜 we have recived a new feedback just now : #newfeedback \n\n🆔 : ' .. msg.from.id .. '\n\nNAME▶️ : ' .. msg.from.print_name ..'\n\nusername▶️ :@ ' .. msg.from.username ..'\n\n🅿♏ ️️ :\n\n\n' .. matches[1]
local fuses = '!printf user#id' .. msg.from.id
local text = matches[1]
bannedidone = string.find(msg.from.id, '123')
bannedidtwo =string.find(msg.from.id, '465')
bannedidthree =string.find(msg.from.id, '678')
print(msg.to.id)
if bannedidone or bannedidtwo or bannedidthree then --for banned people
return 'You are banned to send a feedback'
else
local sends0 = send_msg('chat#59845789', fuse, ok_cb, false)
return 'Your request has been sended to @gnbd_army 😜!'
end
end
return {
description = "Feedback to sudos",
usage = "!feedback : send maseage to admins with bot",
patterns = {
"^[!/]([Ff]eedback) (.*)$"
},
run = run
}
end
--by @ArashInfernal--
| gpl-2.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Mod/ModManager.lua | 1 | 2909 | --[[
Title: plugin manager
Author(s): LiXizhi
Date: 2015/4/9
Desc: mod is a special type of plugin that can be dynamically loaded.
use the lib:
------------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Mod/ModManager.lua");
local ModManager = commonlib.gettable("Mod.ModManager");
ModManager:Init();
ModManager:OnLoadWorld();
-------------------------------------------------------
]]
NPL.load("(gl)script/ide/System/Plugins/PluginManager.lua");
NPL.load("(gl)script/apps/Aries/Creator/Game/Mod/ModBase.lua");
local GameLogic = commonlib.gettable("MyCompany.Aries.Game.GameLogic")
local PluginManager = commonlib.gettable("System.Plugins.PluginManager");
local ModManager = commonlib.inherit(PluginManager, {});
ModManager:Property({"Name", "Paracraft"});
function ModManager:ctor()
end
-- called only once
function ModManager:Init()
if(self.inited) then
return;
end
self.inited = true;
GameLogic.GetFilters():add_filter("InitDesktop", function(bSkipDefaultDesktop)
return self:OnInitDesktop();
end);
GameLogic.GetFilters():add_filter("ActivateDesktop", function(bIgnoreDefaultDesktop, mode)
return self:OnActivateDesktop(mode);
end);
end
function ModManager:handleKeyEvent(event)
return self:InvokeMethod("handleKeyEvent", event);
end
function ModManager:handleMouseEvent(event)
return self:InvokeMethod("handleMouseEvent", event);
end
-- signal
function ModManager:OnWorldLoad()
self:InvokeMethod("OnWorldLoad");
LOG.std(nil, "info", "ModManager", "plugins (mods) loaded in world");
end
-- signal
function ModManager:OnWorldSave()
self:InvokeMethod("OnWorldSave");
LOG.std(nil, "info", "ModManager", "plugins (mods) saved in world");
end
-- singal
function ModManager:OnWillLeaveWorld()
self:InvokeMethod("OnWillLeaveWorld");
end
-- signal
function ModManager:OnLeaveWorld()
self:InvokeMethod("OnLeaveWorld");
end
-- signal
function ModManager:OnDestroy()
self:InvokeMethod("OnDestroy");
end
-- signal
function ModManager:OnLogin()
self:InvokeMethod("OnLogin");
end
-- called when a desktop is inited such as displaying the initial user interface.
-- return true to prevent further processing.
function ModManager:OnInitDesktop()
return self:InvokeMethod("OnInitDesktop");
end
-- virtual: called when a desktop mode is changed such as from game mode to edit mode.
-- return true to prevent further processing.
function ModManager:OnActivateDesktop(mode)
return self:InvokeMethod("OnActivateDesktop", mode);
end
-- virtual: called when a user try to close the application window
-- return true to prevent further processing.
function ModManager:OnClickExitApp(bForceExit, bRestart)
return self:InvokeMethod("OnClickExitApp",bForceExit, bRestart);
end
-- create singleton and assign it to Mod.ModManager
local g_Instance = ModManager:new(commonlib.gettable("Mod.ModManager"));
PluginManager.AddInstance(g_Instance); | gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Monastic_Cavern/npcs/qm1.lua | 1 | 1376 | -----------------------------------
-- Area: Monastic Cavern
-- NPC: ???
-- Used In Quest: Whence Blows the Wind
-- @zone 150
-- @pos 168 -1 -22
-----------------------------------
package.loaded["scripts/zones/Monastic_Cavern/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/settings");
require("scripts/globals/keyitems");
require("scripts/globals/quests");
require("scripts/zones/Monastic_Cavern/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
if(player:getQuestStatus(JEUNO,WHENCE_BLOWS_THE_WIND) == QUEST_ACCEPTED and player:hasKeyItem(ORCISH_CREST) == false) then
player:addKeyItem(ORCISH_CREST);
player:messageSpecial(KEYITEM_OBTAINED, ORCISH_CREST);
else
player:messageSpecial(NOTHING_ORDINARY_HERE);
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 |
RyMarq/Zero-K | units/zenith.lua | 1 | 10817 | return { zenith = {
unitname = [[zenith]],
name = [[Zenith]],
description = [[Meteor Controller]],
acceleration = 0,
activateWhenBuilt = true,
buildCostMetal = 40000,
builder = false,
buildingGroundDecalDecaySpeed = 30,
buildingGroundDecalSizeX = 11,
buildingGroundDecalSizeY = 11,
buildingGroundDecalType = [[zenith_aoplane.dds]],
buildPic = [[zenith.png]],
category = [[SINK]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[90 194 90]],
collisionVolumeType = [[cylY]],
corpse = [[DEAD]],
customParams = {
keeptooltip = [[any string I want]],
--neededlink = 150,
--pylonrange = 150,
modelradius = [[45]],
},
energyUse = 0,
explodeAs = [[ATOMIC_BLAST]],
fireState = 0,
footprintX = 8,
footprintZ = 8,
iconType = [[mahlazer]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 12000,
maxSlope = 18,
maxVelocity = 0,
maxWaterDepth = 0,
minCloakDistance = 150,
noChaseCategory = [[FIXEDWING GUNSHIP SUB STUPIDTARGET]],
objectName = [[zenith.s3o]],
onoffable = true,
script = [[zenith.lua]],
selfDestructAs = [[ATOMIC_BLAST]],
sightDistance = 660,
turnRate = 0,
useBuildingGroundDecal = true,
workerTime = 0,
yardMap = [[oooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo]],
weapons = {
{
def = [[METEOR]],
badTargetCateogory = [[MOBILE]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER GUNSHIP]],
},
{
def = [[GRAVITY_NEG]],
onlyTargetCategory = [[NONE]],
},
},
weaponDefs = {
GRAVITY_NEG = {
name = [[Attractive Gravity (fake)]],
alwaysVisible = 1,
avoidFriendly = false,
canAttackGround = false,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
light_radius = 0,
},
damage = {
default = 0.001,
planes = 0.001,
subs = 5E-05,
},
duration = 2,
explosionGenerator = [[custom:NONE]],
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0,
intensity = 0.7,
interceptedByShieldType = 1,
noSelfDamage = true,
range = 20000,
reloadtime = 0.2,
rgbColor = [[0 0 1]],
rgbColor2 = [[1 0.5 1]],
size = 32,
soundStart = [[weapon/gravity_fire]],
soundStartVolume = 0.15,
thickness = 32,
tolerance = 5000,
turret = true,
weaponType = [[LaserCannon]],
weaponVelocity = 6000,
},
METEOR = {
name = [[Meteor]],
accuracy = 700,
alwaysVisible = 1,
areaOfEffect = 240,
avoidFriendly = false,
avoidFeature = false,
avoidGround = false,
cegTag = [[METEOR_TAG]],
collideFriendly = true,
craterBoost = 3,
craterMult = 6,
customParams = {
light_color = [[2.4 1.5 0.6]],
light_radius = 600,
spawns_name = "asteroid_dead",
spawns_feature = 1,
},
damage = {
default = 1600,
subs = 80,
},
edgeEffectiveness = 0.8,
explosionGenerator = [[custom:av_tess]],
fireStarter = 70,
flightTime = 30,
impulseBoost = 250,
impulseFactor = 0.5,
interceptedByShieldType = 2,
noSelfDamage = false,
model = [[asteroid.s3o]],
range = 9000,
reloadtime = 1,
smokeTrail = true,
soundHit = [[weapon/cannon/supergun_bass_boost]],
startVelocity = 1500,
textures = {
[[null]],
[[null]],
[[null]],
},
turret = true,
turnrate = 2000,
weaponAcceleration = 2000,
weaponType = [[MissileLauncher]],
weaponVelocity = 1600,
wobble = 5500,
},
METEOR_AIM = {
name = [[Meteor]],
accuracy = 700,
alwaysVisible = 1,
areaOfEffect = 240,
avoidFriendly = false,
avoidFeature = false,
avoidGround = false,
cegTag = [[meteor_aim]],
collideFriendly = true,
craterBoost = 3,
craterMult = 6,
customParams = {
light_radius = 0,
spawns_name = "asteroid_dead",
spawns_feature = 1,
},
damage = {
default = 1600,
subs = 80,
},
edgeEffectiveness = 0.8,
explosionGenerator = [[custom:av_tess]],
fireStarter = 70,
flightTime = 300,
impulseBoost = 250,
impulseFactor = 0.5,
interceptedByShieldType = 2,
noSelfDamage = false,
model = [[asteroid.s3o]],
range = 9000,
reloadtime = 1,
smokeTrail = true,
soundHit = [[weapon/cannon/supergun_bass_boost]],
startVelocity = 1500,
textures = {
[[null]],
[[null]],
[[null]],
},
tracks = true,
turret = true,
turnRate = 25000,
weaponAcceleration = 600,
weaponType = [[MissileLauncher]],
weaponVelocity = 1200,
wobble = 0,
},
METEOR_FLOAT = {
name = [[Meteor]],
accuracy = 700,
alwaysVisible = 1,
areaOfEffect = 240,
avoidFriendly = false,
avoidFeature = false,
avoidGround = false,
cegTag = [[meteor_hover]],
collideFriendly = true,
craterBoost = 3,
craterMult = 6,
customParams = {
light_radius = 0,
do_not_save = 1, -- Controlled meteors are regenerated on load.
spawns_name = "asteroid_dead",
spawns_feature = 1,
},
damage = {
default = 1600,
subs = 80,
},
edgeEffectiveness = 0.8,
explosionGenerator = [[custom:av_tess]],
fireStarter = 70,
flightTime = 300,
impulseBoost = 250,
impulseFactor = 0.5,
interceptedByShieldType = 2,
noSelfDamage = false,
model = [[asteroid.s3o]],
range = 9000,
reloadtime = 1,
smokeTrail = true,
soundHit = [[weapon/cannon/supergun_bass_boost]],
startVelocity = 1500,
textures = {
[[null]],
[[null]],
[[null]],
},
tracks = true,
trajectoryHeight = 0,
turret = true,
turnRate = 6000,
weaponAcceleration = 200,
weaponType = [[MissileLauncher]],
weaponVelocity = 200,
wobble = 30000,
},
METEOR_UNCONTROLLED = {
name = [[Meteor]],
accuracy = 700,
alwaysVisible = 1,
areaOfEffect = 240,
avoidFriendly = false,
avoidFeature = false,
avoidGround = false,
cegTag = [[meteor_fall]],
collideFriendly = true,
craterBoost = 3,
craterMult = 6,
customParams = {
light_color = [[2.4 1.5 0.6]],
light_radius = 600,
do_not_save = 1, -- Controlled meteors are regenerated on load.
spawns_name = "asteroid_dead",
spawns_feature = 1,
},
damage = {
default = 1600,
subs = 80,
},
edgeEffectiveness = 0.8,
explosionGenerator = [[custom:av_tess]],
fireStarter = 70,
flightTime = 30,
impulseBoost = 250,
impulseFactor = 0.5,
interceptedByShieldType = 2,
noSelfDamage = false,
model = [[asteroid.s3o]],
range = 9000,
reloadtime = 1,
smokeTrail = true,
soundHit = [[weapon/cannon/supergun_bass_boost]],
startVelocity = 1500,
textures = {
[[null]],
[[null]],
[[null]],
},
turret = true,
weaponType = [[Cannon]],
weaponVelocity = 1600,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 8,
footprintZ = 8,
object = [[zenith_dead.s3o]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[90 194 90]],
collisionVolumeType = [[cylY]],
},
HEAP = {
blocking = false,
footprintX = 3,
footprintZ = 3,
object = [[debris4x4c.s3o]],
},
},
} }
| gpl-2.0 |
james2doyle/lit | libs/handlers.lua | 4 | 6708 | --[[
Copyright 2014-2015 The Luvit Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS-IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
--]]
local log = require('log').log
local git = require('git')
local digest = require('openssl').digest.digest
local githubQuery = require('github-request')
local jsonParse = require('json').parse
local verifySignature = require('verify-signature')
local function split(line)
local args = {}
for match in string.gmatch(line, "[^ ]+") do
args[#args + 1] = match
end
return unpack(args)
end
local metrics = require('metrics')
return function (core)
local db = core.db
local handlers = {}
metrics.define("handlers.read")
function handlers.read(remote, data)
metrics.increment("handlers.read")
local name, version = split(data)
local author
author, name = name:match("([^/]+)/(.*)")
-- TODO: check for mismatch
local hash = db.read(author, name, version)
remote.writeAs("reply", hash)
end
metrics.define("handlers.match")
function handlers.match(remote, data)
metrics.increment("handlers.match")
local name, version = split(data)
local author
author, name = name:match("([^/]+)/(.*)")
if not name then
return remote.writeAs("error", "Missing name parameter")
end
local match, hash = db.match(author, name, version)
if not match and hash then
error(hash)
end
remote.writeAs("reply", match and (match .. ' ' .. hash))
end
metrics.define("handlers.wants")
function handlers.wants(remote, hashes)
metrics.increment("handlers.wants")
for i = 1, #hashes do
local hash = hashes[i]
local data, err = db.load(hash)
if not data then
return remote.writeAs("error", err or "No such hash: " .. hash)
end
local kind, raw = git.deframe(data)
if kind == 'tag' then
local tag = git.decoders.tag(raw)
log("client want", tag.tag)
else
log("client want", hash, "string")
end
remote.writeAs("send", data)
end
end
metrics.define("handlers.want")
function handlers.want(remote, hash)
metrics.increment("handlers.want")
return handlers.wants(remote, {hash})
end
metrics.define("handlers.send")
function handlers.send(remote, data)
metrics.increment("handlers.send")
local authorized = remote.authorized or {}
local kind, raw = git.deframe(data)
local hashes = {}
do
local hash = digest("sha1", data)
if kind == "tag" then
if remote.tag then
return remote.writeAs("error", "package upload already in progress: " .. remote.tag.tag)
end
local tag = git.decoders.tag(raw)
local username = string.match(tag.tag, "^[^/]+")
local success, err = verifySignature(db, username, raw)
if not success then
return remote.writeAs("error", err or "Signature verification failure")
end
tag.hash = hash
remote.tag = tag
remote.authorized = authorized
hashes[#hashes + 1] = tag.object
local meta = jsonParse(tag.message)
if meta and meta.snapshot then
hashes[#hashes + 1] = meta.snapshot
end
else
if not authorized[hash] then
return remote.writeAs('error', "Attempt to send unauthorized object: " .. hash)
end
authorized[hash] = nil
if kind == "tree" then
local tree = git.decoders.tree(raw)
for i = 1, #tree do
hashes[#hashes + 1] = tree[i].hash
end
end
end
assert(db.save(data) == hash)
end
local wants = {}
for i = 1, #hashes do
local hash = hashes[i]
if not (authorized[hash] or db.has(hash)) then
wants[#wants + 1] = hash
authorized[hash] = true
end
end
if #wants > 0 then
remote.writeAs("wants", wants)
elseif not next(authorized) then
local tag = remote.tag
local author, name, version = string.match(tag.tag, "([^/]+)/(.*)/v(.*)")
db.write(author, name, version, tag.hash)
log("new package", tag.tag)
remote.writeAs("done", tag.hash)
remote.tag = nil
remote.authorized = nil
end
end
local function verifyRequest(raw)
local data = assert(jsonParse(string.match(raw, "([^\n]+)")))
local success, err = verifySignature(db, data.username, raw)
assert(success, err or "Signature verification failure")
return data
end
metrics.define("handlers.claim")
function handlers.claim(remote, raw)
metrics.increment("handlers.claim")
-- The request is RSA signed by the .username field.
-- This will verify the signature and return the data table
local data = verifyRequest(raw)
local username, org = data.username, data.org
if db.isOwner(org, username) then
error("Already an owner in org: " .. org)
end
local head, members = githubQuery("/orgs/" .. org .. "/public_members")
if head.code == 404 then
error("Not an org name: " .. org)
end
local member = false
for i = 1, #members do
if members[i].login == username then
member = true
break
end
end
if not member then
error("Not a public member of org: " .. org)
end
db.addOwner(org, username)
remote.writeAs("reply", "claimed")
end
metrics.define("handlers.share")
function handlers.share(remote, raw)
metrics.increment("handlers.share")
local data = verifyRequest(raw)
local username, org, friend = data.username, data.org, data.friend
if not db.isOwner(org, username) then
error("Can't share a org you're not in: " .. org)
end
if (db.isOwner(org, friend)) then
error("Friend already in org: " .. friend)
end
db.addOwner(org, friend)
remote.writeAs("reply", "shared")
end
metrics.define("handlers.unclaim")
function handlers.unclaim(remote, raw)
metrics.increment("handlers.unclaim")
local data = verifyRequest(raw)
local username, org = data.username, data.org
if not db.isOwner(org, username) then
error("Non a member of org: " .. org)
end
db.removeOwner(org, username)
remote.writeAs("reply", "unshared")
end
return handlers
end
| apache-2.0 |
gleachkr/luakit | lib/select_wm.lua | 2 | 19685 | --- Select a page element with a visual interface.
--
-- This web module allows other Lua modules to select page elements with the
-- same interface as that used by the follow mode plugin: a visual overlay is
-- shown that allows the users to type to filter visible hints. For example,
-- this module is used by the `formfiller` module when selecting a form to add.
--
-- @module select_wm
-- @copyright 2017 Aidan Holm <aidanholm@gmail.com>
local ceil, floor, max = math.ceil, math.floor, math.max
local _M = {}
local ui = ipc_channel("select_wm")
local has_client_rects_api = tonumber(luakit.webkit_version:match("^2%.(%d+)%.")) > 16
-- Label making
-- Calculates the minimum number of characters needed in a hint given a
-- charset of a certain length (I.e. the base)
local function max_hint_len(size, base)
local len = 0
if base == 1 then return size end
while size > 0 do size, len = floor(size / base), len + 1 end
return len
end
-- Reverse a UTF8 string: multibyte sequences are reversed twice
local function utf8_rev (s)
s = s:gsub(utf8.charpattern, function (ch) return #ch > 1 and ch:reverse() end)
return s:reverse()
end
local function charset(seq, size)
local base, digits, labels = utf8.len(seq), {}, {}
for ch in seq:gmatch(utf8.charpattern) do digits[#digits+1] = ch end
local maxlen = max_hint_len(size, base)
for n = 1, size do
local t, i, j, d = {}, 1, n
repeat
d, n = (n % base) + 1, floor(n / base)
rawset(t, i, rawget(digits, d))
i = i + 1
until n == 0
rawset(labels, j, string.rep(digits[1], maxlen-i+1) .. utf8_rev(table.concat(t, "")))
end
return labels
end
-- Different hint label styles
local label_styles = {
charset = function (seq)
assert(type(seq) == "string" and #seq > 0, "invalid sequence")
return function (size) return charset(seq, size) end
end,
numbers = function ()
return function (size) return charset("0123456789", size) end
end,
-- Interleave style
interleave = function (left, right)
assert(type(left) == "string" and type(right) == "string",
"left and right parameters must be strings")
assert(#left > 1 or #right > 1,
"either left or right parameters' length must be greater than 1")
local cmap = {}
for ch in (left..right):gmatch(utf8.charpattern) do
if cmap[ch] then
error("duplicate characters %s in hint strings %s, %s", ch, left, right)
else
cmap[ch] = 1
end
end
return function (size)
local function allstrings(n, t, k, s)
k, s = k or 1, s or {}
if k > n then
coroutine.yield(table.concat(s))
else
for i = 1, #t do
s[k] = t[i]
allstrings(n, t, k+1, s)
end
end
end
local function permute(n, t)
return coroutine.wrap(allstrings), n, t
end
-- calculate the hinting length
local hint_len = 1
while true do
local lo, hi = floor(hint_len/2), ceil(hint_len/2)
if (#left)^lo * (#right)^hi + (#left)^hi * (#right)^lo >= size then break end
hint_len = hint_len + 1
end
local tleft, tright = {}, {}
left:gsub(utf8.charpattern, function(c) table.insert(tleft, c) end)
right:gsub(utf8.charpattern, function(c) table.insert(tright, c) end)
local labels = {}
local lo, hi = floor(hint_len/2), ceil(hint_len/2)
for a in permute(hi, tleft) do
for b in permute(lo, tright) do
rawset(labels, size, a:gsub('()('..utf8.charpattern..')',
function(p, c) return c..b:sub(p, p+#c-1) end))
size = size - 1
if size == 0 then return labels end
end
end
for a in permute(hi, tright) do
for b in permute(lo, tleft) do
rawset(labels, size, a:gsub('()('..utf8.charpattern..')',
function(p, c) return c..b:sub(p, p+#c-1) end))
size = size - 1
if size == 0 then return labels end
end
end
return labels
end
end,
-- Chainable style: sorts labels
sort = function (make_labels)
return function (size)
local labels = make_labels(size)
table.sort(labels)
return labels
end
end,
-- Chainable style: reverses label strings
reverse = function (make_labels)
return function (size)
local labels = make_labels(size)
for i = 1, #labels do
rawset(labels, i, utf8_rev(rawget(labels, i)))
end
return labels
end
end,
trim = function (make_labels)
return function (size)
local labels = make_labels(size)
local P = {}
for _, l in ipairs(labels) do
local p = l:gsub(utf8.charpattern.."$", "")
if #p > 0 then P[p] = (P[p] or 0) + 1 end
end
for p, count in pairs(P) do
if count == 1 then
for i, l in ipairs(labels) do
if l:sub(1, #p) == p then labels[i] = p end
end
end
end
return labels
end
end,
}
-- Default label style
local label_maker
do
local s = label_styles
label_maker = s.trim(s.sort(s.interleave("12345", "67890")))
end
local function bounding_boxes_intersect(a, b)
if a.x + a.w < b.x then return false end
if b.x + b.w < a.x then return false end
if a.y + a.h < b.y then return false end
if b.y + b.h < a.y then return false end
return true
end
local function get_element_bb_if_visible(element, wbb, page)
-- Find the element bounding box
local r
if has_client_rects_api then
r = element:client_rects()
for i=#r,1,-1 do
if r[i].width == 0 or r[i].height == 0 then table.remove(r, i) end
end
if #r == 0 then return nil end
r = r[1]
else
local client_rects = page:wrap_js([=[
var rects = element.getClientRects();
if (rects.length == 0)
return undefined;
var rect = {
"top": rects[0].top,
"bottom": rects[0].bottom,
"left": rects[0].left,
"right": rects[0].right,
};
for (var i = 1; i < rects.length; i++) {
rect.top = Math.min(rect.top, rects[i].top);
rect.bottom = Math.max(rect.bottom, rects[i].bottom);
rect.left = Math.min(rect.left, rects[i].left);
rect.right = Math.max(rect.right, rects[i].right);
}
rect.width = rect.right - rect.left;
rect.height = rect.bottom - rect.top;
return rect;
]=], {"element"})
r = client_rects(element) or element.rect
end
local rbb = {
x = wbb.x + r.left,
y = wbb.y + r.top,
w = r.width,
h = r.height,
}
if rbb.w == 0 or rbb.h == 0 then return nil end
local style = element.style
local display = style.display
local visibility = style.visibility
if display == 'none' or visibility == 'hidden' then return nil end
-- Clip bounding box!
if display == "inline" then
local parent = element.parent
local pd = parent.style.display
if pd == "block" or pd == "inline-block" then
local w = parent.rect.width
w = w - (r.left - parent.rect.left)
if rbb.w > w then rbb.w = w end
end
end
if not bounding_boxes_intersect(wbb, rbb) then return nil end
-- If a link element contains one image, use the image dimensions
if element.tag_name == "A" then
local first = element.first_child
if first and first.tag_name == "IMG" and not first.next_sibling then
return get_element_bb_if_visible(first, wbb, page) or rbb
end
end
return rbb
end
local function frame_find_hints(page, frame, elements)
local hints = {}
if type(elements) == "string" then
elements = frame.body:query(elements)
else
local elems = {}
for _, e in ipairs(elements) do
if e.owner_document == frame.doc then
elems[#elems + 1] = e
end
end
elements = elems
end
-- Find the visible bounding box
local w = frame.doc.window
local wbb = {
x = w.scroll_x,
y = w.scroll_y,
w = w.inner_width,
h = w.inner_height,
}
for _, element in ipairs(elements) do
local rbb = get_element_bb_if_visible(element,wbb, page)
if rbb then
local text = element.text_content
if text == "" then text = element.value or "" end
if text == "" then text = element.attr.placeholder or "" end
hints[#hints+1] = { elem = element, bb = rbb, text = text }
end
end
return hints
end
local function sort_hints_top_left(a, b)
local dtop = a.bb.y - b.bb.y
if dtop ~= 0 then
return dtop < 0
else
return a.bb.x - b.bb.x < 0
end
end
local function make_labels(num)
return label_maker(num)
end
local function find_frames(root_frame)
if not root_frame.body then
return {}
end
local subframes = root_frame.body:query("frame, iframe")
local frames = { root_frame }
-- For each frame/iframe element, recurse
for _, frame in ipairs(subframes) do
local f = { doc = frame.document, body = frame.document.body }
local s = find_frames(f)
for _, sf in ipairs(s) do
frames[#frames + 1] = sf
end
end
return frames
end
local page_states = {}
local function init_frame(frame, stylesheet)
assert(frame.doc)
assert(frame.body)
frame.overlay = frame.doc:create_element("div", { id = "luakit_select_overlay" })
frame.stylesheet = frame.doc:create_element("style", { id = "luakit_select_stylesheet" }, stylesheet)
frame.body.parent:append(frame.overlay)
frame.body.parent:append(frame.stylesheet)
end
local function cleanup_frame(frame)
if frame.overlay then
frame.overlay:remove()
frame.overlay = nil
end
if frame.stylesheet then
frame.stylesheet:remove()
frame.stylesheet = nil
end
end
local function hint_matches(hint, hint_pat, text_pat)
if hint_pat ~= nil and string.find(hint.label, hint_pat) then return true end
if text_pat ~= nil and string.find(hint.text, text_pat) then return true end
return false
end
local function filter(state, hint_pat, text_pat)
state.num_visible_hints = 0
for _, hint in pairs(state.hints) do
local old_hidden = hint.hidden
hint.hidden = not hint_matches(hint, hint_pat, text_pat)
if not hint.hidden then
state.num_visible_hints = state.num_visible_hints + 1
end
if not old_hidden and hint.hidden then
-- Save old style, set new style to "display: none"
hint.overlay_style = hint.overlay_elem.attr.style
hint.label_style = hint.label_elem.attr.style
hint.overlay_elem.attr.style = "display: none;"
hint.label_elem.attr.style = "display: none;"
elseif old_hidden and not hint.hidden then
-- Restore saved style
hint.overlay_elem.attr.style = hint.overlay_style
hint.label_elem.attr.style = hint.label_style
end
end
end
local function focus(state, step)
local last = state.focused
local index
local function sign(n) return n > 0 and 1 or n < 0 and -1 or 0 end
if state.num_visible_hints == 0 then return end
-- Advance index to the first non-hidden item
if step == 0 then
index = last and last or 1
while state.hints[index].hidden do
index = index + 1
if index > #state.hints then index = 1 end
end
if index == last then return end
end
-- Which hint to focus?
if step ~= 0 and last then
index = last
while step ~= 0 do
repeat
index = index + sign(step)
if index < 1 then index = #state.hints end
if index > #state.hints then index = 1 end
until not state.hints[index].hidden
step = step - sign(step)
end
end
local new_hint = state.hints[index]
-- Save and update class for the new hint
new_hint.orig_class = new_hint.overlay_elem.attr.class
new_hint.overlay_elem.attr.class = new_hint.orig_class .. " hint_selected"
-- Restore the original class for the old hint
if last then
local old_hint = state.hints[last]
old_hint.overlay_elem.attr.class = old_hint.orig_class
old_hint.orig_class = nil
end
state.focused = index
return new_hint
end
--- Enter element selection mode on a web page.
--
-- The web page must not already be in element selection mode.
--
-- @tparam page page The web page in which to enter element selection.
-- @tparam string|{dom_element} elements A selector to filter elements, or an array of elements.
-- @tparam string stylesheet The stylesheet to apply.
-- @tparam boolean ignore_case `true` if text case should be ignored.
-- @treturn {...} Table with data for the currently focused hint.
-- @treturn number The number of currently visible hints.
function _M.enter(page, elements, stylesheet, ignore_case)
assert(type(page) == "page")
assert(type(elements) == "string" or type(elements) == "table")
assert(type(stylesheet) == "string")
local page_id = page.id
assert(page_states[page_id] == nil)
local root = page.document
local root_frame = { doc = root, body = root.body }
local state = {}
page_states[page_id] = state
state.frames = find_frames(root_frame)
state.focused = nil
state.hints = {}
state.ignore_case = ignore_case or false
-- Find all hints in the viewport
for _, frame in ipairs(state.frames) do
-- Set up the frame, and find hints
init_frame(frame, stylesheet)
frame.hints = frame_find_hints(page, frame, elements)
-- Build an array of all hints
for _, hint in ipairs(frame.hints) do
state.hints[#state.hints+1] = hint
end
end
-- Sort them by on-screen position, and assign labels
local labels = make_labels(#state.hints)
assert(#state.hints == #labels)
table.sort(state.hints, sort_hints_top_left)
for i, hint in ipairs(state.hints) do
hint.label = labels[i]
end
for _, frame in ipairs(state.frames) do
local fwr = frame.doc.window
local fsx, fsy = fwr.scroll_x, fwr.scroll_y
for _, hint in ipairs(frame.hints) do
-- Append hint elements to overlay
local e = hint.elem
local r = hint.bb
local overlay_style = string.format("left: %dpx; top: %dpx; width: %dpx; height: %dpx;", r.x, r.y, r.w, r.h)
local label_style = string.format("left: %dpx; top: %dpx;", max(r.x-10, fsx), max(r.y-10, fsy), r.w, r.h)
local overlay_class = "hint_overlay hint_overlay_" .. e.tag_name
local label_class = "hint_label hint_label_" .. e.tag_name
hint.overlay_elem = frame.doc:create_element("span", {class = overlay_class, style = overlay_style})
hint.label_elem = frame.doc:create_element("span", {class = label_class, style = label_style}, hint.label)
frame.overlay:append(hint.overlay_elem)
frame.overlay:append(hint.label_elem)
end
end
for _, frame in ipairs(state.frames) do
frame.doc:add_signal("destroy", function ()
cleanup_frame(frame)
end)
end
filter(state, "", "")
return focus(state, 0), state.num_visible_hints
end
--- Leave element selection mode on a web page.
--
-- The web page must be in element selection mode.
--
-- @tparam page|number page The web page (or the web page id) in which to
-- leave element selection.
function _M.leave(page)
if type(page) == "page" then page = page.id end
assert(type(page) == "number")
local state = page_states[page]
if not state then return end
for _, frame in ipairs(state.frames) do
cleanup_frame(frame)
end
page_states[page] = nil
end
--- Update the element selection interface when user selection text changes.
--
-- The web page must be in element selection mode.
--
-- @tparam page page The web page.
-- @tparam string hint_pat The hint pattern filter.
-- @tparam string text_pat The text pattern filter.
-- @tparam string text The full text.
-- @treturn table The currently focused hint.
-- @treturn number The number of currently visible hints.
function _M.changed(page, hint_pat, text_pat, text)
assert(type(page) == "page")
assert(hint_pat == nil or type(hint_pat) == "string")
assert(text_pat == nil or type(text_pat) == "string")
assert(type(text) == "string")
local state = assert(page_states[page.id])
if state.ignore_case then
local convert = function(pat)
if pat == nil then return nil end
local converter = function (ch) return '[' .. string.upper(ch) .. string.lower(ch) .. ']' end
return string.gsub(pat, '(%a)', converter)
end
hint_pat = convert(hint_pat)
text_pat = convert(text_pat)
end
filter(state, hint_pat, text_pat)
return focus(state, 0), state.num_visible_hints
end
--- Update the element selection interface when the user moves the focus.
--
-- The web page must be in element selection mode.
--
-- @usage
--
-- function handle_next (page)
-- select_wm.focus(page, 1)
-- end
-- function handle_prev (page)
-- select_wm.focus(page, -1)
-- end
--
-- @tparam page page The web page.
-- @tparam number step Relative number of tags to shift focus by.
-- @treturn table The currently focused hint.
-- @treturn number The number of currently visible hints.
function _M.focus(page, step)
assert(type(page) == "page")
assert(type(step) == "number")
local state = assert(page_states[page.id])
return focus(state, step), state.num_visible_hints
end
--- Get the current state of element hints on a web page.
--
-- The web page must be in element selection mode.
--
-- @tparam page page The web page.
-- @treturn table The current hint state for `page`.
function _M.hints(page)
assert(type(page) == "page")
local state = assert(page_states[page.id])
return state.hints
end
--- Get the currently focused element hint on a web page.
--
-- The web page must be in element selection mode.
--
-- @tparam page page The web page.
-- @treturn table The currently focused hint.
function _M.focused_hint(page)
assert(type(page) == "page")
local state = assert(page_states[page.id])
return state.hints[state.focused]
end
ui:add_signal("set_label_maker", function (_, _, f)
setfenv(f, label_styles)
label_maker = f(label_styles)
end)
return _M
-- vim: et:sw=4:ts=8:sts=4:tw=80
| gpl-3.0 |
llX8Xll/DEVKEEPER1 | libs/JSON.lua | 3765 | 34843 | -- -*- coding: utf-8 -*-
--
-- Simple JSON encoding and decoding in pure Lua.
--
-- Copyright 2010-2014 Jeffrey Friedl
-- http://regex.info/blog/
--
-- Latest version: http://regex.info/blog/lua/json
--
-- This code is released under a Creative Commons CC-BY "Attribution" License:
-- http://creativecommons.org/licenses/by/3.0/deed.en_US
--
-- It can be used for any purpose so long as the copyright notice above,
-- the web-page links above, and the 'AUTHOR_NOTE' string below are
-- maintained. Enjoy.
--
local VERSION = 20141223.14 -- version history at end of file
local AUTHOR_NOTE = "-[ JSON.lua package by Jeffrey Friedl (http://regex.info/blog/lua/json) version 20141223.14 ]-"
--
-- The 'AUTHOR_NOTE' variable exists so that information about the source
-- of the package is maintained even in compiled versions. It's also
-- included in OBJDEF below mostly to quiet warnings about unused variables.
--
local OBJDEF = {
VERSION = VERSION,
AUTHOR_NOTE = AUTHOR_NOTE,
}
--
-- Simple JSON encoding and decoding in pure Lua.
-- http://www.json.org/
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
--
--
--
-- DECODING (from a JSON string to a Lua table)
--
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local lua_value = JSON:decode(raw_json_text)
--
-- If the JSON text is for an object or an array, e.g.
-- { "what": "books", "count": 3 }
-- or
-- [ "Larry", "Curly", "Moe" ]
--
-- the result is a Lua table, e.g.
-- { what = "books", count = 3 }
-- or
-- { "Larry", "Curly", "Moe" }
--
--
-- The encode and decode routines accept an optional second argument,
-- "etc", which is not used during encoding or decoding, but upon error
-- is passed along to error handlers. It can be of any type (including nil).
--
--
--
-- ERROR HANDLING
--
-- With most errors during decoding, this code calls
--
-- JSON:onDecodeError(message, text, location, etc)
--
-- with a message about the error, and if known, the JSON text being
-- parsed and the byte count where the problem was discovered. You can
-- replace the default JSON:onDecodeError() with your own function.
--
-- The default onDecodeError() merely augments the message with data
-- about the text and the location if known (and if a second 'etc'
-- argument had been provided to decode(), its value is tacked onto the
-- message as well), and then calls JSON.assert(), which itself defaults
-- to Lua's built-in assert(), and can also be overridden.
--
-- For example, in an Adobe Lightroom plugin, you might use something like
--
-- function JSON:onDecodeError(message, text, location, etc)
-- LrErrors.throwUserError("Internal Error: invalid JSON data")
-- end
--
-- or even just
--
-- function JSON.assert(message)
-- LrErrors.throwUserError("Internal Error: " .. message)
-- end
--
-- If JSON:decode() is passed a nil, this is called instead:
--
-- JSON:onDecodeOfNilError(message, nil, nil, etc)
--
-- and if JSON:decode() is passed HTML instead of JSON, this is called:
--
-- JSON:onDecodeOfHTMLError(message, text, nil, etc)
--
-- The use of the fourth 'etc' argument allows stronger coordination
-- between decoding and error reporting, especially when you provide your
-- own error-handling routines. Continuing with the the Adobe Lightroom
-- plugin example:
--
-- function JSON:onDecodeError(message, text, location, etc)
-- local note = "Internal Error: invalid JSON data"
-- if type(etc) = 'table' and etc.photo then
-- note = note .. " while processing for " .. etc.photo:getFormattedMetadata('fileName')
-- end
-- LrErrors.throwUserError(note)
-- end
--
-- :
-- :
--
-- for i, photo in ipairs(photosToProcess) do
-- :
-- :
-- local data = JSON:decode(someJsonText, { photo = photo })
-- :
-- :
-- end
--
--
--
--
--
-- DECODING AND STRICT TYPES
--
-- Because both JSON objects and JSON arrays are converted to Lua tables,
-- it's not normally possible to tell which original JSON type a
-- particular Lua table was derived from, or guarantee decode-encode
-- round-trip equivalency.
--
-- However, if you enable strictTypes, e.g.
--
-- JSON = assert(loadfile "JSON.lua")() --load the routines
-- JSON.strictTypes = true
--
-- then the Lua table resulting from the decoding of a JSON object or
-- JSON array is marked via Lua metatable, so that when re-encoded with
-- JSON:encode() it ends up as the appropriate JSON type.
--
-- (This is not the default because other routines may not work well with
-- tables that have a metatable set, for example, Lightroom API calls.)
--
--
-- ENCODING (from a lua table to a JSON string)
--
-- JSON = assert(loadfile "JSON.lua")() -- one-time load of the routines
--
-- local raw_json_text = JSON:encode(lua_table_or_value)
-- local pretty_json_text = JSON:encode_pretty(lua_table_or_value) -- "pretty printed" version for human readability
-- local custom_pretty = JSON:encode(lua_table_or_value, etc, { pretty = true, indent = "| ", align_keys = false })
--
-- On error during encoding, this code calls:
--
-- JSON:onEncodeError(message, etc)
--
-- which you can override in your local JSON object.
--
-- The 'etc' in the error call is the second argument to encode()
-- and encode_pretty(), or nil if it wasn't provided.
--
--
-- PRETTY-PRINTING
--
-- An optional third argument, a table of options, allows a bit of
-- configuration about how the encoding takes place:
--
-- pretty = JSON:encode(val, etc, {
-- pretty = true, -- if false, no other options matter
-- indent = " ", -- this provides for a three-space indent per nesting level
-- align_keys = false, -- see below
-- })
--
-- encode() and encode_pretty() are identical except that encode_pretty()
-- provides a default options table if none given in the call:
--
-- { pretty = true, align_keys = false, indent = " " }
--
-- For example, if
--
-- JSON:encode(data)
--
-- produces:
--
-- {"city":"Kyoto","climate":{"avg_temp":16,"humidity":"high","snowfall":"minimal"},"country":"Japan","wards":11}
--
-- then
--
-- JSON:encode_pretty(data)
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- The following three lines return identical results:
-- JSON:encode_pretty(data)
-- JSON:encode_pretty(data, nil, { pretty = true, align_keys = false, indent = " " })
-- JSON:encode (data, nil, { pretty = true, align_keys = false, indent = " " })
--
-- An example of setting your own indent string:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = "| " })
--
-- produces:
--
-- {
-- | "city": "Kyoto",
-- | "climate": {
-- | | "avg_temp": 16,
-- | | "humidity": "high",
-- | | "snowfall": "minimal"
-- | },
-- | "country": "Japan",
-- | "wards": 11
-- }
--
-- An example of setting align_keys to true:
--
-- JSON:encode_pretty(data, nil, { pretty = true, indent = " ", align_keys = true })
--
-- produces:
--
-- {
-- "city": "Kyoto",
-- "climate": {
-- "avg_temp": 16,
-- "humidity": "high",
-- "snowfall": "minimal"
-- },
-- "country": "Japan",
-- "wards": 11
-- }
--
-- which I must admit is kinda ugly, sorry. This was the default for
-- encode_pretty() prior to version 20141223.14.
--
--
-- AMBIGUOUS SITUATIONS DURING THE ENCODING
--
-- During the encode, if a Lua table being encoded contains both string
-- and numeric keys, it fits neither JSON's idea of an object, nor its
-- idea of an array. To get around this, when any string key exists (or
-- when non-positive numeric keys exist), numeric keys are converted to
-- strings.
--
-- For example,
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- produces the JSON object
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To prohibit this conversion and instead make it an error condition, set
-- JSON.noKeyConversion = true
--
--
-- SUMMARY OF METHODS YOU CAN OVERRIDE IN YOUR LOCAL LUA JSON OBJECT
--
-- assert
-- onDecodeError
-- onDecodeOfNilError
-- onDecodeOfHTMLError
-- onEncodeError
--
-- If you want to create a separate Lua JSON object with its own error handlers,
-- you can reload JSON.lua or use the :new() method.
--
---------------------------------------------------------------------------
local default_pretty_indent = " "
local default_pretty_options = { pretty = true, align_keys = false, indent = default_pretty_indent }
local isArray = { __tostring = function() return "JSON array" end } isArray.__index = isArray
local isObject = { __tostring = function() return "JSON object" end } isObject.__index = isObject
function OBJDEF:newArray(tbl)
return setmetatable(tbl or {}, isArray)
end
function OBJDEF:newObject(tbl)
return setmetatable(tbl or {}, isObject)
end
local function unicode_codepoint_as_utf8(codepoint)
--
-- codepoint is a number
--
if codepoint <= 127 then
return string.char(codepoint)
elseif codepoint <= 2047 then
--
-- 110yyyxx 10xxxxxx <-- useful notation from http://en.wikipedia.org/wiki/Utf8
--
local highpart = math.floor(codepoint / 0x40)
local lowpart = codepoint - (0x40 * highpart)
return string.char(0xC0 + highpart,
0x80 + lowpart)
elseif codepoint <= 65535 then
--
-- 1110yyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x1000)
local remainder = codepoint - 0x1000 * highpart
local midpart = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midpart
highpart = 0xE0 + highpart
midpart = 0x80 + midpart
lowpart = 0x80 + lowpart
--
-- Check for an invalid character (thanks Andy R. at Adobe).
-- See table 3.7, page 93, in http://www.unicode.org/versions/Unicode5.2.0/ch03.pdf#G28070
--
if ( highpart == 0xE0 and midpart < 0xA0 ) or
( highpart == 0xED and midpart > 0x9F ) or
( highpart == 0xF0 and midpart < 0x90 ) or
( highpart == 0xF4 and midpart > 0x8F )
then
return "?"
else
return string.char(highpart,
midpart,
lowpart)
end
else
--
-- 11110zzz 10zzyyyy 10yyyyxx 10xxxxxx
--
local highpart = math.floor(codepoint / 0x40000)
local remainder = codepoint - 0x40000 * highpart
local midA = math.floor(remainder / 0x1000)
remainder = remainder - 0x1000 * midA
local midB = math.floor(remainder / 0x40)
local lowpart = remainder - 0x40 * midB
return string.char(0xF0 + highpart,
0x80 + midA,
0x80 + midB,
0x80 + lowpart)
end
end
function OBJDEF:onDecodeError(message, text, location, etc)
if text then
if location then
message = string.format("%s at char %d of: %s", message, location, text)
else
message = string.format("%s: %s", message, text)
end
end
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
OBJDEF.onDecodeOfNilError = OBJDEF.onDecodeError
OBJDEF.onDecodeOfHTMLError = OBJDEF.onDecodeError
function OBJDEF:onEncodeError(message, etc)
if etc ~= nil then
message = message .. " (" .. OBJDEF:encode(etc) .. ")"
end
if self.assert then
self.assert(false, message)
else
assert(false, message)
end
end
local function grok_number(self, text, start, etc)
--
-- Grab the integer part
--
local integer_part = text:match('^-?[1-9]%d*', start)
or text:match("^-?0", start)
if not integer_part then
self:onDecodeError("expected number", text, start, etc)
end
local i = start + integer_part:len()
--
-- Grab an optional decimal part
--
local decimal_part = text:match('^%.%d+', i) or ""
i = i + decimal_part:len()
--
-- Grab an optional exponential part
--
local exponent_part = text:match('^[eE][-+]?%d+', i) or ""
i = i + exponent_part:len()
local full_number_text = integer_part .. decimal_part .. exponent_part
local as_number = tonumber(full_number_text)
if not as_number then
self:onDecodeError("bad number", text, start, etc)
end
return as_number, i
end
local function grok_string(self, text, start, etc)
if text:sub(start,start) ~= '"' then
self:onDecodeError("expected string's opening quote", text, start, etc)
end
local i = start + 1 -- +1 to bypass the initial quote
local text_len = text:len()
local VALUE = ""
while i <= text_len do
local c = text:sub(i,i)
if c == '"' then
return VALUE, i + 1
end
if c ~= '\\' then
VALUE = VALUE .. c
i = i + 1
elseif text:match('^\\b', i) then
VALUE = VALUE .. "\b"
i = i + 2
elseif text:match('^\\f', i) then
VALUE = VALUE .. "\f"
i = i + 2
elseif text:match('^\\n', i) then
VALUE = VALUE .. "\n"
i = i + 2
elseif text:match('^\\r', i) then
VALUE = VALUE .. "\r"
i = i + 2
elseif text:match('^\\t', i) then
VALUE = VALUE .. "\t"
i = i + 2
else
local hex = text:match('^\\u([0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if hex then
i = i + 6 -- bypass what we just read
-- We have a Unicode codepoint. It could be standalone, or if in the proper range and
-- followed by another in a specific range, it'll be a two-code surrogate pair.
local codepoint = tonumber(hex, 16)
if codepoint >= 0xD800 and codepoint <= 0xDBFF then
-- it's a hi surrogate... see whether we have a following low
local lo_surrogate = text:match('^\\u([dD][cdefCDEF][0123456789aAbBcCdDeEfF][0123456789aAbBcCdDeEfF])', i)
if lo_surrogate then
i = i + 6 -- bypass the low surrogate we just read
codepoint = 0x2400 + (codepoint - 0xD800) * 0x400 + tonumber(lo_surrogate, 16)
else
-- not a proper low, so we'll just leave the first codepoint as is and spit it out.
end
end
VALUE = VALUE .. unicode_codepoint_as_utf8(codepoint)
else
-- just pass through what's escaped
VALUE = VALUE .. text:match('^\\(.)', i)
i = i + 2
end
end
end
self:onDecodeError("unclosed string", text, start, etc)
end
local function skip_whitespace(text, start)
local _, match_end = text:find("^[ \n\r\t]+", start) -- [http://www.ietf.org/rfc/rfc4627.txt] Section 2
if match_end then
return match_end + 1
else
return start
end
end
local grok_one -- assigned later
local function grok_object(self, text, start, etc)
if text:sub(start,start) ~= '{' then
self:onDecodeError("expected '{'", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '{'
local VALUE = self.strictTypes and self:newObject { } or { }
if text:sub(i,i) == '}' then
return VALUE, i + 1
end
local text_len = text:len()
while i <= text_len do
local key, new_i = grok_string(self, text, i, etc)
i = skip_whitespace(text, new_i)
if text:sub(i, i) ~= ':' then
self:onDecodeError("expected colon", text, i, etc)
end
i = skip_whitespace(text, i + 1)
local new_val, new_i = grok_one(self, text, i)
VALUE[key] = new_val
--
-- Expect now either '}' to end things, or a ',' to allow us to continue.
--
i = skip_whitespace(text, new_i)
local c = text:sub(i,i)
if c == '}' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '}'", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '{'", text, start, etc)
end
local function grok_array(self, text, start, etc)
if text:sub(start,start) ~= '[' then
self:onDecodeError("expected '['", text, start, etc)
end
local i = skip_whitespace(text, start + 1) -- +1 to skip the '['
local VALUE = self.strictTypes and self:newArray { } or { }
if text:sub(i,i) == ']' then
return VALUE, i + 1
end
local VALUE_INDEX = 1
local text_len = text:len()
while i <= text_len do
local val, new_i = grok_one(self, text, i)
-- can't table.insert(VALUE, val) here because it's a no-op if val is nil
VALUE[VALUE_INDEX] = val
VALUE_INDEX = VALUE_INDEX + 1
i = skip_whitespace(text, new_i)
--
-- Expect now either ']' to end things, or a ',' to allow us to continue.
--
local c = text:sub(i,i)
if c == ']' then
return VALUE, i + 1
end
if text:sub(i, i) ~= ',' then
self:onDecodeError("expected comma or '['", text, i, etc)
end
i = skip_whitespace(text, i + 1)
end
self:onDecodeError("unclosed '['", text, start, etc)
end
grok_one = function(self, text, start, etc)
-- Skip any whitespace
start = skip_whitespace(text, start)
if start > text:len() then
self:onDecodeError("unexpected end of string", text, nil, etc)
end
if text:find('^"', start) then
return grok_string(self, text, start, etc)
elseif text:find('^[-0123456789 ]', start) then
return grok_number(self, text, start, etc)
elseif text:find('^%{', start) then
return grok_object(self, text, start, etc)
elseif text:find('^%[', start) then
return grok_array(self, text, start, etc)
elseif text:find('^true', start) then
return true, start + 4
elseif text:find('^false', start) then
return false, start + 5
elseif text:find('^null', start) then
return nil, start + 4
else
self:onDecodeError("can't parse JSON", text, start, etc)
end
end
function OBJDEF:decode(text, etc)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onDecodeError("JSON:decode must be called in method format", nil, nil, etc)
end
if text == nil then
self:onDecodeOfNilError(string.format("nil passed to JSON:decode()"), nil, nil, etc)
elseif type(text) ~= 'string' then
self:onDecodeError(string.format("expected string argument to JSON:decode(), got %s", type(text)), nil, nil, etc)
end
if text:match('^%s*$') then
return nil
end
if text:match('^%s*<') then
-- Can't be JSON... we'll assume it's HTML
self:onDecodeOfHTMLError(string.format("html passed to JSON:decode()"), text, nil, etc)
end
--
-- Ensure that it's not UTF-32 or UTF-16.
-- Those are perfectly valid encodings for JSON (as per RFC 4627 section 3),
-- but this package can't handle them.
--
if text:sub(1,1):byte() == 0 or (text:len() >= 2 and text:sub(2,2):byte() == 0) then
self:onDecodeError("JSON package groks only UTF-8, sorry", text, nil, etc)
end
local success, value = pcall(grok_one, self, text, 1, etc)
if success then
return value
else
-- if JSON:onDecodeError() didn't abort out of the pcall, we'll have received the error message here as "value", so pass it along as an assert.
if self.assert then
self.assert(false, value)
else
assert(false, value)
end
-- and if we're still here, return a nil and throw the error message on as a second arg
return nil, value
end
end
local function backslash_replacement_function(c)
if c == "\n" then
return "\\n"
elseif c == "\r" then
return "\\r"
elseif c == "\t" then
return "\\t"
elseif c == "\b" then
return "\\b"
elseif c == "\f" then
return "\\f"
elseif c == '"' then
return '\\"'
elseif c == '\\' then
return '\\\\'
else
return string.format("\\u%04x", c:byte())
end
end
local chars_to_be_escaped_in_JSON_string
= '['
.. '"' -- class sub-pattern to match a double quote
.. '%\\' -- class sub-pattern to match a backslash
.. '%z' -- class sub-pattern to match a null
.. '\001' .. '-' .. '\031' -- class sub-pattern to match control characters
.. ']'
local function json_string_literal(value)
local newval = value:gsub(chars_to_be_escaped_in_JSON_string, backslash_replacement_function)
return '"' .. newval .. '"'
end
local function object_or_array(self, T, etc)
--
-- We need to inspect all the keys... if there are any strings, we'll convert to a JSON
-- object. If there are only numbers, it's a JSON array.
--
-- If we'll be converting to a JSON object, we'll want to sort the keys so that the
-- end result is deterministic.
--
local string_keys = { }
local number_keys = { }
local number_keys_must_be_strings = false
local maximum_number_key
for key in pairs(T) do
if type(key) == 'string' then
table.insert(string_keys, key)
elseif type(key) == 'number' then
table.insert(number_keys, key)
if key <= 0 or key >= math.huge then
number_keys_must_be_strings = true
elseif not maximum_number_key or key > maximum_number_key then
maximum_number_key = key
end
else
self:onEncodeError("can't encode table with a key of type " .. type(key), etc)
end
end
if #string_keys == 0 and not number_keys_must_be_strings then
--
-- An empty table, or a numeric-only array
--
if #number_keys > 0 then
return nil, maximum_number_key -- an array
elseif tostring(T) == "JSON array" then
return nil
elseif tostring(T) == "JSON object" then
return { }
else
-- have to guess, so we'll pick array, since empty arrays are likely more common than empty objects
return nil
end
end
table.sort(string_keys)
local map
if #number_keys > 0 then
--
-- If we're here then we have either mixed string/number keys, or numbers inappropriate for a JSON array
-- It's not ideal, but we'll turn the numbers into strings so that we can at least create a JSON object.
--
if self.noKeyConversion then
self:onEncodeError("a table with both numeric and string keys could be an object or array; aborting", etc)
end
--
-- Have to make a shallow copy of the source table so we can remap the numeric keys to be strings
--
map = { }
for key, val in pairs(T) do
map[key] = val
end
table.sort(number_keys)
--
-- Throw numeric keys in there as strings
--
for _, number_key in ipairs(number_keys) do
local string_key = tostring(number_key)
if map[string_key] == nil then
table.insert(string_keys , string_key)
map[string_key] = T[number_key]
else
self:onEncodeError("conflict converting table with mixed-type keys into a JSON object: key " .. number_key .. " exists both as a string and a number.", etc)
end
end
end
return string_keys, nil, map
end
--
-- Encode
--
-- 'options' is nil, or a table with possible keys:
-- pretty -- if true, return a pretty-printed version
-- indent -- a string (usually of spaces) used to indent each nested level
-- align_keys -- if true, align all the keys when formatting a table
--
local encode_value -- must predeclare because it calls itself
function encode_value(self, value, parents, etc, options, indent)
if value == nil then
return 'null'
elseif type(value) == 'string' then
return json_string_literal(value)
elseif type(value) == 'number' then
if value ~= value then
--
-- NaN (Not a Number).
-- JSON has no NaN, so we have to fudge the best we can. This should really be a package option.
--
return "null"
elseif value >= math.huge then
--
-- Positive infinity. JSON has no INF, so we have to fudge the best we can. This should
-- really be a package option. Note: at least with some implementations, positive infinity
-- is both ">= math.huge" and "<= -math.huge", which makes no sense but that's how it is.
-- Negative infinity is properly "<= -math.huge". So, we must be sure to check the ">="
-- case first.
--
return "1e+9999"
elseif value <= -math.huge then
--
-- Negative infinity.
-- JSON has no INF, so we have to fudge the best we can. This should really be a package option.
--
return "-1e+9999"
else
return tostring(value)
end
elseif type(value) == 'boolean' then
return tostring(value)
elseif type(value) ~= 'table' then
self:onEncodeError("can't convert " .. type(value) .. " to JSON", etc)
else
--
-- A table to be converted to either a JSON object or array.
--
local T = value
if type(options) ~= 'table' then
options = {}
end
if type(indent) ~= 'string' then
indent = ""
end
if parents[T] then
self:onEncodeError("table " .. tostring(T) .. " is a child of itself", etc)
else
parents[T] = true
end
local result_value
local object_keys, maximum_number_key, map = object_or_array(self, T, etc)
if maximum_number_key then
--
-- An array...
--
local ITEMS = { }
for i = 1, maximum_number_key do
table.insert(ITEMS, encode_value(self, T[i], parents, etc, options, indent))
end
if options.pretty then
result_value = "[ " .. table.concat(ITEMS, ", ") .. " ]"
else
result_value = "[" .. table.concat(ITEMS, ",") .. "]"
end
elseif object_keys then
--
-- An object
--
local TT = map or T
if options.pretty then
local KEYS = { }
local max_key_length = 0
for _, key in ipairs(object_keys) do
local encoded = encode_value(self, tostring(key), parents, etc, options, indent)
if options.align_keys then
max_key_length = math.max(max_key_length, #encoded)
end
table.insert(KEYS, encoded)
end
local key_indent = indent .. tostring(options.indent or "")
local subtable_indent = key_indent .. string.rep(" ", max_key_length) .. (options.align_keys and " " or "")
local FORMAT = "%s%" .. string.format("%d", max_key_length) .. "s: %s"
local COMBINED_PARTS = { }
for i, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, subtable_indent)
table.insert(COMBINED_PARTS, string.format(FORMAT, key_indent, KEYS[i], encoded_val))
end
result_value = "{\n" .. table.concat(COMBINED_PARTS, ",\n") .. "\n" .. indent .. "}"
else
local PARTS = { }
for _, key in ipairs(object_keys) do
local encoded_val = encode_value(self, TT[key], parents, etc, options, indent)
local encoded_key = encode_value(self, tostring(key), parents, etc, options, indent)
table.insert(PARTS, string.format("%s:%s", encoded_key, encoded_val))
end
result_value = "{" .. table.concat(PARTS, ",") .. "}"
end
else
--
-- An empty array/object... we'll treat it as an array, though it should really be an option
--
result_value = "[]"
end
parents[T] = false
return result_value
end
end
function OBJDEF:encode(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or nil)
end
function OBJDEF:encode_pretty(value, etc, options)
if type(self) ~= 'table' or self.__index ~= OBJDEF then
OBJDEF:onEncodeError("JSON:encode_pretty must be called in method format", etc)
end
return encode_value(self, value, {}, etc, options or default_pretty_options)
end
function OBJDEF.__tostring()
return "JSON encode/decode package"
end
OBJDEF.__index = OBJDEF
function OBJDEF:new(args)
local new = { }
if args then
for key, val in pairs(args) do
new[key] = val
end
end
return setmetatable(new, OBJDEF)
end
return OBJDEF:new()
--
-- Version history:
--
-- 20141223.14 The encode_pretty() routine produced fine results for small datasets, but isn't really
-- appropriate for anything large, so with help from Alex Aulbach I've made the encode routines
-- more flexible, and changed the default encode_pretty() to be more generally useful.
--
-- Added a third 'options' argument to the encode() and encode_pretty() routines, to control
-- how the encoding takes place.
--
-- Updated docs to add assert() call to the loadfile() line, just as good practice so that
-- if there is a problem loading JSON.lua, the appropriate error message will percolate up.
--
-- 20140920.13 Put back (in a way that doesn't cause warnings about unused variables) the author string,
-- so that the source of the package, and its version number, are visible in compiled copies.
--
-- 20140911.12 Minor lua cleanup.
-- Fixed internal reference to 'JSON.noKeyConversion' to reference 'self' instead of 'JSON'.
-- (Thanks to SmugMug's David Parry for these.)
--
-- 20140418.11 JSON nulls embedded within an array were being ignored, such that
-- ["1",null,null,null,null,null,"seven"],
-- would return
-- {1,"seven"}
-- It's now fixed to properly return
-- {1, nil, nil, nil, nil, nil, "seven"}
-- Thanks to "haddock" for catching the error.
--
-- 20140116.10 The user's JSON.assert() wasn't always being used. Thanks to "blue" for the heads up.
--
-- 20131118.9 Update for Lua 5.3... it seems that tostring(2/1) produces "2.0" instead of "2",
-- and this caused some problems.
--
-- 20131031.8 Unified the code for encode() and encode_pretty(); they had been stupidly separate,
-- and had of course diverged (encode_pretty didn't get the fixes that encode got, so
-- sometimes produced incorrect results; thanks to Mattie for the heads up).
--
-- Handle encoding tables with non-positive numeric keys (unlikely, but possible).
--
-- If a table has both numeric and string keys, or its numeric keys are inappropriate
-- (such as being non-positive or infinite), the numeric keys are turned into
-- string keys appropriate for a JSON object. So, as before,
-- JSON:encode({ "one", "two", "three" })
-- produces the array
-- ["one","two","three"]
-- but now something with mixed key types like
-- JSON:encode({ "one", "two", "three", SOMESTRING = "some string" }))
-- instead of throwing an error produces an object:
-- {"1":"one","2":"two","3":"three","SOMESTRING":"some string"}
--
-- To maintain the prior throw-an-error semantics, set
-- JSON.noKeyConversion = true
--
-- 20131004.7 Release under a Creative Commons CC-BY license, which I should have done from day one, sorry.
--
-- 20130120.6 Comment update: added a link to the specific page on my blog where this code can
-- be found, so that folks who come across the code outside of my blog can find updates
-- more easily.
--
-- 20111207.5 Added support for the 'etc' arguments, for better error reporting.
--
-- 20110731.4 More feedback from David Kolf on how to make the tests for Nan/Infinity system independent.
--
-- 20110730.3 Incorporated feedback from David Kolf at http://lua-users.org/wiki/JsonModules:
--
-- * When encoding lua for JSON, Sparse numeric arrays are now handled by
-- spitting out full arrays, such that
-- JSON:encode({"one", "two", [10] = "ten"})
-- returns
-- ["one","two",null,null,null,null,null,null,null,"ten"]
--
-- In 20100810.2 and earlier, only up to the first non-null value would have been retained.
--
-- * When encoding lua for JSON, numeric value NaN gets spit out as null, and infinity as "1+e9999".
-- Version 20100810.2 and earlier created invalid JSON in both cases.
--
-- * Unicode surrogate pairs are now detected when decoding JSON.
--
-- 20100810.2 added some checking to ensure that an invalid Unicode character couldn't leak in to the UTF-8 encoding
--
-- 20100731.1 initial public release
--
| gpl-2.0 |
madpilot78/ntopng | scripts/lua/rest/v1/get/host/l7/stats.lua | 2 | 1965 | --
-- (C) 2013-21 - ntop.org
--
local dirs = ntop.getDirs()
package.path = dirs.installdir .. "/scripts/lua/modules/?.lua;" .. package.path
require "lua_utils"
local rest_utils = require("rest_utils")
local stats_utils = require("stats_utils")
--
-- Read statistics about nDPI application protocols for a hsot
-- Example: curl -u admin:admin -H "Content-Type: application/json" -d '{"ifid": "1", "host": "192.168.1.1"}' http://localhost:3000/lua/rest/v1/get/host/l7/stats.lua
--
-- NOTE: in case of invalid login, no error is returned but redirected to login
--
local rc = rest_utils.consts.success.ok
local res = {}
local ifid = _GET["ifid"]
local host_info = url2hostinfo(_GET)
local breed = _GET["breed"]
local ndpi_category = _GET["ndpi_category"]
if isEmptyString(ifid) then
rc = rest_utils.consts.err.invalid_interface
rest_utils.answer(rc)
return
end
local show_breed = false
if breed == "true" then
show_breed = true
end
local show_ndpi_category = false
if ndpi_category == "true" then
show_ndpi_category = true
end
interface.select(ifid)
local ndpi_protos = interface.getnDPIProtocols()
local function getAppUrl(app)
if ndpi_protos[app] ~= nil then
return ntop.getHttpPrefix().."/lua/flows_stats.lua?application="..app
end
return nil
end
local tot = 0
local stats = interface.getHostInfo(host_info["host"], host_info["vlan"])
if stats == nil then
rest_utils.answer(rest_utils.consts.err.not_found)
return
end
tot = stats["bytes.sent"] + stats["bytes.rcvd"]
local _ifstats = computeL7Stats(stats, show_breed, show_ndpi_category)
for key, value in pairsByValues(_ifstats, rev) do
local duration = 0
if(stats["ndpi"][key] ~= nil) then
duration = stats["ndpi"][key]["duration"]
end
res[#res + 1] = {
label = key,
value = value,
duration = duration,
}
end
local collapsed = stats_utils.collapse_stats(res, 1, 3 --[[ threshold ]])
rest_utils.answer(rc, collapsed)
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/Code/NplCad/NplCadDef/NplCadDef_Data.lua | 1 | 12592 | --[[
Title: NplCadDef_Data
Author(s): leio
Date: 2018/9/10
Desc:
use the lib:
-------------------------------------------------------
NPL.load("(gl)script/apps/Aries/Creator/Game/Code/NplCad/NplCadDef/NplCadDef_Data.lua");
local NplCadDef_Data = commonlib.gettable("MyCompany.Aries.Game.Code.NplCad.NplCadDef_Data");
-------------------------------------------------------
]]
local NplCadDef_Data = commonlib.gettable("MyCompany.Aries.Game.Code.NplCad.NplCadDef_Data");
local cmds = {
{
type = "getLocalVariable",
message0 = L"%1",
arg0 = {
{
name = "var",
type = "field_input",
text = L"变量名",
},
},
output = {type = "null",},
category = "Data",
helpUrl = "",
canRun = false,
colourSecondary = "#ffffff",
func_description = '%s',
func_description_js = '%s',
ToNPL = function(self)
return self:getFieldAsString('var');
end,
examples = {{desc = "", canRun = true, code = [[
local key = "value"
say(key, 1)
]]}},
},
{
type = "createLocalVariable",
message0 = L"新建本地%1为%2",
arg0 = {
{
name = "var",
type = "field_input",
text = L"变量名",
},
{
name = "value",
type = "input_value",
shadow = { type = "functionParams", value = "0",},
text = "0",
},
},
category = "Data",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'local %s = %s',
func_description_js = 'var %s = %s',
ToNPL = function(self)
return 'local key = "value"\n';
end,
examples = {{desc = "", canRun = true, code = [[
local key = "value"
say(key, 1)
]]}},
},
{
type = "assign",
message0 = L"%1赋值为%2",
arg0 = {
{
name = "left",
type = "input_value",
shadow = { type = "getLocalVariable", value = L"变量名",},
text = L"变量名",
},
{
name = "right",
type = "input_value",
shadow = { type = "functionParams", value = "1",},
text = "1",
},
},
category = "Data",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = '%s = %s',
func_description_js = '%s = %s',
ToNPL = function(self)
return 'key = "value"\n';
end,
examples = {{desc = "", canRun = true, code = [[
text = "hello"
say(text, 1)
]]}},
},
{
type = "getString",
message0 = "\"%1\"",
arg0 = {
{
name = "left",
type = "field_input",
text = "string",
},
},
output = {type = "null",},
category = "Data",
helpUrl = "",
canRun = false,
func_description = '"%s"',
func_description_js = '"%s"',
ToNPL = function(self)
return string.format('"%s"', self:getFieldAsString('left'));
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
{
type = "getBoolean",
message0 = L"%1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{ "true", "true" },
{ "false", "false" },
{ "nil", "nil" },
}
},
},
output = {type = "field_number",},
category = "Data",
helpUrl = "",
canRun = false,
func_description = '%s',
func_description_js = '%s',
ToNPL = function(self)
return self:getFieldAsString("value");
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
{
type = "getNumber",
message0 = L"%1",
arg0 = {
{
name = "left",
type = "field_number",
text = "0",
},
},
output = {type = "field_number",},
category = "Data",
helpUrl = "",
canRun = false,
func_description = '%s',
func_description_js = '%s',
ToNPL = function(self)
return string.format('%s', self:getFieldAsString('left'));
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
{
type = "newEmptyTable",
message0 = L"{%1%2%3}",
arg0 = {
{
name = "start_dummy",
type = "input_dummy",
},
{
name = "end_dummy",
type = "input_dummy",
},
{
name = "btn",
type = "field_button",
content = {
src = "png/plus-2x.png"
},
width = 16,
height = 16,
callback = "FIELD_BUTTON_CALLBACK_append_mcml_attr"
},
},
output = {type = "field_number",},
category = "Data",
helpUrl = "",
canRun = false,
func_description_lua_provider = [[
var attrs = Blockly.Extensions.readTextFromMcmlAttrs(block, "Lua", ",");
if (attrs) {
return ["{%s}".format(attrs), Blockly.Lua.ORDER_ATOMIC];
}else{
return ["{}", Blockly.Lua.ORDER_ATOMIC];
}
]],
ToNPL = function(self)
return "{}";
end,
examples = {{desc = "", canRun = true, code = [[
local t = {}
t[1] = "hello"
t["age"] = 10;
log(t)
]]}},
},
{
type = "getTableValue",
message0 = L"%1中的%2",
arg0 = {
{
name = "table",
type = "input_value",
shadow = { type = "functionParams", value = "_G",},
text = "_G",
},
{
name = "key",
type = "input_value",
shadow = { type = "text", value = "key",},
text = "key",
},
},
output = {type = "field_number",},
category = "Data",
helpUrl = "",
canRun = false,
func_description = '%s[%s]',
ToNPL = function(self)
return string.format('%s["%s"]', self:getFieldAsString('table'), self:getFieldAsString('key'));
end,
examples = {{desc = "", canRun = true, code = [[
local t = {}
t[1] = "hello"
t["age"] = 10;
log(t)
]]}},
},
{
type = "defineFunction",
message0 = L"定义函数%1(%2)",
message1 = L"%1",
arg0 = {
{
name = "name",
type = "field_input",
text = "",
},
{
name = "param",
type = "field_input",
text = "",
},
},
arg1 = {
{
name = "input",
type = "input_statement",
text = "",
},
},
previousStatement = true,
nextStatement = true,
hide_in_codewindow = true,
category = "Data",
helpUrl = "",
canRun = false,
func_description = 'function %s(%s)\\n%send',
ToPython = function(self)
local input = self:getFieldAsString('input')
if input == '' then
input = 'pass'
end
return string.format('def %s(%s):\n %s\n', self:getFieldAsString('name'), self:getFieldAsString('param'), input);
end,
ToNPL = function(self)
return string.format('function %s(%s)\n %s\nend\n', self:getFieldAsString('name'), self:getFieldAsString('param'), self:getFieldAsString('input'));
end,
examples = {{desc = "", canRun = true, code = [[
function intersected()
pushNode("union","intersected",'#ffc658',true)
sphere("union",1,'#ffc658')
cube("intersection",1.5,'#ffc658')
popNode()
end
function holes()
pushNode("difference","holes",'#ffc658',true)
cylinder("union",0.5,2,'#ffc658')
cylinder("union",0.5,2,'#ffc658')
rotate('x',90)
cylinder("union",0.5,2,'#ffc658')
rotate('z',90)
popNode()
end
pushNode("union","object0",'#ffc658',true)
intersected("")
holes("")
popNode()
]]}},
},
{
type = "functionParams",
message0 = "%1",
arg0 = {
{
name = "value",
type = "field_input",
text = ""
},
},
hide_in_toolbox = true,
category = "Data",
output = {type = "null",},
helpUrl = "",
canRun = false,
func_description = '%s',
colourSecondary = "#ffffff",
ToNPL = function(self)
return self:getFieldAsString('value');
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
{
type = "callFunction",
message0 = L"调用函数%1(%2)",
arg0 = {
{
name = "name",
type = "field_input",
text = "log",
},
{
name = "param",
type = "input_value",
shadow = { type = "functionParams", value = "param",},
text = "",
},
},
previousStatement = true,
nextStatement = true,
category = "Data",
helpUrl = "",
canRun = false,
func_description = '%s(%s)',
ToNPL = function(self)
return string.format('%s(%s)\n', self:getFieldAsString('name'), self:getFieldAsString('param'));
end,
examples = {{desc = "", canRun = true, code = [[
function f(x)
return 0.5 * x
end
function g(x)
return {x, f(x) * f(x), 0}
end
for a = -10, 10, 2 do
cube("union",1,"#ffc658")
move(a,f(a),0)
end
for a = -10, 10, 1 do
sphere("union",0.5,"#ffc658")
local t = g(a)
move(t[1], t[2], t[3])
end
]]}},
},
{
type = "code_block",
message0 = L"代码%1",
message1 = L"%1",
arg0 = {
{
name = "label_dummy",
type = "input_dummy",
text = "",
},
},
arg1 = {
{
name = "codes",
type = "field_input",
text = "",
},
},
hide_in_toolbox = true,
category = "Data",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = '%s',
func_description_js = '%s',
ToNPL = function(self)
return string.format('%s\n', self:getFieldAsString('codes'));
end,
examples = {{desc = L"", canRun = true, code = [[
]]}},
},
{
type = "code_comment",
message0 = L"-- %1",
arg0 = {
{
name = "value",
type = "field_input",
text = "",
},
},
category = "Data",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = '-- %s',
func_description_js = '// %s',
ToNPL = function(self)
return string.format('-- %s', self:getFieldAsString('value'));
end,
examples = {{desc = L"", canRun = true, code = [[
]]}},
},
{
type = "code_comment_full",
message0 = L"注释全部 %1",
message1 = "%1",
message2 = "%1",
arg0 = {
{
name = "label_dummy",
type = "input_dummy",
text = "",
},
},
arg1 = {
{
name = "input",
type = "input_statement",
text = "",
},
},
arg2 = {
{
name = "label_dummy",
type = "input_dummy",
text = "",
},
},
category = "Data",
helpUrl = "",
canRun = false,
hide_in_toolbox = true,
previousStatement = true,
nextStatement = true,
func_description = '--[[\\n%s\\n]]',
func_description_js = '/**\\n%s\\n*/',
ToPython = function(self)
return string.format('"""\n%s\n"""', self:getFieldAsString('input'));
end,
ToNPL = function(self)
return string.format('--[[\n%s\n]]', self:getFieldAsString('input'));
end,
examples = {{desc = L"", canRun = true, code = [[
]]}},
},
{
type = "data_variable",
message0 = L"%1",
lastDummyAlign0 = "CENTRE",
arg0 = {
{
name = "VARIABLE",
type = "field_variable_getter",
text = "i",
variableType = "",
},
},
colour = "#ff8c1a",
hide_in_toolbox = true,
checkboxInFlyout = false,
output = {type = "null",},
category = "Data",
helpUrl = "",
canRun = false,
func_description = '"%s"',
func_description_js = '"%s"',
ToNPL = function(self)
return string.format('"%s"', self:getFieldAsString('VARIABLE'));
end,
examples = {{desc = L"", canRun = true, code = [[
]]}},
},
{
type = "print3d",
message0 = L"打印 %1",
arg0 = {
{
name = "value",
type = "field_dropdown",
options = {
{ L"需要", "true" },
{ L"不需要", "false" },
},
},
},
hide_in_toolbox = true,
category = "Data",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'print3d(%s)',
func_description_js = 'print3d(%s)',
ToNPL = function(self)
return string.format('print3d(%s)',
self:getFieldValue('value')
);
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
{
type = "setMaxTrianglesCnt",
message0 = L"模型三角形最大数量: %1",
arg0 = {
{
name = "value",
type = "field_number",
text = "-1",
},
},
category = "Data",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'setMaxTrianglesCnt(%s)',
ToNPL = function(self)
return string.format('setMaxTrianglesCnt(%s)', self:getFieldAsString('value'));
end,
examples = {{desc = "", canRun = true, code = [[
]]}},
},
{
type = "jsonToObj",
message0 = L"转换Json字符串 %1 为Lua Table",
arg0 = {
{
name = "value",
type = "field_input",
text = "",
},
},
category = "Data",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'jsonToObj("%s")',
func_description_js = 'jsonToObj("%s")',
ToNPL = function(self)
return string.format('jsonToObj("%s")', self:getFieldAsString('value'));
end,
examples = {{desc = L"", canRun = true, code = [[
]]}},
},
{
type = "objToJson",
message0 = L"转换 %1 为Json字符串",
arg0 = {
{
name = "value",
type = "field_input",
text = "",
},
},
category = "Data",
helpUrl = "",
canRun = false,
previousStatement = true,
nextStatement = true,
func_description = 'objToJson(%s)',
func_description_js = 'objToJson(%s)',
ToNPL = function(self)
return string.format('objToJson(%s)', self:getFieldAsString('value'));
end,
examples = {{desc = L"", canRun = true, code = [[
]]}},
},
};
function NplCadDef_Data.GetCmds()
return cmds;
end
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/zones/Bastok_Mines/npcs/Davyad.lua | 1 | 1200 | -----------------------------------
-- Area: Bastok Mines
-- NPC: Davyad
-- Standard Info NPC
-- Involved in Mission: Bastok 3-2
-----------------------------------
require("scripts/globals/missions");
package.loaded["scripts/zones/Bastok_Mines/TextIDs"] = nil;
require("scripts/zones/Bastok_Mines/TextIDs");
-----------------------------------
-- onTrade Action
-----------------------------------
function onTrade(player,npc,trade)
end;
-----------------------------------
-- onTrigger Action
-----------------------------------
function onTrigger(player,npc)
activeMission = player:hasCurrentMission(BASTOK,TO_THE_FORSAKEN_MINES);
if (activeMission == false) then
player:startEvent(0x0036);
else
player:startEvent(0x0035);
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 |
pakoito/ToME---t-engine4 | game/modules/tome/data/zones/temple-of-creation/objects.lua | 3 | 4176 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
load("/data/general/objects/2htridents.lua", function(e) e.rarity = e.trident_rarity end)
load("/data/general/objects/objects-far-east.lua")
local Talents = require "engine.interface.ActorTalents"
local Stats = require "engine.interface.ActorStats"
local DamageType = require "engine.DamageType"
newEntity{ base = "BASE_LITE",
power_source = {arcane=true},
define_as = "ELDRITCH_PEARL",
unided_name = "bright pearl",
name = "Eldritch Pearl", unique=true, image = "object/artifact/eldritch_pearl.png",
display ='*', color = colors.AQUAMARINE,
desc = [[Thousands of years spent inside the temple of creation have infused this pearl with the fury of rushing water. It pulses light.]],
-- No cost, it's invaluable
wielder = {
lite = 6,
can_breath = {water=1},
combat_dam = 12,
combat_spellpower = 12,
inc_stats = {
[Stats.STAT_STR] = 4,
[Stats.STAT_DEX] = 4,
[Stats.STAT_MAG] = 4,
[Stats.STAT_WIL] = 4,
[Stats.STAT_CUN] = 4,
[Stats.STAT_CON] = 4,
[Stats.STAT_LCK] = -5,
},
},
max_power = 150, power_regen = 1,
use_talent = { id = Talents.T_TIDAL_WAVE, level=4, power = 80 },
}
for i = 1, 3 do
newEntity{ base = "BASE_LORE",
define_as = "NOTE"..i,
name = "tract", lore="temple-creation-note-"..i,
desc = [[A tract revealing the history of the Nagas.]],
rarity = false,
encumberance = 0,
}
end
newEntity{ base = "BASE_LORE",
define_as = "SLASUL_NOTE",
name = "note", lore="temple-creation-note-4",
desc = [[A note.]],
rarity = false,
encumberance = 0,
}
newEntity{ base = "BASE_TRIDENT",
power_source = {nature=true, psionic=true},
define_as = "LEGACY_NALOREN",
unided_name = "ornate orichalcum trident",
name = "Legacy of the Naloren", unique=true, image = "object/artifact/trident_of_the_tides.png",
desc = [[This incredibly beautiful -- and powerful -- trident is made of the rare metal orichalcum. An amazing pearl is seated in head of the trident, as it spreads into three razor sharp prongs.
It is imbued with the greatest strengths of all of the most powerful Naga warriors.
Slasul gave it to you as a sign of his faith in you. It is a sign of hope for all of the Naloren race, that one outside of their tribe could be so trusted.]],
require = { stat = { str=35 }, },
level_range = {40, 50},
rarity = false,
cost = 350,
material_level = 5,
plot = true,
combat = {
dam = 84,
apr = 20,
physcrit = 20,
dammod = {str=1.4},
damrange = 1.4,
talent_on_hit = { T_STUNNING_BLOW = {level=1, chance=10}, T_SILENCE = {level=3, chance=10}, T_SPIT_POISON = {level=5, chance=10} }
},
wielder = {
lite = 2,
combat_dam = 12,
combat_mindpower = 12,
combat_mindcrit = 12,
inc_stats = {
[Stats.STAT_STR] = 4,
[Stats.STAT_DEX] = 4,
[Stats.STAT_MAG] = 4,
[Stats.STAT_WIL] = 4,
[Stats.STAT_CUN] = 4,
[Stats.STAT_CON] = 4,
[Stats.STAT_LCK] = 10,
},
resists = {
[DamageType.COLD] = 15,
[DamageType.NATURE] = 20,
[DamageType.ACID] = 10,
},
inc_damage = {
[DamageType.COLD] = 15,
[DamageType.NATURE] = 25,
[DamageType.MIND] = 10,
},
talent_cd_reduction={
[Talents.T_RUSH]=3,
[Talents.T_SPIT_POISON]=2,
},
talents_types_mastery = {
["technique/combat-training"] = 0.3,
["technique/combat-techniques-active"] = 0.3,
["psionic/psychic-assault"] = 0.3,
},
},
max_power = 60, power_regen = 1,
use_talent = { id = Talents.T_IMPLODE, level=2, power = 40 },
}
| gpl-3.0 |
RyMarq/Zero-K | LuaRules/Configs/StartBoxes/Blindside_v2.lua | 7 | 2698 | local suported_playercounts = {5, 11, 16}
--[[ The 16 startpoints form a planar graph where each vertex is a 3-mex startpoint and has 3 edges, which
are veh-pathable passages to other vertices with 2 mexes in between. The lack of connection means there
are mountains in between (there are some mexes and geospots in the mountains but they are standalone).
5 of the vertices are landlocked but also have a geospot. The remanining 11 vertices are all on the coast
so have water access but no geo. Each of the 11 has exactly one connection to one of the 5, but not vice
versa (there's two connections between geo pairs and one standalone spot with 3 connections to the shore).
The "3 connections each" rule could probably be used to construct a lot of mostly-fair distributions
for other player counts but I don't have the mana to do that so only did the obvious geo-related ones. ]]
local potential_starts = { -- x, z, hasGeoButIsLandlocked, connectedVertices (geo)
[ 1] = { 1628, 3881, false, { 2 , ( 3), 4 }},
[ 2] = { 3300, 1179, false, { 1 , ( 3), 5 }},
[ 3] = { 3853, 3498, true, { 1 , 2 , ( 6) }},
[ 4] = { 3420, 6195, false, { 1 , ( 6), 7 }},
[ 5] = { 5861, 1299, false, { 2 , ( 6), 8 }},
[ 6] = { 5983, 4260, true, {( 3), 4 , 5 }},
[ 7] = { 6448, 6681, false, { 4 , ( 9), 10 }},
[ 8] = { 9085, 1259, false, { 5 , (11), 13 }},
[ 9] = { 8387, 4180, true, { 7 , 10 , (11) }},
[10] = { 9000, 6533, false, { 7 , ( 9), 12 }},
[11] = {10710, 3457, true, { 8 , ( 9), 12 }},
[12] = {10926, 6131, false, { 10 , (11), 15 }},
[13] = {12784, 1325, false, { 8 , (14), 16 }},
[14] = {12742, 4092, true, { 13 , 15 , 16 }}, -- not connected to any geo, though has one itself
[15] = {13729, 6509, false, { 12 , (14), 16 }},
[16] = {14914, 2751, false, { 13 , (14), 15 }},
}
local starts
local N = Spring.Utilities.GetTeamCount()
if N <= 5 then
-- just the geospot starts
starts = {}
for i = 1, #potential_starts do
local p = potential_starts[i]
if p[3] then
starts[#starts + 1] = p
end
end
elseif N <= 11 then
-- just the non-geospot starts
starts = {}
for i = 1, #potential_starts do
local p = potential_starts[i]
if not p[3] then
starts[#starts + 1] = p
end
end
else
starts = potential_starts
end
-- convert the above to boxes (256 radius circles)
local ret = {}
for i = 1, #starts do
ret[i-1] = {
startpoints = { { starts[i][1], starts[i][2] } },
boxes = { { } },
}
for j = 1, 16 do
ret[i-1].boxes[1][j] = {
starts[i][1] + 256 * math.sin(j * math.pi / 8),
starts[i][2] + 256 * math.cos(j * math.pi / 8),
}
end
end
return ret, suported_playercounts
| gpl-2.0 |
JonasJurczok/faketorio | spec/copy_spec.lua | 1 | 2590 | describe("Test the copy functionality #copy", function()
lazy_setup(function()
require("faketorio.lib")
faketorio.lfs.mkdir("locale")
faketorio.lfs.mkdir("locale/de")
faketorio.lfs.mkdir("locale/en")
local file = io.open("locale/de/blub.cfg", "w")
file:write("asdasd")
file:close()
file = io.open("locale/en/blub.cfg", "w")
file:write("asdasd")
file:close()
faketorio.lfs.mkdir("factorio")
end)
lazy_teardown(function()
faketorio.delete_directory("locale")
faketorio.delete_directory("factorio")
faketorio.clean()
end)
if not busted then busted = {} end
function busted.collect_file_names(directory)
local result = {}
for file in faketorio.lfs.dir(directory) do
if (file ~= "." and file ~= "..") then
local path = directory .."/".. file
local mode = faketorio.lfs.attributes(path, "mode")
if mode == "file" then
table.insert(result, path)
elseif mode == "directory" then
for _, p in pairs(busted.collect_file_names(path)) do
table.insert(result, p)
end
end
end
end
table.insert(result, directory)
return result
end
it("should collect all lua scripts with their subfolders from src, spec and locale.", function()
faketorio.execute({copy = true})
assert.are.equals("target/Faketorio-test-mod_0.1.0", faketorio.output_folder)
for _, file in pairs(busted.collect_file_names("src")) do
file = string.gsub(file, "src", "factorio/Faketorio-test-mod_0.1.0")
faketorio.print_message("Verifying file ["..file.."].")
assert.is_Truthy(faketorio.lfs.attributes(file))
end
for _, file in pairs(busted.collect_file_names("locale")) do
file = "factorio/Faketorio-test-mod_0.1.0/"..file
faketorio.print_message("Verifying file ["..file.."].")
assert.is_Truthy(faketorio.lfs.attributes(file))
end
local file = "factorio/Faketorio-test-mod_0.1.0/faketorio/features/dummy_feature.lua"
assert.is_Truthy(faketorio.lfs.attributes(file))
file = "factorio/Faketorio-test-mod_0.1.0/faketorio/features/clean_spec.lua"
assert.is_Falsy(faketorio.lfs.attributes(file))
assert.is_Truthy(faketorio.lfs.attributes("factorio/Faketorio-test-mod_0.1.0/info.json"))
end)
end) | mit |
Laterus/Darkstar-Linux-Fork | scripts/zones/Windurst_Woods/Zone.lua | 1 | 1921 | -----------------------------------
--
-- Zone: Windurst_Woods
--
-----------------------------------
package.loaded["scripts/zones/Windurst_Woods/TextIDs"] = nil;
-----------------------------------
require("scripts/globals/server");
require("scripts/globals/settings");
require("scripts/zones/Windurst_Woods/TextIDs");
-----------------------------------
-- onInitialize
-----------------------------------
function onInitialize(zone)
end;
-----------------------------------
-- onZoneIn
-----------------------------------
function onZoneIn(player,prevZone)
cs = -1;
-- FIRST LOGIN (START CS)
if (prevZone == 0) then
if (OPENING_CUTSCENE_ENABLE == 1) then
cs = 0x016F;
end
CharCreate(player);
player:setPos(0,0,-50,0);
player:setHomePoint();
end
-- MOG HOUSE EXIT
if ((player:getXPos() == 0) and (player:getYPos() == 0) and (player:getZPos() == 0)) then
position = math.random(1,5) + 37;
player:setPos(-138,-10,position,0);
if (player:getMainJob() ~= player:getVar("PlayerMainJob")) then
cs = 0x7534;
end
player:setVar("PlayerMainJob",0);
end
return cs;
end;
-----------------------------------
-- onRegionEnter
-----------------------------------
function onRegionEnter(player,region)
end;
-----------------------------------
-- onEventUpdate
-----------------------------------
function onEventUpdate(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
end;
-----------------------------------
-- onEventFinish
-----------------------------------
function onEventFinish(player,csid,option)
--printf("CSID: %u",csid);
--printf("RESULT: %u",option);
if(csid == 0x016F) then
player:messageSpecial(ITEM_OBTAINED,0x218);
elseif (csid == 0x7534 and option == 0) then
player:setHomePoint();
player:messageSpecial(HOMEPOINT_SET);
end
end;
| gpl-3.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/maps/zones/prides.lua | 3 | 6960 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
startx = 63
starty = 32
endx = 0
endy = 32
subGenerator{
x = 8, y = 8, w = 48, h = 48,
generator = data.sublevel.class,
data = table.clone(data.sublevel),
}
local floor = data.floor or data.sublevel.floor
local wall = data.wall or data.sublevel.wall or "HARDWALL"
local generic_leveler = data.generic_leveler or data.sublevel.generic_leveler or "GENERIC_LEVER"
local generic_leveler_door = data.generic_leveler_door or data.sublevel.generic_leveler_door or "GENERIC_LEVER_DOOR"
-- defineTile section
defineTile("#", wall)
defineTile("o", floor, nil, {entity_mod=function(e) e.make_escort = nil return e end, random_filter={type='humanoid', subtype='orc', special=function(e) return e.pride == data.sublevel.pride end}})
quickEntity("g", 'o')
defineTile(".", floor)
defineTile("+", data.sublevel.door)
defineTile("<", data.up)
if level.level == zone.max_level then quickEntity(">", '.') else defineTile(">", data.down, nil, nil, nil, {no_teleport=true}) end
if level.level == 1 then defineTile("O", floor, nil, {random_filter={type='humanoid', subtype='orc', special=function(e) return e.pride == data.sublevel.pride end, random_boss={nb_classes=1, loot_quality="store", loot_quantity=3, ai_move="move_complex", rank=3.5,}}})
else quickEntity('O', 'o') end
defineTile(";", floor, nil, nil, nil, {no_teleport=true})
defineTile(" ", floor, nil, {entity_mod=function(e) e.make_escort = nil return e end, random_filter={type='humanoid', subtype='orc', special=function(e) return e.pride == data.sublevel.pride end, random_boss={nb_classes=1, loot_quality="store", loot_quantity=1, no_loot_randart=true, ai_move="move_complex", rank=3}}}, nil, {no_teleport=true})
defineTile('&', generic_leveler, nil, nil, nil, {lever=1, lever_kind="pride-doors", lever_spot={type="lever", subtype="door"}})
defineTile('*', generic_leveler_door, nil, nil, nil, {lever_action=2, lever_action_value=0, lever_action_kind="pride-doors"}, {type="lever", subtype="door"})
-- addSpot section
-- addZone section
-- ASCII map section
return [[
################################################################
################################################################
########################..g...##################################
########################&#g......###############################
########################..g...##.###############################
################################.###############################
################################.###############################
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
###;;;#..................................................#ooo###
##;;;##..................................................##...##
##;;;##..................................................##...##
;;;;;##..................................................##.....
;;;;;#....................................................#.....
; ;;;#....................................................#.....
> ;;;*....................................................+O...<
; ;;;#....................................................#.....
;;;;;#....................................................#.....
;;;;;##..................................................##.....
##;;;##..................................................##...##
##;;;##..................................................##...##
###;;;#..................................................#ooo###
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
#######..................................................#######
################################.###############################
################################.###############################
########################..g...##.###############################
########################&#g......###############################
########################..g...##################################
################################################################
################################################################]] | gpl-3.0 |
groupforspeed/API-WaderTG | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
fegimanam/s | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
Ali-2h/hackerbot | libs/mimetype.lua | 3662 | 2922 | -- Thanks to https://github.com/catwell/lua-toolbox/blob/master/mime.types
do
local mimetype = {}
-- TODO: Add more?
local types = {
["text/html"] = "html",
["text/css"] = "css",
["text/xml"] = "xml",
["image/gif"] = "gif",
["image/jpeg"] = "jpg",
["application/x-javascript"] = "js",
["application/atom+xml"] = "atom",
["application/rss+xml"] = "rss",
["text/mathml"] = "mml",
["text/plain"] = "txt",
["text/vnd.sun.j2me.app-descriptor"] = "jad",
["text/vnd.wap.wml"] = "wml",
["text/x-component"] = "htc",
["image/png"] = "png",
["image/tiff"] = "tiff",
["image/vnd.wap.wbmp"] = "wbmp",
["image/x-icon"] = "ico",
["image/x-jng"] = "jng",
["image/x-ms-bmp"] = "bmp",
["image/svg+xml"] = "svg",
["image/webp"] = "webp",
["application/java-archive"] = "jar",
["application/mac-binhex40"] = "hqx",
["application/msword"] = "doc",
["application/pdf"] = "pdf",
["application/postscript"] = "ps",
["application/rtf"] = "rtf",
["application/vnd.ms-excel"] = "xls",
["application/vnd.ms-powerpoint"] = "ppt",
["application/vnd.wap.wmlc"] = "wmlc",
["application/vnd.google-earth.kml+xml"] = "kml",
["application/vnd.google-earth.kmz"] = "kmz",
["application/x-7z-compressed"] = "7z",
["application/x-cocoa"] = "cco",
["application/x-java-archive-diff"] = "jardiff",
["application/x-java-jnlp-file"] = "jnlp",
["application/x-makeself"] = "run",
["application/x-perl"] = "pl",
["application/x-pilot"] = "prc",
["application/x-rar-compressed"] = "rar",
["application/x-redhat-package-manager"] = "rpm",
["application/x-sea"] = "sea",
["application/x-shockwave-flash"] = "swf",
["application/x-stuffit"] = "sit",
["application/x-tcl"] = "tcl",
["application/x-x509-ca-cert"] = "crt",
["application/x-xpinstall"] = "xpi",
["application/xhtml+xml"] = "xhtml",
["application/zip"] = "zip",
["application/octet-stream"] = "bin",
["audio/midi"] = "mid",
["audio/mpeg"] = "mp3",
["audio/ogg"] = "ogg",
["audio/x-m4a"] = "m4a",
["audio/x-realaudio"] = "ra",
["video/3gpp"] = "3gpp",
["video/mp4"] = "mp4",
["video/mpeg"] = "mpeg",
["video/quicktime"] = "mov",
["video/webm"] = "webm",
["video/x-flv"] = "flv",
["video/x-m4v"] = "m4v",
["video/x-mng"] = "mng",
["video/x-ms-asf"] = "asf",
["video/x-ms-wmv"] = "wmv",
["video/x-msvideo"] = "avi"
}
-- Returns the common file extension from a content-type
function mimetype.get_mime_extension(content_type)
return types[content_type]
end
-- Returns the mimetype and subtype
function mimetype.get_content_type(extension)
for k,v in pairs(types) do
if v == extension then
return k
end
end
end
-- Returns the mimetype without the subtype
function mimetype.get_content_type_no_sub(extension)
for k,v in pairs(types) do
if v == extension then
-- Before /
return k:match('([%w-]+)/')
end
end
end
return mimetype
end | gpl-2.0 |
BinChengfei/openwrt-3.10.14 | package/ramips/ui/luci-mtk/src/applications/luci-freifunk-widgets/luasrc/model/cbi/freifunk/widgets/widgets_overview.lua | 78 | 2041 | --[[
LuCI - Lua Configuration Interface
Copyright 2012 Manuel Munz <freifunk at somakoma dot de>
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
]]--
local uci = require "luci.model.uci".cursor()
local fs = require "luci.fs"
local utl = require "luci.util"
m = Map("freifunk-widgets", translate("Widgets"),
translate("Configure installed widgets."))
wdg = m:section(TypedSection, "widget", translate("Widgets"))
wdg.addremove = true
wdg.extedit = luci.dispatcher.build_url("admin/freifunk/widgets/widget/%s")
wdg.template = "cbi/tblsection"
wdg.sortable = true
--[[
function wdg.create(...)
local sid = TypedSection.create(...)
luci.http.redirect(wdg.extedit % sid)
end
]]--
local en = wdg:option(Flag, "enabled", translate("Enable"))
en.rmempty = false
--en.default = "0"
function en.cfgvalue(self, section)
return Flag.cfgvalue(self, section) or "0"
end
local tmpl = wdg:option(ListValue, "template", translate("Template"))
for k, v in ipairs(fs.dir('/usr/lib/lua/luci/view/freifunk/widgets/')) do
if v ~= "." and v ~= ".." then
tmpl:value(v)
end
end
local title = wdg:option(Value, "title", translate("Title"))
title.rmempty = true
local width = wdg:option(Value, "width", translate("Width"))
width.rmempty = true
local height = wdg:option(Value, "height", translate("Height"))
height.rmempty = true
local pr = wdg:option(Value, "paddingright", translate("Padding right"))
pr.rmempty = true
function m.on_commit(self)
-- clean custom text files whose config has been deleted
local dir = "/usr/share/customtext/"
local active = {}
uci:foreach("freifunk-widgets", "widget", function(s)
if s["template"] == "html" then
table.insert(active, s[".name"])
end
end )
for k, v in ipairs(fs.dir(dir)) do
filename = string.gsub(v, ".html", "")
if not utl.contains(active, filename) then
fs.unlink(dir .. v)
end
end
end
return m
| gpl-2.0 |
pakoito/ToME---t-engine4 | game/modules/tome/data/lore/slazish.lua | 3 | 4796 | -- ToME - Tales of Maj'Eyal
-- Copyright (C) 2009 - 2014 Nicolas Casalini
--
-- This program is free software: you can redistribute it and/or modify
-- it under the terms of the GNU General Public License as published by
-- the Free Software Foundation, either version 3 of the License, or
-- (at your option) any later version.
--
-- This program is distributed in the hope that it will be useful,
-- but WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
-- GNU General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
--
-- Nicolas Casalini "DarkGod"
-- darkgod@te4.org
--------------------------------------------------------------------------
-- Slazish fens
--------------------------------------------------------------------------
newLore{
id = "slazish-note-1",
category = "slazish fens",
name = "conch (1)",
lore = [[#{italic}#Touching the conch makes it emit a sound. As you put it to your ear you hear a lyrical voice emanating from within:#{normal}#
"Report from Tidewarden Isimon to Tidebringer Zoisla. Alucia and I have, um, begun scouting the outer perimeter. The, uh, the terrain is proving difficult to navigate, but I'm sure we'll make, uh, quick progress. We shall, uh, we'll continue now... in the name of the Saviour!
"...Um, you think that was okay?"
#{italic}#A second, lighter voice joins in.#{normal}# "Yeah, that was fine, Isimon. We'll make a Myrmidon of you yet!"
"Heh, I wouldn't be so sure of that... Guess I'll turn this off and we'll get going."
"Hey, what's the rush? This is the first time we've been alone from the others all week. Maybe we could..."
"What? Surely you don't mean-? What if someone comes along?"
"Oh, who would catch us out here? Come on!"
"I, uh, well, I suppose... I should stop this recording."]],
}
newLore{
id = "slazish-note-2",
category = "slazish fens",
name = "conch (2)",
lore = [[#{italic}#Touching the conch makes it emit a sound. As you put it to your ear you hear a deep voice emanating from within:#{normal}#
"Waverider Tiamel reporting. Immediate perimeter is secure, though I have sent some members to scout the surrounding areas. I will feel better when we have mapped the land and are ready to sustain a larger team. Still, we should be perfectly safe as long as the landdwellers do not know of our presence. And even if they dare come here the magics of Zoisla will put their puny star worship to shame.
"I fear that some of the team are not taking our mission seriously. Do they not know the responsibility the Saviour has laid on us? We are his arms and tails in this far land, and it is our duty to protect the farportal which will help bring us to greater strengths. We are his first line of attack against the blood relatives of those who doomed our race so long ago. And with our efforts we shall push forward our race to new boundaries, laying the path for the bright future our great Saviour has planned for us. Long live Slasul! Long live the legend of the Devourer!"]],
}
newLore{
id = "slazish-note-3",
category = "slazish fens",
name = "conch (3)",
lore = [[#{italic}#Touching the conch makes it emit a sound. As you put it to your ear you hear a charismatic and commanding voice emanating from within:#{normal}#
"My fellow nagas! I do not envy you on your journey so far from our great Temple. But you have been chosen for a glorious mission, to establish a new outpost for invasion against the landwalkers. These are the cousins and descendants of those who abandoned us and left our race for dead. Whilst we have hidden beneath the waves for centuries, they prance about worshipping the sun! Well, their nightfall comes soon, and the dawn will rise with us as rulers of land and sea.
"Do not despair that we are attacking this outpost instead of the orcs. My stratagem is carefully planned, and the Sunwall is too great a threat to my designs to be allowed to stand any longer. The orcs... will have their uses in the short term. But be assured, when our time comes there shall be none who can stand as equals against us. Our greatness cannot be quelled or submerged! Our long history of suffering will finally bring forth redemption!
"Your immediate mission is clear, my friends. Ensure the farportal is correctly set up and secured, but take care, as the Sher'Tul magics used are still experimental. Then scout out the area and begin to fortify the surroundings, but do so in secret. When your job is done well I, your humble leader Slasul, shall be honoured to join you on the front line. Until then, swim safely my brothers and sisters, and do not forget our glory."
]],
}
| gpl-3.0 |
RyMarq/Zero-K | units/striderdetriment.lua | 1 | 10668 | return { striderdetriment = {
unitname = [[striderdetriment]],
name = [[Detriment]],
description = [[Ultimate Assault Strider]],
acceleration = 0.328,
activateWhenBuilt = true,
autoheal = 30,
brakeRate = 1.435,
buildCostMetal = 20000,
builder = false,
buildPic = [[striderdetriment.png]],
canGuard = true,
--canManualFire = true,
canMove = true,
canPatrol = true,
category = [[LAND]],
collisionVolumeOffsets = [[0 14 0]],
collisionVolumeScales = [[92 158 92]],
collisionVolumeType = [[cylY]],
corpse = [[DEAD]],
customParams = {
modelradius = [[95]],
extradrawrange = 925,
},
explodeAs = [[NUCLEAR_MISSILE]],
footprintX = 6,
footprintZ = 6,
iconType = [[krogoth]],
leaveTracks = true,
losEmitHeight = 100,
maxDamage = 86000,
maxSlope = 37,
maxVelocity = 1.2,
maxWaterDepth = 5000,
minCloakDistance = 150,
movementClass = [[AKBOT6]],
noAutoFire = false,
noChaseCategory = [[TERRAFORM SATELLITE SUB]],
objectName = [[detriment.s3o]],
script = [[striderdetriment.lua]],
selfDestructAs = [[NUCLEAR_MISSILE]],
selfDestructCountdown = 10,
sightDistance = 910,
sonarDistance = 910,
trackOffset = 0,
trackStrength = 8,
trackStretch = 0.8,
trackType = [[ComTrack]],
trackWidth = 60,
turnRate = 482,
upright = true,
weapons = {
{
def = [[GAUSS]],
badTargetCategory = [[FIXEDWING]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SUB SHIP SWIM FLOAT GUNSHIP HOVER]],
},
{
def = [[AALASER]],
badTargetCategory = [[GUNSHIP]],
onlyTargetCategory = [[FIXEDWING GUNSHIP]],
},
{
def = [[ORCONE_ROCKET]],
onlyTargetCategory = [[SWIM LAND SINK TURRET FLOAT SHIP HOVER]],
},
{
def = [[TRILASER]],
onlyTargetCategory = [[FIXEDWING LAND SINK TURRET SHIP SWIM FLOAT GUNSHIP HOVER]],
},
},
weaponDefs = {
GAUSS = {
name = [[Gauss Battery]],
alphaDecay = 0.12,
areaOfEffect = 16,
avoidfeature = false,
bouncerebound = 0.15,
bounceslip = 1,
burst = 3,
burstrate = 0.2,
cegTag = [[gauss_tag_h]],
craterBoost = 0,
craterMult = 0,
customParams = {
single_hit_multi = true,
reaim_time = 1,
},
damage = {
default = 200.1,
planes = 200.1,
},
explosionGenerator = [[custom:gauss_hit_h]],
groundbounce = 1,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0,
interceptedByShieldType = 1,
noExplode = true,
noSelfDamage = true,
numbounce = 40,
range = 600,
reloadtime = 1.2,
rgbColor = [[0.5 1 1]],
separation = 0.5,
size = 0.8,
sizeDecay = -0.1,
soundHit = [[weapon/gauss_hit]],
soundStart = [[weapon/gauss_fire]],
sprayangle = 800,
stages = 32,
tolerance = 4096,
turret = true,
waterweapon = true,
weaponType = [[Cannon]],
weaponVelocity = 900,
},
AALASER = {
name = [[Anti-Air Laser Battery]],
areaOfEffect = 12,
beamDecay = 0.736,
beamTime = 1/30,
beamttl = 15,
canattackground = false,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
cylinderTargeting = 1,
customParams = {
isaa = [[1]],
reaim_time = 1,
},
damage = {
default = 2.05,
planes = 20.5,
subs = 1.125,
},
explosionGenerator = [[custom:flash_teal7]],
fireStarter = 100,
impactOnly = true,
impulseFactor = 0,
interceptedByShieldType = 1,
laserFlareSize = 3.75,
minIntensity = 1,
noSelfDamage = true,
range = 820,
reloadtime = 0.1,
rgbColor = [[0 1 1]],
soundStart = [[weapon/laser/rapid_laser]],
thickness = 2.5,
tolerance = 8192,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 2200,
},
DISRUPTOR = {
name = [[Disruptor Pulse Beam]],
areaOfEffect = 32,
beamdecay = 0.95,
beamTime = 1/30,
beamttl = 90,
coreThickness = 0.25,
craterBoost = 0,
craterMult = 0,
customParams = {
--timeslow_preset = [[module_disruptorbeam]],
timeslow_damagefactor = [[2]],
reaim_time = 1,
},
damage = {
default = 600,
},
explosionGenerator = [[custom:flash2purple]],
fireStarter = 30,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 4.33,
minIntensity = 1,
noSelfDamage = true,
range = 350,
reloadtime = 2,
rgbColor = [[0.3 0 0.4]],
soundStart = [[weapon/laser/heavy_laser5]],
soundStartVolume = 3,
soundTrigger = true,
sweepfire = false,
texture1 = [[largelaser]],
texture2 = [[flare]],
texture3 = [[flare]],
texture4 = [[smallflare]],
thickness = 18,
tolerance = 18000,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 500,
},
TRILASER = {
name = [[High-Energy Laserbeam]],
areaOfEffect = 14,
beamTime = 0.8,
beamttl = 1,
coreThickness = 0.5,
craterBoost = 0,
craterMult = 0,
customParams = {
light_color = [[0.2 0.8 0.2]],
reaim_time = 1,
},
damage = {
default = 600,
planes = 600,
subs = 45,
},
explosionGenerator = [[custom:flash1green]],
fireStarter = 90,
impactOnly = true,
impulseBoost = 0,
impulseFactor = 0.4,
interceptedByShieldType = 1,
largeBeamLaser = true,
laserFlareSize = 10.4,
leadLimit = 18,
minIntensity = 1,
noSelfDamage = true,
projectiles = 3,
range = 600,
reloadtime = 6,
rgbColor = [[0 1 0]],
scrollSpeed = 5,
soundStart = [[weapon/laser/heavy_laser3]],
soundStartVolume = 2,
sweepfire = false,
texture1 = [[largelaser]],
texture2 = [[flare]],
texture3 = [[flare]],
texture4 = [[smallflare]],
thickness = 8,
tileLength = 300,
tolerance = 10000,
turret = true,
weaponType = [[BeamLaser]],
weaponVelocity = 2250,
},
ORCONE_ROCKET = {
name = [[Medium-Range Missiles]],
areaOfEffect = 160,
cegTag = [[seismictrail]],
collideFriendly = false,
craterBoost = 1,
craterMult = 2,
customParams = {
gatherradius = [[180]],
smoothradius = [[120]],
smoothmult = [[0.25]],
smoothexponent = [[0.45]],
movestructures = [[1]],
light_color = [[1 1.4 0.35]],
light_radius = 400,
reaim_time = 1,
},
damage = {
default = 851,
subs = 42.5,
},
edgeEffectiveness = 0.75,
explosionGenerator = [[custom:TESS]],
fireStarter = 55,
flightTime = 10,
impulseBoost = 0,
impulseFactor = 0.8,
interceptedByShieldType = 2,
model = [[wep_m_kickback.s3o]],
noSelfDamage = true,
range = 925,
reloadtime = 1.533,
smokeTrail = false,
soundHit = [[weapon/missile/vlaunch_hit]],
soundStart = [[weapon/missile/missile_launch]],
turnrate = 18000,
weaponAcceleration = 245,
weaponTimer = 2,
weaponType = [[StarburstLauncher]],
weaponVelocity = 10000,
},
},
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 6,
footprintZ = 6,
object = [[Detriment_wreck.s3o]],
},
HEAP = {
blocking = false,
footprintX = 4,
footprintZ = 4,
object = [[debris4x4b.s3o]],
},
},
} }
| gpl-2.0 |
RyMarq/Zero-K | LuaRules/Gadgets/unit_AA_overkill_control.lua | 2 | 5815 | local versionNumber = "v0.1"
function gadget:GetInfo()
return {
name = "AA overkill control",
desc = versionNumber .. " Managed Allowed Weapon Target for Defender, Hacksaw, Chainsaw and Artemis to prevent overkill",
author = "Jseah",
date = "03/05/13",
license = "GNU GPL, v2 or later",
layer = 0,
enabled = false -- loaded by default?
}
end
if (not gadgetHandler:IsSyncedCode()) then
return
end
--SYNCED--
include("LuaRules/Configs/customcmds.h.lua")
local unitAICmdDesc = {
id = CMD_UNIT_AI,
type = CMDTYPE.ICON_MODE,
name = 'Unit AI',
action = 'unitai',
tooltip = 'Toggles smart unit AI for the unit',
params = {1, 'AI Off','AI On'}
}
local GetTarget = Spring.GetProjectileTarget
local GetUnitDefID = Spring.GetUnitDefID
local GetHP = Spring.GetUnitHealth
local FindUnitCmdDesc = Spring.FindUnitCmdDesc
local EditUnitCmdDesc = Spring.EditUnitCmdDesc
local GetUnitCmdDesc = Spring.GetUnitCmdDescs
local InsertUnitCmdDesc = Spring.InsertUnitCmdDesc
local airtargets = {} -- {id = unitID, incoming = {shotID}, receivingdamage = int}
local shot = {} -- {id = shotID, unitID = ownerunitID, target = targetunitID, damage = int)
local AAunittypes = {["turretmissile"] = 1, ["turretaaclose"] = 1, ["turretaafar"] = 1, ["turretaaheavy"] = 1} -- number = shot damage
local IsAA = {
[UnitDefNames.turretmissile.id] = true,
[UnitDefNames.turretaaclose.id] = true,
[UnitDefNames.turretaafar.id] = true,
[UnitDefNames.turretaaheavy.id] = true
}
local Isair = {}
for i=1,#UnitDefs do
if UnitDefs[i].canFly then
Isair[i] = true
end
end
local remUnitDefID = {}
local Echo = Spring.Echo
-------------------FUNCTIONS------------------
function IsMicroCMD(unitID)
if unitID ~= nil then
local cmdDescID = FindUnitCmdDesc(unitID, CMD_UNIT_AI)
local cmdDesc = GetUnitCmdDesc(unitID, cmdDescID, cmdDescID)
local nparams = cmdDesc[1].params
if nparams[1] == '1' then
return true
end
end
return false
end
function AddShot(shotID, unitID, target, damage)
--Echo("Added shot", shotID, unitID, target, damage)
if target ~= nil then
shot[shotID] = {id = shotID, owner = unitID, target = target, damage = damage}
if airtargets[target] ~= nil then
airtargets[target].incoming[shotID] = shotID
airtargets[target].receivingdamage = airtargets[target].receivingdamage + damage
end
end
end
function RemoveShot(shotID)
--Echo("Removed shot", shotID)
local target = shot[shotID].target
if airtargets[target] ~= nil then
airtargets[target].incoming[shotID] = nil
airtargets[target].receivingdamage = airtargets[target].receivingdamage - shot[shotID].damage
end
shot[shotID] = nil
end
function AddAir(unitID, ud)
--Echo("Added air unit", unitID)
airtargets[unitID] = {id = unitID, incoming = {}, receivingdamage = 0}
end
function removeAir(unitID)
--Echo("Removed air unit", unitID)
for shotID in pairs(airtargets[unitID].incoming) do
--Echo("Overkill shot removed", shotID)
RemoveShot(shotID)
end
airtargets[unitID] = nil
end
-------------------CALL INS-------------------
function gadget:UnitCreated(unitID, unitDefID, unitTeam, builderID)
remUnitDefID[unitID] = unitDefID
if IsAA[unitDefID] then
local ud = UnitDefs[unitDefID]
InsertUnitCmdDesc(unitID, unitAICmdDesc)
local cmdDescID = FindUnitCmdDesc(unitID, CMD_UNIT_AI)
EditUnitCmdDesc(unitID, cmdDescID, {params = {0, 'AI Off','AI On'}})
end
if Isair[unitDefID] then
AddAir(unitID, ud)
end
end
function gadget:UnitDestroyed(unitID, unitDefID, unitTeam)
local ud = UnitDefs[unitDefID]
remUnitDefID[unitID] = unitDefID
if Isair[unitDefID] then
removeAir(unitID)
end
end
function gadget:Initialize()
Echo("AA overkill control Gadget Enabled")
for unitname in pairs(AAunittypes) do
local damage = 0
for i = 1,#WeaponDefs do
local wd = WeaponDefs[i]
if wd.name:find(unitname) then
for j = 1, #wd.damages do
if damage < wd.damages[j] then
damage = wd.damages[j]
end
end
end
end
AAunittypes[unitname] = damage
end
for _, unitID in pairs(Spring.GetAllUnits()) do
local unitDefID = Spring.GetUnitDefID(unitID)
gadget:UnitCreated(unitID, unitDefID)
end
end
function gadget:ProjectileCreated(projID, unitID)
local unitDefID = GetUnitDefID(unitID)
local ud = UnitDefs[unitDefID]
--Echo(ud.name)
if IsAA[unitDefID] then
AddShot(projID, unitID, GetTarget(projID), AAunittypes[ud.name])
end
end
function gadget:ProjectileDestroyed(projID)
if shot[projID] ~= nil then
RemoveShot(projID)
end
end
function gadget:AllowWeaponTarget(attackerID, targetID, attackerWeaponNum, attackerWeaponDefID, defPriority)
local unitDefID = remUnitDefID[attackerID]
if IsAA[unitDefID] and IsMicroCMD(attackerID) then
local ud = UnitDefs[unitDefID]
--Echo(attackerID, targetID)
local tunitDefID = Spring.GetUnitDefID(targetID)
local tud = UnitDefs[tunitDefID]
if Isair[tunitDefID] then
hp = GetHP(targetID)
if hp < airtargets[targetID].receivingdamage then
--Echo("preventing overkill")
return false, 1
end
end
end
return true, 1
end
function gadget:AllowCommand_GetWantedCommand()
return true
end
function gadget:AllowCommand_GetWantedUnitDefID()
return IsAA
end
function gadget:AllowCommand(unitID, unitDefID, teamID, cmdID, cmdParams, cmdOptions)
local ud = UnitDefs[unitDefID]
if IsAA[unitDefID] then
if cmdID == CMD_UNIT_AI then
local cmdDescID = FindUnitCmdDesc(unitID, CMD_UNIT_AI)
if cmdParams[1] == 0 then
nparams = {0, 'AI Off','AI On'}
else
nparams = {1, 'AI Off','AI On'}
end
EditUnitCmdDesc(unitID, cmdDescID, {params = nparams})
end
end
return true
end
| gpl-2.0 |
RyMarq/Zero-K | units/staticrearm.lua | 1 | 2062 | return { staticrearm = {
unitname = [[staticrearm]],
name = [[Airpad]],
description = [[Repairs and Rearms Aircraft, repairs at 2.5 e/s per pad]],
acceleration = 0,
activateWhenBuilt = true,
brakeRate = 0,
buildCostMetal = 350,
buildDistance = 6,
builder = true,
buildPic = [[staticrearm.png]],
canAttack = true,
canMove = true,
canPatrol = true,
category = [[UNARMED FLOAT]],
collisionVolumeOffsets = [[0 0 0]],
collisionVolumeScales = [[130 40 130]],
collisionVolumeType = [[box]],
selectionVolumeOffsets = [[0 0 0]],
selectionVolumeScales = [[130 40 130]],
selectionVolumeType = [[box]],
corpse = [[DEAD]],
customParams = {
pad_count = 4,
nobuildpower = 1,
notreallyafactory = 1,
selection_rank = [[1]],
selectionscalemult = 1,
ispad = 1,
},
explodeAs = [[LARGE_BUILDINGEX]],
footprintX = 9,
footprintZ = 9,
iconType = [[building]],
idleAutoHeal = 5,
idleTime = 1800,
maxDamage = 1860,
maxSlope = 18,
maxVelocity = 0,
minCloakDistance = 150,
objectName = [[airpad.s3o]],
script = [[staticrearm.lua]],
selfDestructAs = [[LARGE_BUILDINGEX]],
showNanoSpray = false,
sightDistance = 273,
turnRate = 0,
waterline = 8,
workerTime = 10,
yardMap = [[ooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooooo]],
featureDefs = {
DEAD = {
blocking = true,
featureDead = [[HEAP]],
footprintX = 9,
footprintZ = 9,
object = [[airpad_dead.s3o]],
},
HEAP = {
blocking = false,
footprintX = 1,
footprintZ = 1,
object = [[debris4x4a.s3o]],
},
},
} }
| gpl-2.0 |
Laterus/Darkstar-Linux-Fork | scripts/globals/items/bibiki_slug.lua | 1 | 1279 | -----------------------------------------
-- ID: 5122
-- Item: Bibiki Slug
-- Food Effect: 5Min, Mithra only
-----------------------------------------
-- Dexterity -5
-- Vitality 4
-- defense % 16
-----------------------------------------
require("scripts/globals/status");
-----------------------------------------
-- OnItemCheck
-----------------------------------------
function onItemCheck(target)
result = 0;
if (target:getRace() ~= 7) then
result = 247;
elseif (target:hasStatusEffect(EFFECT_FOOD) == true) then
result = 246;
end
return result;
end;
-----------------------------------------
-- OnItemUse
-----------------------------------------
function onItemUse(target)
target:addStatusEffect(EFFECT_FOOD,0,0,300,0,5122);
end;
-----------------------------------------
-- onEffectGain Action
-----------------------------------------
function onEffectGain(target,effect)
target:addMod(MOD_DEX, -5);
target:addMod(MOD_VIT, 4);
target:addMod(MOD_DEFP, 16);
end;
-----------------------------------------
-- onEffectLose Action
-----------------------------------------
function onEffectLose(target,effect)
target:delMod(MOD_DEX, -5);
target:delMod(MOD_VIT, 4);
target:delMod(MOD_DEFP, 16);
end;
| gpl-3.0 |
madpilot78/ntopng | scripts/lua/modules/voip_utils.lua | 1 | 32489 | --
-- (C) 2013-21 - ntop.org
--
-- ########################################################
-- require "flow_utils"
local payload_type = 0
function isVoip(key,value)
key_label = getFlowKey(key)
if (key_label == "Total number of exported flows") then return 1 end
if (key_label =='Rtp Voice Quality') then
print("<tr><th width=30%>" .. key_label .. '</th><td colspan=2>')
print(MosPercentageBar(value))
print("</td></tr>\n")
return 1
elseif (key_label=='Sip Call State') then
print("<tr><th width=30%>" .. key_label .. "</th><td colspan=2>")
SipCallStatePercentageBar(value)
print("</td></tr>\n")
return 1
elseif ((key_label == 'Rtp Out Coming Payload Type') or (key_label == "Rtp Incoming Payload Type")) then
if (payload_type == 0) then
payload_type = 1
print("<tr><th width=30%>Rtp Payload Type</th><td colspan=2>"..formatRtpPayloadType(value).."</td></tr>\n")
end
return 1
elseif ((key_label == 'Rtp Out Coming Packet Delay Variation') or (key_label == "Rtp Incoming Packet Delay Variation")) then
print("<tr><th width=30%>" .. key_label .. "</th><td colspan=2>"..((value/1000)/1000).." ms</td></tr>\n")
return 1
elseif ((key_label == 'SIP_CALLED_PARTY') or (key_label == "SIP_CALLING_PARTY")) then
print("<tr><th width=30%>" .. key_label .. "</th><td colspan=2>"..spiltSipID(value).."</td></tr>\n")
return 1
end
return 0
end
function spiltSipID( id )
id = string.gsub(id, "<sip:", "")
id = string.gsub(id, ">", "")
port = split(id,":")
sip_party = split(port[1],"@")
host = interface.getHostInfo(sip_party[2])
if (host ~= nil) then
return(hostinfo2detailshref(host, nil, id))
end
return(id)
end
-- RTP
rtp_payload_type = {
[0] = 'PCMU',
[1] = 'reserved',
[2] = 'reserved',
[3] = 'GSM',
[4] = 'G723',
[5] = 'DVI4',
[6] = 'DVI4',
[7] = 'LPC',
[8] = 'PCMA',
[9] = 'G722',
[10] = 'L16',
[11] = 'L16',
[12] = 'QCELP',
[13] = 'CN',
[14] = 'MPA',
[15] = 'G728',
[16] = 'DVI4',
[17] = 'DVI4',
[18] = 'G729',
[25] = 'CELB',
[26] = 'JPEG',
[28] = 'NV',
[31] = 'H261',
[32] = 'MPV',
[33] = 'MP2T',
[34] = 'H263',
[35] = 'unassigned',
[71] = 'unassigned',
[76] = 'Reserved for RTCP conflict avoidance',
[72] = 'Reserved for RTCP conflict avoidance',
[73] = 'Reserved for RTCP conflict avoidance',
[74] = 'Reserved for RTCP conflict avoidance',
[75] = 'Reserved for RTCP conflict avoidance',
[76] = 'Reserved for RTCP conflict avoidance',
[95] = 'unassigned',
[96] = 'dynamic',
[127] = 'dynamic'
}
-- ########################################################
function formatRtpPayloadType(flags)
if(flags == nil) then return("") end
flags = tonumber(flags)
if(rtp_payload_type[flags] ~= nil) then
return(rtp_payload_type[flags])
end
return flags;
end
-- ########################################################
function MosPercentageBar(value)
local ret_bar = ""
value = tonumber(value)
if (value >= 4.0) then
ret_bar = '<span class="badge bg-success">'..value..' '..i18n("flow_details.desirable_label")..'</span>'
elseif ((value >= 3.6) and (value < 4.0)) then
ret_bar = '<span class="badge bg-info">'..value..' '..i18n("flow_details.acceptable_label")..'</span>'
elseif ((value >= 2.6) and (value < 3.6)) then
ret_bar = '<span class="badge bg-warning">'..value..' '..i18n("flow_details.reach_connection_label")..'</span>'
elseif ((value > 0) and (value < 2.6)) then
ret_bar = '<span class="badge bg-danger">'..value..' '..i18n("flow_details.not_recommended_label")..'</span>'
end
return ret_bar
end
-- ########################################################
function RFactorPercentageBar(value)
local ret_bar = ""
value = tonumber(value)
if (value >= 80.0) then
ret_bar = '<span class="badge bg-success">'..value..' '..i18n("flow_details.desirable_label")..'</span>'
elseif ((value >= 70.0) and (value < 80.0)) then
ret_bar = '<span class="badge bg-info">'..value..' '..i18n("flow_details.acceptable_label")..'</span>'
elseif ((value >= 50.0) and (value < 70.0)) then
ret_bar = '<span class="badge bg-warning">'..value..' '..i18n("flow_details.reach_connection_label")..'</span>'
elseif ((value >= 0) and (value < 50.0)) then
ret_bar = '<span class="badge bg-danger">'..value..' '..i18n("flow_details.not_recommended_label")..'</span>'
end
return ret_bar
end
-- ########################################################
function SipCallStatePercentageBar(state)
-- Wireshark use different state http://wiki.wireshark.org/VoIP_calls
label_class = "bg-secondary"
if (state == "REGISTER") then
label_class = "bg-info"
end
if (state == "CALL_STARTED") then
label_class = "bg-info"
end
if (state == "CALL_IN_PROGRESS") then
label_class = "bg-progress"
end
if (state == "CALL_COMPLETED") then
label_class = "bg-success"
end
if (state == "CALL_ERROR") then
label_class = "bg-danger"
end
if (state == "CALL_CANCELED") then
label_class = "bg-warning"
end
if (state == "UNKNOWN") then
label_class = "bg-warning"
end
print('<span class="badge '..label_class..'">'..state..'</span>')
end
-- ######################################
-- RTP functions
-- ######################################
function printSyncSourceFields ()
print [[
var sync_source_id_tr = document.getElementById('sync_source_id_tr').style;
if( rsp["rtp.sync_source_id"] && (rsp["rtp.sync_source_id"] != "") ){
$('#sync_source_id').html(rsp["rtp.sync_source_id"]);
sync_source_id_tr.display = 'table-row';
} else {
$('#sync_source_id').html("");
sync_source_id_tr.display = 'none';
}
]]
end
-- ######################################
function printFirstLastFlowSequenceFields ()
print [[
var first_last_flow_sequence_id_tr = document.getElementById('first_last_flow_sequence_id_tr').style;
if( (rsp["rtp.first_flow_sequence"] && (rsp["rtp.first_flow_sequence"] != "")) ||
(rsp["rtp.last_flow_sequence"] && (rsp["rtp.last_flow_sequence"] != ""))){
first_last_flow_sequence_id_tr.display = 'table-row';
}
if( rsp["rtp.first_flow_sequence"] && (rsp["rtp.first_flow_sequence"] != "") ){
$('#first_flow_sequence').html(rsp["rtp.first_flow_sequence"]);
} else {
$('#first_flow_sequence').html("-");
}
if( rsp["rtp.last_flow_sequence"] && (rsp["rtp.last_flow_sequence"] != "") ){
$('#last_flow_sequence').html(rsp["rtp.last_flow_sequence"]);
} else {
$('#last_flow_sequence').html("-");
}
]]
end
-- ######################################
function printJitterFields ()
print [[
var jitter_id_tr = document.getElementById('jitter_id_tr').style;
if( (rsp["rtp.jitter_in"] && (rsp["rtp.jitter_in"] != "")) ||
(rsp["rtp.jitter_out"] && (rsp["rtp.jitter_out"] != ""))){
jitter_id_tr.display = 'table-row';
}
if( rsp["rtp.jitter_in"] && (rsp["rtp.jitter_in"] != "") ){
$('#jitter_in').html(rsp["rtp.jitter_in"]+" ms");
if(jitter_in_trend){
if(rsp["rtp.jitter_in"] > jitter_in_trend){
$('#jitter_in_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.jitter_in"] < jitter_in_trend){
$('#jitter_in_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#jitter_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#jitter_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
jitter_in_trend = rsp["rtp.jitter_in"];
} else {
$('#jitter_in').html("-");
$('#jitter_in_trend').html("");
}
if( rsp["rtp.jitter_out"] && (rsp["rtp.jitter_out"] != "") ){
$('#jitter_out').html(rsp["rtp.jitter_out"]+" ms");
if(jitter_out_trend){
if(rsp["rtp.jitter_out"] > jitter_out_trend){
$('#jitter_out_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.jitter_out"] < jitter_out_trend){
$('#jitter_out_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#jitter_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#jitter_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#jitter_out').html("-");
$('#jitter_out_trend').html("");
}
jitter_out_trend = rsp["rtp.jitter_out"];
]]
end
-- ######################################
function printPacketLostFields ()
print [[
var rtp_packet_loss_id_tr = document.getElementById('rtp_packet_loss_id_tr').style;
if( (rsp["rtp.packet_lost_in"] && (rsp["rtp.packet_lost_in"] != "")) ||
(rsp["rtp.packet_lost_out"] && (rsp["rtp.packet_lost_out"] != ""))){
rtp_packet_loss_id_tr.display = 'table-row';
}
if( rsp["rtp.packet_lost_in"] && (rsp["rtp.packet_lost_in"] != "") ){
$('#packet_lost_in').html(NtopUtils.formatPackets(rsp["rtp.packet_lost_in"]));
if(packet_lost_in_trend){
if(rsp["rtp.packet_lost_in"] > packet_lost_in_trend){
$('#packet_lost_in_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else {
$('#packet_lost_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#packet_lost_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#packet_lost_in').html("-");
$('#packet_lost_in_trend').html("");
}
packet_lost_in_trend = rsp["rtp.packet_lost_in"];
if( rsp["rtp.packet_lost_out"] && (rsp["rtp.packet_lost_out"] != "") ){
$('#packet_lost_out').html(NtopUtils.formatPackets(rsp["rtp.packet_lost_out"]));
if(packet_lost_out_trend){
if(rsp["rtp.packet_lost_out"] > packet_lost_out_trend){
$('#packet_lost_out_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else {
$('#packet_lost_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#packet_lost_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#packet_lost_out').html("-");
$('#packet_lost_out_trend').html("");
}
packet_lost_out_trend = rsp["rtp.packet_lost_out"];
]]
end
-- ######################################
function printPacketDropFields ()
print [[
var packet_drop_id_tr = document.getElementById('packet_drop_id_tr').style;
if( (rsp["rtp.packet_drop_in"] && (rsp["rtp.packet_drop_in"] != "")) ||
(rsp["rtp.packet_drop_out"] && (rsp["rtp.packet_drop_out"] != ""))){
packet_drop_id_tr.display = 'table-row';
}
if( rsp["rtp.packet_drop_in"] && (rsp["rtp.packet_drop_in"] != "") ){
$('#packet_drop_in').html(NtopUtils.formatPackets(rsp["rtp.packet_drop_in"]));
if(packet_drop_in_trend){
if(rsp["rtp.packet_drop_in"] > packet_drop_in_trend){
$('#packet_drop_in_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else {
$('#packet_drop_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#packet_drop_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#packet_drop_in').html("-");
$('#packet_drop_in_trend').html("");
}
packet_drop_in_trend = rsp["rtp.packet_drop_in"];
if( rsp["rtp.packet_drop_out"] && (rsp["rtp.packet_drop_out"] != "") ){
$('#packet_drop_out').html(NtopUtils.formatPackets(rsp["rtp.packet_drop_out"]));
if(packet_drop_out_trend){
if(rsp["rtp.packet_drop_out"] > packet_drop_out_trend){
$('#packet_drop_out_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else {
$('#packet_drop_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#packet_drop_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#packet_drop_out').html("-");
$('#packet_drop_out_trend').html("");
}
packet_drop_out_trend = rsp["rtp.packet_drop_out"];
]]
end
-- ######################################
function printPayloadTypeInOutFields ()
print [[
var payload_id_tr = document.getElementById('payload_id_tr').style;
if( (rsp["rtp.payload_type_in"] && (rsp["rtp.payload_type_in"] != "")) ||
(rsp["rtp.payload_type_out"] && (rsp["rtp.payload_type_out"] != ""))){
payload_id_tr.display = 'table-row';
}
if( rsp["rtp.payload_type_in"] && (rsp["rtp.payload_type_in"] != "") ){
$('#payload_type_in').html(rsp["rtp.payload_type_in"]);
} else {
$('#payload_type_in').html("-");
}
if( rsp["rtp.payload_type_out"] && (rsp["rtp.payload_type_out"] != "") ){
$('#payload_type_out').html(rsp["rtp.payload_type_in"]);
} else {
$('#payload_type_out').html("-");
}
]]
end
-- ######################################
function printDeltaTimeInOutFields ()
print [[
var delta_time_id_tr = document.getElementById('delta_time_id_tr').style;
if( (rsp["rtp.max_delta_time_in"] && (rsp["rtp.max_delta_time_in"] != "")) ||
(rsp["rtp.max_delta_time_out"] && (rsp["rtp.max_delta_time_out"] != ""))){
delta_time_id_tr.display = 'table-row';
}
if( rsp["rtp.max_delta_time_in"] && (rsp["rtp.max_delta_time_in"] != "") ){
$('#max_delta_time_in').html(rsp["rtp.max_delta_time_in"]+" ms");
if(max_delta_time_in_trend){
if(rsp["rtp.max_delta_time_in"] > max_delta_time_in_trend){
$('#max_delta_time_in_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.max_delta_time_in"] < max_delta_time_in_trend){
$('#max_delta_time_in_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#max_delta_time_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#max_delta_time_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#max_delta_time_in').html("-");
$('#max_delta_time_in_trend').html("");
}
max_delta_time_in_trend = rsp["rtp.max_delta_time_in"];
if( rsp["rtp.max_delta_time_out"] && (rsp["rtp.max_delta_time_out"] != "") ){
$('#max_delta_time_out').html(rsp["rtp.max_delta_time_out"]+" ms");
if(max_delta_time_out_trend){
if(rsp["rtp.max_delta_time_out"] > max_delta_time_out_trend){
$('#max_delta_time_out_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.max_delta_time_out"] < max_delta_time_out_trend){
$('#max_delta_time_out_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#max_delta_time_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#max_delta_time_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#max_delta_time_out').html("-");
$('#max_delta_time_out_trend').html("");
}
max_delta_time_out_trend = rsp["rtp.max_delta_time_out"];
]]
end
-- ######################################
function printSipCallIdFields ()
print [[
var sip_call_id_tr = document.getElementById('sip_call_id_tr').style;
if( rsp["rtp.rtp_sip_call_id"] && (rsp["rtp.rtp_sip_call_id"] != "")){
sip_call_id_tr.display = 'table-row';
$('#rtp_sip_call_id').html(rsp["rtp.rtp_sip_call_id"]);
} else {
$('#rtp_sip_call_id').html("-");
}
]]
end
-- ######################################
function printQualityAverageFields ()
print [[
var quality_average_id_tr = document.getElementById('quality_average_id_tr').style;
if( (rsp["rtp.mos_average"] && (rsp["rtp.mos_average"] != "")) ||
(rsp["rtp.r_factor_average"] && (rsp["rtp.r_factor_average"] != "")) ){
quality_average_id_tr.display = 'table-row';
}
if( (rsp["rtp.mos_average"] && (rsp["rtp.mos_average"] != "")) || (rsp["rtp.r_factor_average"] && (rsp["rtp.r_factor_average"] != ""))){
if( rsp["rtp.mos_average"] && (rsp["rtp.mos_average"] != "")) {
if( rsp["rtp.mos_average"] < 2) {
$('#mos_average_signal').html("<i class='fas fa-signal' style='color:red'></i> ");
}
if ( (rsp["rtp.mos_average"] > 2) && (rsp["rtp.mos_average"] < 3)) {
$('#mos_average_signal').html("<i class='fas fa-signal' style='color:orange'></i> ");
}
if( rsp["rtp.mos_average"] > 3) {
$('#mos_average_signal').html("<i class='fas fa-signal' style='color:green'></i> ");
}
} else {
$('#mos_average_signal').html("<i class='fas fa-signal'></i> ");
}
} else {
$('#mos_average_signal').html("");
}
if( rsp["rtp.mos_average"] && (rsp["rtp.mos_average"] != "") ){
$('#mos_average').html(rsp["rtp.mos_average"]);
if(mos_average_trend){
if(rsp["rtp.mos_average"] > mos_average_trend){
$('#mos_average_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.mos_average"] < mos_average_trend){
$('#mos_average_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#mos_average_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#mos_average_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#mos_average').html("-");
$('#mos_average_trend').html("");
}
mos_average_trend = rsp["rtp.mos_average"];
if( rsp["rtp.mos_average"] && (rsp["rtp.mos_average"] != "") ){
$('#mos_average_slash').html(" / ");
$('#r_factor_average').html(rsp["rtp.r_factor_average"]);
if(r_factor_average_trend){
if(rsp["rtp.r_factor_average"] > r_factor_average_trend){
$('#r_factor_average_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.r_factor_average"] < r_factor_average_trend){
$('#r_factor_average_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#r_factor_average_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#r_factor_average_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#mos_average_slash').html("");
$('#r_factor_average').html("");
$('#r_factor_average_trend').html("");
}
r_factor_average_trend = rsp["rtp.r_factor_average"];
]]
end
-- ######################################
function printQualityMosFields ()
print [[
var quality_mos_id_tr = document.getElementById('quality_mos_id_tr').style;
if( (rsp["rtp.mos_in"] && (rsp["rtp.mos_in"] != "")) ||
(rsp["rtp.r_factor_in"] && (rsp["rtp.r_factor_in"] != "")) ||
(rsp["rtp.mos_out"] && (rsp["rtp.mos_out"] != "")) ||
(rsp["rtp.r_factor_out"] && (rsp["rtp.r_factor_out"] != "")) ){
quality_mos_id_tr.display = 'table-row';
}
if( (rsp["rtp.mos_in"] && (rsp["rtp.mos_in"] != "")) || (rsp["rtp.r_factor_in"] && (rsp["rtp.r_factor_in"] != ""))){
if( rsp["rtp.mos_in"] && (rsp["rtp.mos_in"] != "")) {
if( rsp["rtp.mos_in"] < 2) {
$('#mos_in_signal').html("<i class='fas fa-signal' style='color:red'></i> ");
}
if ( (rsp["rtp.mos_in"] > 2) && (rsp["rtp.mos_in"] < 3)) {
$('#mos_in_signal').html("<i class='fas fa-signal' style='color:orange'></i> ");
}
if( rsp["rtp.mos_in"] > 3) {
$('#mos_in_signal').html("<i class='fas fa-signal' style='color:green'></i> ");
}
} else {
$('#mos_in_signal').html("<i class='fas fa-signal'></i> ");
}
} else {
$('#mos_in_signal').html("-");
}
if( rsp["rtp.mos_in"] && (rsp["rtp.mos_in"] != "") ){
$('#mos_in').html(rsp["rtp.mos_in"]);
if(mos_in_trend){
if(rsp["rtp.mos_in"] > mos_in_trend){
$('#mos_in_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.mos_in"] < mos_in_trend){
$('#mos_in_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#mos_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#mos_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#mos_in').html("-");
$('#mos_in_trend').html("");
}
mos_in_trend = rsp["rtp.mos_in"];
if( rsp["rtp.r_factor_in"] && (rsp["rtp.r_factor_in"] != "") ){
$('#mos_in_slash').html(" / ");
$('#r_factor_in').html(rsp["rtp.r_factor_in"]);
if(r_factor_in_trend){
if(rsp["rtp.r_factor_in"] > r_factor_in_trend){
$('#r_factor_in_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.r_factor_in"] < r_factor_in_trend){
$('#r_factor_in_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#r_factor_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#r_factor_in_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#mos_in_slash').html("");
$('#r_factor_in').html("");
$('#r_factor_in_trend').html("");
}
r_factor_in_trend = rsp["rtp.r_factor_in"];
if( (rsp["rtp.mos_out"] && (rsp["rtp.mos_out"] != "")) || (rsp["rtp.r_factor_out"] && (rsp["rtp.r_factor_out"] != ""))){
if( rsp["rtp.mos_out"] && (rsp["rtp.mos_out"] != "")) {
if( rsp["rtp.mos_out_signal"] < 2) {
$('#mos_out_signal').html("<i class='fas fa-signal' style='color:red'></i> ");
}
if ( (rsp["rtp.mos_out_signal"] > 2) && (rsp["rtp.mos_out_signal"] < 3)) {
$('#mos_out_signal').html("<i class='fas fa-signal' style='color:orange'></i> ");
}
if( rsp["rtp.mos_out_signal"] > 3) {
$('#mos_out_signal').html("<i class='fas fa-signal' style='color:green'></i> ");
}
} else {
$('#mos_out_signal').html("<i class='fas fa-signal'></i> ");
}
} else {
$('#mos_out_signal').html("-");
}
if( rsp["rtp.mos_out"] && (rsp["rtp.mos_out"] != "") ){
$('#mos_out').html(rsp["rtp.mos_out"]);
if(mos_out_trend){
if(rsp["rtp.mos_out"] > mos_out_trend){
$('#mos_out_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.mos_out"] < mos_out_trend){
$('#mos_out_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#mos_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#mos_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#mos_out').html("-");
$('#mos_out_trend').html("");
}
mos_out_trend = rsp["rtp.mos_out"];
if( rsp["rtp.r_factor_out"] && (rsp["rtp.r_factor_out"] != "") ){
$('#mos_out_slash').html(" / ");
$('#r_factor_out').html(rsp["rtp.r_factor_out"]);
if(r_factor_out_trend){
if(rsp["rtp.r_factor_out"] > r_factor_out_trend){
$('#r_factor_out_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.r_factor_out"] < r_factor_out_trend){
$('#r_factor_out_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#r_factor_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#r_factor_out_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#mos_out_slash').html("");
$('#r_factor_out').html("");
$('#r_factor_out_trend').html("");
}
r_factor_out_trend = rsp["rtp.r_factor_out"];
]]
end
-- ######################################
function printTransitIFields ()
print [[
var rtp_transit_id_tr = document.getElementById('rtp_transit_id_tr').style;
if( (rsp["rtp.rtp_transit_in"] && (rsp["rtp.rtp_transit_in"] != "")) ||
(rsp["rtp.rtp_transit_out"] && (rsp["rtp.rtp_transit_out"] != "")) ){
rtp_transit_id_tr.display = 'table-row';
}
if( rsp["rtp.rtp_transit_in"] && (rsp["rtp.rtp_transit_in"] != "") ){
$('#rtp_transit_in').html(rsp["rtp.rtp_transit_in"]);
} else {
$('#rtp_transit_in').html("-");
}
if( rsp["rtp.rtp_transit_out"] && (rsp["rtp.rtp_transit_out"] != "") ){
$('#rtp_transit_out').html(rsp["rtp.rtp_transit_out"]);
} else {
$('#rtp_transit_out').html("-");
}
]]
end
-- ######################################
function printRrtFields ()
print [[
var rtt_id_tr = document.getElementById('rtt_id_tr').style;
if( rsp["rtp.rtp_rtt"] && (rsp["rtp.rtp_rtt"] != "")){
rtt_id_tr.display = 'table-row';
}
if( rsp["rtp.rtp_rtt"] && (rsp["rtp.rtp_rtt"] != "") ){
$('#rtp_rtt').html(rsp["rtp.rtp_rtt"]+ " ms");
if(rtp_rtt_trend){
if(rsp["rtp.rtp_rtt"] > rtp_rtt_trend){
$('#rtp_rtt_trend').html("<i class=\"fas fa-arrow-up\"></i>");
} else if(rsp["rtp.rtp_rtt"] < rtp_rtt_trend){
$('#rtp_rtt_trend').html("<i class=\"fas fa-arrow-down\"></i>");
} else {
$('#rtp_rtt_trend').html("<i class=\"fas fa-minus\"></i>");
}
}else{
$('#rtp_rtt_trend').html("<i class=\"fas fa-minus\"></i>");
}
} else {
$('#rtp_rtt').html("-");
$('#rtp_rtt_trend').html("");
}
rtp_rtt_trend = rsp["rtp.rtp_rtt"];
]]
end
-- ######################################
function printDtmfFields ()
print [[
var dtmf_id_tr = document.getElementById('dtmf_id_tr').style;
if( (rsp["rtp.rtp_transit_in"] && (rsp["rtp.rtp_transit_in"] != "")) ||
(rsp["rtp.rtp_transit_out"] && (rsp["rtp.rtp_transit_out"] != "")) ){
dtmf_id_tr.display = 'table-row';
}
if( rsp["rtp.dtmf_tones"] && (rsp["rtp.dtmf_tones"] != "") ){
$('#dtmf_tones').html(rsp["rtp.dtmf_tones"]);
} else {
$('#dtmf_tones').html("-");
}
]]
end
-- ######################################
function updatePrintRtp ()
printFirstLastFlowSequenceFields()
printJitterFields()
printPacketLostFields()
printPacketDropFields()
printPayloadTypeInOutFields()
printDeltaTimeInOutFields()
printSipCallIdFields()
printTransitIFields()
printRrtFields()
printDtmfFields()
print [[
]]
end
-- ######################################
-- SIP functions
-- ######################################
function printCallIdFields ()
print[[
var call_id_tr = document.getElementById('call_id_tr').style;
if( rsp["sip.call_id"] && (rsp["sip.call_id"] != "") ){
$('#call_id').html(rsp["sip.call_id"]);
call_id_tr.display = 'table-row';
} else {
$('#call_id').html("-");
}
]]
end
-- ######################################
function printCalledCallingFields ()
print[[
var called_calling_tr = document.getElementById('called_calling_tr').style;
if( rsp["sip.calling_called_party"] && (rsp["sip.calling_called_party"] != "") ){
$('#calling_called_party').html(rsp["sip.calling_called_party"]);
called_calling_tr.display = 'table-row';
} else {
$('#calling_called_party').html("");
called_calling_tr.display = 'none';
}
]]
end
-- ######################################
function printCodecsFields ()
print[[
var rtp_codecs_tr = document.getElementById('rtp_codecs_tr').style;
if( rsp["sip.rtp_codecs"] && (rsp["sip.rtp_codecs"] != "") ){
$('#rtp_codecs').html(rsp["sip.rtp_codecs"]);
rtp_codecs_tr.display = 'table-row';
} else {
$('#rtp_codecs').html("");
rtp_codecs_tr.display = 'none';
}
]]
end
-- ######################################
function printInviteFields ()
print[[
var invite_time_tr = document.getElementById('invite_time_tr').style;
if( rsp["sip.time_invite"] && (rsp["sip.time_invite"] != "") ){
$('#time_invite').html(rsp["sip.time_invite"]);
invite_time_tr.display = 'table-row';
} else {
$('#time_invite').html("");
invite_time_tr.display = 'none';
}
]]
end
-- ######################################
function printTryingTimeFields ()
print[[
var trying_time_tr = document.getElementById('trying_time_tr').style;
if( rsp["sip.time_trying"] && (rsp["sip.time_trying"] != "") ){
$('#time_trying').html(rsp["sip.time_trying"]);
trying_time_tr.display = 'table-row';
} else {
$('#time_trying').html("");
trying_time_tr.display = 'none';
}
]]
end
-- ######################################
function printRingingTimeFields ()
print[[
var ringing_time_tr = document.getElementById('ringing_time_tr').style;
if( rsp["sip.time_ringing"] && (rsp["sip.time_ringing"] != "") ){
$('#time_ringing').html(rsp["sip.time_ringing"]);
ringing_time_tr.display = 'table-row';
} else {
$('#time_ringing').html("");
ringing_time_tr.display = 'none';
}
]]
end
-- ######################################
function printInviteOkFailureTimeFields ()
print[[
if( rsp["sip.time_invite_ok"] && (rsp["sip.time_invite_ok"] != "") ){
$('#time_invite_ok').html(rsp["sip.time_invite_ok"]);
} else {
$('#time_invite_ok').html("");
}
if( rsp["sip.time_invite_failure"] && (rsp["sip.time_invite_failure"] != "") ){
$('#time_invite_failure').html(rsp["sip.time_invite_failure"]);
} else {
$('#time_invite_failure').html("");
}
var invite_ok_tr = document.getElementById('invite_ok_tr').style;
if ( (rsp["sip.time_invite_ok"] && (rsp["sip.time_invite_ok"] != "")) || (rsp["sip.time_invite_failure"] && (rsp["sip.time_invite_failure"] != "")) )
invite_ok_tr.display = 'table-row';
else
invite_ok_tr.display = 'none';
]]
end
-- ######################################
function printByeByeOkTimeFields ()
print[[
if( rsp["sip.time_bye"] && (rsp["sip.time_bye"] != "") ){
$('#time_bye').html(rsp["sip.time_bye"]);
} else {
$('#time_bye').html("");
}
if( rsp["sip.time_bye_ok"] && (rsp["sip.time_bye_ok"] != "") ){
$('#time_bye_ok').html(rsp["sip.time_bye_ok"]);
} else {
$('#time_bye_ok').html("");
}
var time_bye_tr = document.getElementById('time_bye_tr').style;
if ( (rsp["sip.time_bye"] && (rsp["sip.time_bye"] != "")) || (rsp["sip.time_bye_ok"] && (rsp["sip.time_bye_ok"] != "")) )
time_bye_tr.display = 'table-row';
else
time_bye_tr.display = 'none';
]]
end
-- ######################################
function printCancelCancelOkTimeFields ()
print[[
if( rsp["sip.time_cancel"] && (rsp["sip.time_cancel"] != "") ){
$('#time_cancel').html(rsp["sip.time_cancel"]);
} else {
$('#time_cancel').html("");
}
if( rsp["sip.time_cancel_ok"] && (rsp["sip.time_cancel_ok"] != "") ){
$('#time_cancel_ok').html(rsp["sip.time_cancel_ok"]);
} else {
$('#time_cancel_ok').html("");
}
var time_failure_tr = document.getElementById('time_failure_tr').style;
if ( (rsp["sip.time_cancel"] && (rsp["sip.time_cancel"] != "")) || (rsp["sip.time_cancel_ok"] && (rsp["sip.time_cancel_ok"] != "")) )
time_failure_tr.display = 'table-row';
else
time_failure_tr.display = 'none';
]]
end
-- ######################################
function printRtpStreamFields ()
print[[
var rtp_stream_tr = document.getElementById('rtp_stream_tr').style;
if( rsp["sip.rtp_stream"] && (rsp["sip.rtp_stream"] != "") ){
$('#rtp_stream').html(rsp["sip.rtp_stream"]);
rtp_stream_tr.display = 'table-row';
} else {
$('#rtp_stream').html("");
rtp_stream_tr.display = 'none';
}
]]
end
-- ######################################
function printFailureResponseCodeFields ()
print[[
var failure_resp_code_tr = document.getElementById('failure_resp_code_tr').style;
if( rsp["sip.response_code"] && (rsp["sip.response_code"] != "") ){
$('#response_code').html(rsp["sip.response_code"]);
failure_resp_code_tr.display = 'table-row';
} else {
$('#response_code').html("");
failure_resp_code_tr.display = 'none';
}
]]
end
-- ######################################
function printCbfReasonCauseFields ()
print[[
var cbf_reason_cause_tr = document.getElementById('cbf_reason_cause_tr').style;
if( rsp["sip.reason_cause"] && (rsp["sip.reason_cause"] != "") ){
$('#reason_cause').html(rsp["sip.reason_cause"]);
cbf_reason_cause_tr.display = 'table-row';
} else {
$('#reason_cause').html("");
cbf_reason_cause_tr.display = 'none';
}
]]
end
-- ######################################
function printSipCIpFields ()
print[[
var sip_c_ip_tr = document.getElementById('sip_c_ip_tr').style;
if( rsp["sip.c_ip"] && (rsp["sip.c_ip"] != "") ){
$('#c_ip').html(rsp["sip.c_ip"]);
sip_c_ip_tr.display = 'table-row';
} else {
$('#c_ip').html("");
sip_c_ip_tr.display = 'none';
}
]]
end
-- ######################################
function printCallStateFields ()
print[[
var sip_call_state_tr = document.getElementById('sip_call_state_tr').style;
if( rsp["sip.call_state"] && (rsp["sip.call_state"] != "") ){
$('#call_state').html(rsp["sip.call_state"]);
sip_call_state_tr.display = 'table-row';
} else {
$('#call_state').html("");
sip_call_state_tr.display = 'none';
}
]]
end
-- ######################################
function updatePrintSip ()
printCallIdFields()
printCalledCallingFields()
printCodecsFields()
printInviteFields()
printTryingTimeFields()
printRingingTimeFields()
printInviteOkFailureTimeFields()
printByeByeOkTimeFields()
printCancelCancelOkTimeFields()
printRtpStreamFields()
printFailureResponseCodeFields()
printCbfReasonCauseFields()
printSipCIpFields()
printCallStateFields()
end
| gpl-3.0 |
NPLPackages/paracraft | script/apps/Aries/Creator/Game/mcml/keepwork/KpUserTag.lua | 1 | 1716 | --[[
Title: icon tag for user
Author(s): leio
Date: 2020/8/10
Desc:
Use Lib:
-------------------------------------------------------
local KpUserTag = NPL.load("(gl)script/apps/Aries/Creator/Game/mcml/keepwork/KpUserTag.lua");
--]]
local KpUserTag = NPL.export();
function KpUserTag.Is_crown(user_info)
return user_info.vip == 1;
end
function KpUserTag.Is_student(user_info)
return user_info.student == 1;
end
function KpUserTag.Is_teacher(user_info)
return user_info.tLevel == 1;
end
function KpUserTag.GetMcml(user_info)
if(not user_info)then
return
end
local s = "";
local crown_tag = "";
local s_tag = "";
local t_tag = "";
if(KpUserTag.Is_crown(user_info))then
crown_tag = [[
<div style="float:left" >
<img tooltip="<%=L('Paracraft 会员')%>" style="width:18px;height:18px;background:url(Texture/Aries/Creator/keepwork/UserInfo/crown_32bits.png#0 0 18 18)"/>
</div>
]]
end
if(KpUserTag.Is_student(user_info))then
s_tag = [[
<div style="float:left;margin-left:2px;">
<img tooltip="<%=L('合作机构vip学员')%>" style="width:18px;height:18px;background:url(Texture/Aries/Creator/keepwork/UserInfo/V_32bits.png#0 0 18 18)"/>
</div>
]]
end
if(KpUserTag.Is_teacher(user_info))then
t_tag = [[
<div style="float:left;margin-left:2px;">
<img tooltip="<%=L('合作机构vip教师')%>" style="width:18px;height:18px;background:url(Texture/Aries/Creator/keepwork/UserInfo/blue_v_32bits.png#0 0 18 18)"/>
</div>
]]
s_tag = "";
end
s = string.format("%s%s%s",crown_tag,s_tag,t_tag);
return s;
end
| gpl-2.0 |
abasshacker/abbasgh | plugins/spammer.lua | 86 | 65983 | local function run(msg)
if msg.text == "[!/]killwili" then
return "".. [[
kose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nkose nanat hack shod left bede\nv
]]
end
end
return {
description = "Spamms the group fastly",
usage = "!fuck or Fuckgp or Fuck : send 10000 Spams to the group",
patterns = {
"^[!/]fuck$",
"^fuckgp$",
"^Fuck$",
"^spam$",
"^Fuckgp$",
},
run = run,
privileged = true,
pre_process = pre_process
}
| gpl-2.0 |
LuaDist2/zee | zee/main.lua | 1 | 4772 | -- Program invocation, startup and shutdown
--
-- Copyright (c) 2010-2015 Free Software Foundation, Inc.
--
-- This file is part of Zee.
--
-- This program is free software; you can redistribute it and/or modify it
-- under the terms of the GNU General Public License as published by
-- the Free Software Foundation; either version 3, or (at your option)
-- any later version.
--
-- This program is distributed in the hope that it will be useful, but
-- WITHOUT ANY WARRANTY; without even the implied warranty of
-- MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
-- General Public License for more details.
--
-- You should have received a copy of the GNU General Public License
-- along with this program. If not, see <http://www.gnu.org/licenses/>.
-- Derived constants
VERSION_STRING = PACKAGE_NAME .. " " .. VERSION
local COPYRIGHT_STRING = ""
local program_name = posix.basename (arg[0] or PACKAGE)
spec = program_name .. " " .. VERSION .. [[
Copyright (C) 2015 Free Software Foundation, Inc.
]] .. PACKAGE_NAME .. " comes with ABSOLUTELY NO WARRANTY." .. [[
You may redistribute copies of ]] .. PACKAGE_NAME .. [[
under the terms of the GNU General Public License.
For more information about these matters, see the file named COPYING.
Usage: ]] .. program_name .. [[
An editor.
Exit status is 0 if OK, 1 if it cannot start up, for example because
of an invalid command-line argument, and 2 if it crashes or runs out
of memory.
~/.]] .. PACKAGE .. [[ is the user init file
-q, --no-init-file do not load ~/.]] .. PACKAGE .. [[
-e, --eval=CHUNK evaluate Lua chunk CHUNK
-n, --line=LINE start editing at line LINE
--version display version information, then exit
--help display this help, then exit
Please report bugs at ]] .. PACKAGE_BUGREPORT .. [[
]]
-- -b, --batch run non-interactively
-- Runtime constants
-- Display attributes
display = {}
-- Keyboard handling
GETKEY_DEFAULT = -1
GETKEY_DELAYED = 2000
-- Global flags, stored in thisflag and lastflag.
-- need_resync: a resync is required.
-- quit: the user has asked to quit.
-- defining_macro: we are defining a macro.
-- The current window
win = nil
-- The current buffer
buf = nil
-- The global editor flags.
thisflag = {}
lastflag = {}
local function segv_sig_handler (signo)
io.stderr:write (prog.name .. ": " .. PACKAGE_NAME ..
" crashed. Please send a bug report to <" ..
PACKAGE_BUGREPORT .. ">.\r\n")
editor_exit (true)
end
local function other_sig_handler (signo)
local msg = progran_name .. ": terminated with signal " .. signo .. ".\n" .. debug.traceback ()
io.stderr:write (msg:gsub ("\n", "\r\n"))
editor_exit (false)
end
local function signal_init ()
-- Set up signal handling
posix.signal(posix.SIGSEGV, segv_sig_handler)
posix.signal(posix.SIGBUS, segv_sig_handler)
posix.signal(posix.SIGHUP, other_sig_handler)
posix.signal(posix.SIGINT, other_sig_handler)
posix.signal(posix.SIGTERM, other_sig_handler)
end
function main ()
signal_init ()
local OptionParser = require "std.optparse"
local parser = OptionParser (spec)
_G.arg, _G.opts = parser:parse (_G.arg)
if #arg ~= 1 and not (#arg == 0 and opts.eval) then
parser:opterr ("Need a file or expression")
end
os.setlocale ("")
win = {}
local w, h = term_width (), term_height ()
win = {topdelta = 0, start_column = 0, last_line = 0}
win.fwidth = 2
term_init ()
resize_window ()
if not opts.no_init_file then
local s = os.getenv ("HOME")
if s then
execute_command ("load", s .. "/." .. PACKAGE)
end
end
-- Load file
local ok = true
if #arg == 1 then
ok = not read_file (arg[1])
if ok then
execute_command ("move-goto-line", opts.line or 1)
end
end
-- Evaluate Lua chunks given on the command line.
if type (opts.eval) == "string" then -- If only one argument, put it in a table
opts.eval = {opts.eval}
end
for _, c in ipairs (opts.eval or {}) do
if execute_command ("eval", c) then
break
end
if thisflag.quit then
break
end
end
if ok and #arg == 1 then
lastflag.need_resync = true
-- Refresh minibuffer in case there's a pending error message.
minibuf_refresh ()
-- Leave cursor in correct position.
term_redraw_cursor ()
-- Run the main loop.
while not thisflag.quit do
if lastflag.need_resync then
window_resync (win)
end
get_and_run_command ()
end
end
-- Tidy and close the terminal.
term_finish ()
-- Print any error message.
if not ok then
io.stderr:write (minibuf_contents .. "\n")
end
-- FIXME: Add startup banner (how to quit and get menu)
end
| gpl-3.0 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.