content stringlengths 5 1.05M |
|---|
NPC.Class = "npc_fastzombie"
NPC.Name = translate.Get("npc_class_banshee")
NPC.Description = translate.Get("npc_description_banshee")
NPC.Icon = "VGUI/zombies/info_banshee"
NPC.IsEngineNPC = true
NPC.Flag = FL_SPAWN_BANSHEE_ALLOWED
NPC.Cost = GetConVar("zm_cost_banshee"):GetInt()
NPC.PopCost = GetConVar("zm_popcost_banshee"):GetInt()
NPC.Health = GetConVar("zm_fastzombie_health"):GetInt()
NPC.Model = "models/zombie/zm_fast.mdl"
NPC.DelaySetModel = true |
-- Decompiled using luadec 2.2 rev: for Lua 5.2 from https://github.com/viruscamp/luadec
-- Command line: A:\Steam\twd-definitive\scripteditor-10-31-20\definitive_lighting_improvements\WDC_pc_WalkingDead201_data\NextTimeOn_temp.lua
-- params : ...
-- function num : 0 , upvalues : _ENV
local kScript = "NextTimeOn"
local kScene = "adv_nextTimeOn201"
NextTimeOn = function()
-- function num : 0_0 , upvalues : _ENV, kScene, kScript
Game_NewScene(kScene, kScript)
Navigate_Enable(false)
if Platform_NeedShaderPreload() then
RenderPreloadShader("SceneToonOutline2_CC_TINT_QLo.t3fxb", "64")
RenderPreloadShader("Mesh_DTL_CC_TINT_SDTL_QLo.t3fxb", "67")
RenderPreloadShader("Mesh_CC_TINT_QLo.t3fxb", "323")
RenderPreloadShader("Mesh_LGT_CC_TINT_QLo.t3fxb", "324")
RenderPreloadShader("Mesh_CC_TINT_QLo.t3fxb", "195")
RenderPreloadShader("Mesh_LGT_VCOL_CC_TINT_QLo.t3fxb", "324")
RenderPreloadShader("Mesh_CC_TINT_QLo.t3fxb", "66")
RenderPreloadShader("Mesh_CC_TINT_QLo.t3fxb", "74")
RenderPreloadShader("Mesh_1SKN_CC_TINT_QLo.t3fxb", "74")
RenderPreloadShader("SceneToonOutline2_CC_TINT_QLo.t3fxb", "192")
RenderPreloadShader("Mesh_CC_TINT_QLo.t3fxb", "326")
RenderPreloadShader("Mesh_VCOL_CC_TINT_QLo.t3fxb", "67")
RenderPreloadShader("Mesh_1SKN_CC_TINT_QLo.t3fxb", "67")
end
Game_StartScene(true)
end
NextTimeOn_EndEpisode = function()
-- function num : 0_1 , upvalues : _ENV
WDAchievements_Unlock("achievement_07")
SaveLoad_SetEpisode("ShowEndCredits1")
Menu_EndStats(1)
Game_EndEpisode("MenuSeason2", "Menu_Main")
end
SceneOpen(kScene, kScript)
SceneAdd("ui_nextTimeOn")
|
-- Objects
local LGUI = Instance.new("ScreenGui")
local Background = Instance.new("Frame")
local Ver = Instance.new("TextLabel")
local GRAB = Instance.new("TextButton")
local styleLine = Instance.new("Frame")
local GAXE = Instance.new("TextButton")
local styleLine_2 = Instance.new("Frame")
local Title = Instance.new("TextLabel")
local styleLine_3 = Instance.new("Frame")
local CCW = Instance.new("TextButton")
local styleLine_4 = Instance.new("Frame")
local ULM = Instance.new("TextButton")
local styleLine_5 = Instance.new("Frame")
local FTR = Instance.new("TextButton")
local styleLine_6 = Instance.new("Frame")
local BTOOL = Instance.new("TextButton")
local styleLine_7 = Instance.new("Frame")
-- Properties
LGUI.Name = "LGUI"
LGUI.Parent = game.CoreGui
Background.Name = "Background"
Background.Parent = LGUI
Background.Active = true
Background.BackgroundColor3 = Color3.new(1, 1, 1)
Background.Draggable = true
Background.Position = UDim2.new(0, 0, 0, 355)
Background.Selectable = true
Background.Size = UDim2.new(0, 150, 0, 275)
Background.Style = Enum.FrameStyle.DropShadow
Ver.Name = "Ver"
Ver.Parent = Background
Ver.BackgroundColor3 = Color3.new(1, 1, 1)
Ver.BackgroundTransparency = 1
Ver.BorderSizePixel = 0
Ver.Position = UDim2.new(0, 0, 1, -15)
Ver.Size = UDim2.new(1, -6, 0, 10)
Ver.Font = Enum.Font.SourceSans
Ver.FontSize = Enum.FontSize.Size14
Ver.Text = "Version 2.0"
Ver.TextColor3 = Color3.new(1, 1, 1)
Ver.TextTransparency = 0.80000001192093
GRAB.Name = "GRAB"
GRAB.Parent = Background
GRAB.BackgroundColor3 = Color3.new(1, 1, 1)
GRAB.BackgroundTransparency = 0.5
GRAB.BorderSizePixel = 0
GRAB.Position = UDim2.new(0, 17, 0, 75)
GRAB.Size = UDim2.new(0, 100, 0, 30)
GRAB.Font = Enum.Font.SourceSansBold
GRAB.FontSize = Enum.FontSize.Size18
GRAB.Text = "Grabber"
GRAB.TextColor3 = Color3.new(0, 0, 0)
GRAB.TextTransparency = 0.5
styleLine.Name = "styleLine"
styleLine.Parent = GRAB
styleLine.BackgroundColor3 = Color3.new(1, 1, 1)
styleLine.BorderSizePixel = 0
styleLine.Size = UDim2.new(0, 5, 1, 0)
GAXE.Name = "GAXE"
GAXE.Parent = Background
GAXE.BackgroundColor3 = Color3.new(1, 1, 1)
GAXE.BackgroundTransparency = 0.5
GAXE.BorderSizePixel = 0
GAXE.Position = UDim2.new(0, 17, 0, 40)
GAXE.Size = UDim2.new(0, 100, 0, 30)
GAXE.Font = Enum.Font.SourceSansBold
GAXE.FontSize = Enum.FontSize.Size18
GAXE.Text = "Golden Axe"
GAXE.TextColor3 = Color3.new(0, 0, 0)
GAXE.TextTransparency = 0.5
styleLine_2.Name = "styleLine"
styleLine_2.Parent = GAXE
styleLine_2.BackgroundColor3 = Color3.new(1, 1, 1)
styleLine_2.BorderSizePixel = 0
styleLine_2.Size = UDim2.new(0, 5, 1, 0)
Title.Name = "Title"
Title.Parent = Background
Title.BackgroundColor3 = Color3.new(1, 1, 1)
Title.BorderSizePixel = 0
Title.Position = UDim2.new(0, -2, 0, -2)
Title.Size = UDim2.new(1, 4, 0, 32)
Title.Font = Enum.Font.SourceSansBold
Title.FontSize = Enum.FontSize.Size24
Title.Text = "LumberGui"
Title.TextColor3 = Color3.new(0, 0, 0)
Title.TextXAlignment = Enum.TextXAlignment.Left
styleLine_3.Name = "styleLine"
styleLine_3.Parent = Title
styleLine_3.BackgroundColor3 = Color3.new(0, 0, 0)
styleLine_3.BackgroundTransparency = 0.30000001192093
styleLine_3.BorderSizePixel = 0
styleLine_3.Position = UDim2.new(0, 0, 0, 28)
styleLine_3.Size = UDim2.new(1, 0, 0, 4)
styleLine_3.ZIndex = 2
CCW.Name = "CCW"
CCW.Parent = Background
CCW.BackgroundColor3 = Color3.new(1, 1, 1)
CCW.BackgroundTransparency = 0.5
CCW.BorderSizePixel = 0
CCW.Position = UDim2.new(0, 17, 0, 110)
CCW.Size = UDim2.new(0, 100, 0, 30)
CCW.Font = Enum.Font.SourceSansBold
CCW.FontSize = Enum.FontSize.Size14
CCW.Text = "CanCollide Water"
CCW.TextColor3 = Color3.new(0, 0, 0)
CCW.TextTransparency = 0.5
styleLine_4.Name = "styleLine"
styleLine_4.Parent = CCW
styleLine_4.BackgroundColor3 = Color3.new(1, 1, 1)
styleLine_4.BorderSizePixel = 0
styleLine_4.Size = UDim2.new(0, 5, 1, 0)
ULM.Name = "ULM"
ULM.Parent = Background
ULM.BackgroundColor3 = Color3.new(1, 1, 1)
ULM.BackgroundTransparency = 0.5
ULM.BorderSizePixel = 0
ULM.Position = UDim2.new(0, 17, 0, 145)
ULM.Size = UDim2.new(0, 100, 0, 30)
ULM.Font = Enum.Font.SourceSansBold
ULM.FontSize = Enum.FontSize.Size18
ULM.Text = "Unlock Maze"
ULM.TextColor3 = Color3.new(0, 0, 0)
ULM.TextTransparency = 0.5
styleLine_5.Name = "styleLine"
styleLine_5.Parent = ULM
styleLine_5.BackgroundColor3 = Color3.new(1, 1, 1)
styleLine_5.BorderSizePixel = 0
styleLine_5.Size = UDim2.new(0, 5, 1, 0)
FTR.Name = "FTR"
FTR.Parent = Background
FTR.BackgroundColor3 = Color3.new(1, 1, 1)
FTR.BackgroundTransparency = 0.5
FTR.BorderSizePixel = 0
FTR.Position = UDim2.new(0, 17, 0, 215)
FTR.Size = UDim2.new(0, 100, 0, 30)
FTR.Font = Enum.Font.SourceSansBold
FTR.FontSize = Enum.FontSize.Size18
FTR.Text = "Truck speed"
FTR.TextColor3 = Color3.new(0, 0, 0)
FTR.TextTransparency = 0.5
styleLine_6.Name = "styleLine"
styleLine_6.Parent = FTR
styleLine_6.BackgroundColor3 = Color3.new(1, 1, 1)
styleLine_6.BorderSizePixel = 0
styleLine_6.Size = UDim2.new(0, 5, 1, 0)
BTOOL.Name = "BTOOL"
BTOOL.Parent = Background
BTOOL.BackgroundColor3 = Color3.new(1, 1, 1)
BTOOL.BackgroundTransparency = 0.5
BTOOL.BorderSizePixel = 0
BTOOL.Position = UDim2.new(0, 17, 0, 180)
BTOOL.Size = UDim2.new(0, 100, 0, 30)
BTOOL.Font = Enum.Font.SourceSansBold
BTOOL.FontSize = Enum.FontSize.Size18
BTOOL.Text = "BTools"
BTOOL.TextColor3 = Color3.new(0, 0, 0)
BTOOL.TextTransparency = 0.5
styleLine_7.Name = "styleLine"
styleLine_7.Parent = BTOOL
styleLine_7.BackgroundColor3 = Color3.new(1, 1, 1)
styleLine_7.BorderSizePixel = 0
styleLine_7.Size = UDim2.new(0, 5, 1, 0)
game.Players.LocalPlayer:GetMouse().KeyDown:connect(function(m)
if m == 'q' then
Background:TweenPosition(UDim2.new(0,-150,0,355) , "Out", "Quad", 1, true)
end
end)
game.Players.LocalPlayer:GetMouse().KeyDown:connect(function(m)
if m == 'e' then
Background:TweenPosition(UDim2.new(0,0,0,355) , "Out", "Quad", 1, true)
end
end)
BTOOL.MouseButton1Down:connect(function()
lp = game.Players.LocalPlayer
local a,b,c = Instance.new("HopperBin", lp.Backpack),Instance.new("HopperBin", lp.Backpack),Instance.new("HopperBin", lp.Backpack)
a.BinType = 2
b.BinType = 3
c.BinType = 4
print('BTools Loaded')
end)
CCW.MouseButton1Down:connect(function()
for i,v in pairs(game.Workspace.Water:GetChildren()) do
if v:IsA("Part") then
v.CanCollide = true
end
end
print('Water CanCollided')
end)
ULM.MouseButton1Down:connect(function()
for i,v in pairs(game.Workspace.Region_MazeCave:GetChildren()) do
if v:IsA("Part") then
v.Locked = false
end
end
print('Maze Cave Unlocked')
end)
GAXE.MouseButton1Down:connect(function()
Door = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet.Model
Door1 = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet.ItemName
Door2 = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet.Price
Door3 = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet.Description
Door4 = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet.Box
Door5 = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet.AssetId
Door6 = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet.ItemName
Door7 = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet.ItemImage
Door8 = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet.AxeClass
Door9 = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet.Type
Door:Remove()
Door1:Remove()
Door2:Remove()
Door3:Remove()
Door4:Remove()
Door5:Remove()
Door6:Remove()
Door7:Remove()
Door8:Remove()
Door9:Remove()
ff = game.ReplicatedStorage.Purchasables.Tools.AllTools.BasicHatchet
tt = game.ReplicatedStorage.Purchasables.Tools.AllTools.GoldAxe
tt.Model:Clone().Parent = ff
tt.ItemName:Clone().Parent = ff
tt.Price:Clone().Parent = ff
tt.Description:Clone().Parent = ff
tt.Box:Clone().Parent = ff
tt.AssetId:Clone().Parent = ff
tt.ItemImage:Clone().Parent = ff
tt.AxeClass:Clone().Parent = ff
tt.Type:Clone().Parent = ff
print('Golden Axe Loaded')
end)
GRAB.MouseButton1Down:connect(function()
f = game.Lighting.Dragger:Clone()
f.Parent = game.Players.LocalPlayer.Backpack
print('Grabber Loaded')
end)
FTR.MouseButton1Down:connect(function()
game.Workspace.PlayerModels.ChildAdded:connect(function(ADDED)
wait(0.5)
if ADDED:FindFirstChild('Configuration') then
if ADDED.Configuration:FindFirstChild('MaxSpeed') then
ADDED.Configuration.MaxSpeed.Value = 5
print('Truck speed hack Loaded')
end
end
end)
end) |
function Rowtransfer(use_cuda)
local model = nn.Sequential()
model:add(nn.SplitTable(1, 3)) -- #H list of (batch_size, W, 512)
return model
end
--(batch_size, H, W, 512)
function Coltransfer(use_cuda)
local model = nn.Sequential()
model:add(nn.SplitTable(2, 3)) -- #W list of (batch_size, W, 512)
return model
end
|
--- Helper class for ScreenCover
-- @classmod ScreenCoverBuilder
local ScreenCoverBuilder = {}
ScreenCoverBuilder.__index = ScreenCoverBuilder
ScreenCoverBuilder.ClassName = "ScreenCoverBuilder"
function ScreenCoverBuilder.new(Template)
local self = setmetatable({}, ScreenCoverBuilder)
self.Template = Template or error("No Template")
return self
end
function ScreenCoverBuilder:CreateFrame()
local template = self.Template or error("No template")
local frame = Instance.new("Frame")
frame.BorderSizePixel = 0
frame.BackgroundColor3 = template.BackgroundColor3
frame.BackgroundTransparency = 0
frame.ZIndex = template.ZIndex
frame.Active = true
frame.Name = "Frame"
return frame
end
function ScreenCoverBuilder:CreateSquare(squareData)
local frame = self:CreateFrame()
frame.Name = "SquareFrame"
frame.AnchorPoint = squareData.AnchorPoint
frame.Position = squareData.Position
return frame
end
return ScreenCoverBuilder |
--工具包引入
require "kit/lv_kit"
-- 变量定义
local s_width, s_height = System.screenSize()
local blockData, tableView
local loading = LoadingIndicator()
loading.size(200, 200)
loading.alignCenter()
loading.show()
tableView = RefreshTableView {
Section = {
SectionCount = 1, -- section数量
RowCount = function(section)
if (blockData) then
return table:getn(blockData.model)
else
return 0
end
end
},
Cell = {
Id = function(section, row) -- 指定section和row对应的Cell类型唯一识别号
return "Cell1";
end,
Cell1 = {
-- cell 具体样式
Size = function(section, row)
return 600
end,
Init = function(cell, section, row) -- 初始化cell
cell.icon = Image();
cell.title = Label();
cell.info = Label();
end,
Layout = function(cell, section, row) -- cell复用时调用
if (blockData) then
cell.icon.size(s_width, 400);
cell.icon.image('http:' .. blockData.model[row].materials["brandLogoUrl"]);
cell.title.frame(0, 400, 200, 50);
cell.title.text(blockData.model[row].materials["logoText"]);
cell.info.frame(500, 400, 600, 50)
cell.info.text(blockData.model[row].materials["brandDesc"])
end
end,
Callback = {
Click = function(cell, section, row) -- 用户点击了section和row
Toast("Click-Section " .. section .. ", Row " .. row);
System.gc();
end,
LongClick= function(cell, section, row)
Toast("LongClick-Section " .. section .. ", Row " .. row);
return true;
end
}
}
},
Callback = {
PullDown = function()
-- 开始下拉刷新回调
Timer(function()
tableView.stopPullDownRefreshing()
end).start(3000);
end,
PullUp = function()
-- 开始上拉刷新回调
end
}
};
tableView.frame(0, 200, s_width, s_height - 200)
tableView.showScrollIndicator(false)
|
-- Copyright (C) 2018 Jérôme Leclercq
-- This file is part of the "Not a Bot" application
-- For conditions of distribution and use, see copyright notice in LICENSE
local bot = Bot
local client = Client
local discordia = Discordia
local enums = discordia.enums
discordia.extensions() -- load all helpful extensions
Module.Name = "channels"
function Module:GetConfigTable()
return {
{
Name = "ReactionActions",
Description = "Map explaining which role to add/remove from which reaction on which message, use the !channelconfig command to setup this",
Type = bot.ConfigType.Custom,
Default = {}
}
}
end
function Module:OnLoaded()
self:RegisterCommand({
Name = "channelconfig",
Args = {
{Name = "configMessage", Type = Bot.ConfigType.Message, Optional = true}
},
PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end,
Help = "Lists the channel module messages and reactions",
Func = function (commandMessage, configMessage)
local guild = commandMessage.guild
local config = self:GetConfig(guild)
local data = self:GetData(guild)
local channelConfig = config.ReactionActions
for channelId,messageTable in pairs(channelConfig) do
local channel = guild:getChannel(channelId)
if (channel) then
for messageId,reactionTable in pairs(messageTable) do
local message = channel:getMessage(messageId)
if (message and (not configMessage or configMessage.id == message.id)) then
local fields = {}
for emoji,actions in pairs(reactionTable) do
local actionStr = ""
if (actions.AddRoles) then
local addedRoles = {}
for _, roleId in pairs(actions.AddRoles) do
local role = guild:getRole(roleId)
if (role) then
table.insert(addedRoles, role.mentionString)
else
table.insert(addedRoles, "<invalid role " .. roleId .. ">")
end
end
if (#addedRoles > 0) then
actionStr = string.format("%s**Adds role%s** %s\n", actionStr, #addedRoles > 1 and "s" or "", table.concat(addedRoles, ", "))
end
end
if (actions.RemoveRoles) then
local removedRoles = {}
for _, roleId in pairs(actions.RemoveRoles) do
local role = guild:getRole(roleId)
if (role) then
table.insert(removedRoles, role.mentionString)
else
table.insert(removedRoles, "<invalid role " .. roleId .. ">")
end
end
if (#removedRoles > 0) then
actionStr = string.format("%s**Removes role%s** %s\n", actionStr, #removedRoles > 1 and "s" or "", table.concat(removedRoles, ", "))
end
end
if (actions.SendMessage) then
actionStr = string.format("%s**Sends private message:**\n\"%s\"\n", actionStr, actions.SendMessage)
end
local emoji = bot:GetEmojiData(guild, emoji)
table.insert(fields, {
name = string.format("- %s:", emoji and emoji.MentionString or "<invalid emoji>"),
value = actionStr
})
end
commandMessage:reply({
embed = {
description = string.format("Message in %s:\n%s", channel.mentionString, bot:GenerateMessageLink(message)),
fields = fields,
footer = {
text = "Use `!updatechannelconfig <message link> <emoji> <action>` to update channels reactions settings."
}
}
})
end
end
end
end
end
})
self:RegisterCommand({
Name = "updatechannelconfig",
Args = {
{Name = "message", Type = Bot.ConfigType.Message},
{Name = "emoji", Type = Bot.ConfigType.Emoji},
{Name = "action", Type = Bot.ConfigType.String},
{Name = "value", Type = Bot.ConfigType.String, Optional = true}
},
PrivilegeCheck = function (member) return member:hasPermission(enums.permission.administrator) end,
Help = "Configures the channel module messages and reactions",
Func = function (commandMessage, message, emoji, action, value)
local guild = commandMessage.guild
local config = self:GetConfig(guild)
local GetReactionActionsConfig = function (channelId, messageId, reaction, noCreate)
local guildConfig = config.ReactionActions
local channelTable = guildConfig[channelId]
if (not channelTable) then
if (noCreate) then
return
end
channelTable = {}
guildConfig[channelId] = channelTable
end
local messageTable = channelTable[messageId]
if (not messageTable) then
if (noCreate) then
return
end
messageTable = {}
channelTable[messageId] = messageTable
end
local reactionActions = messageTable[reaction]
if (not reactionActions) then
if (noCreate) then
return
end
reactionActions = {}
messageTable[reaction] = reactionActions
end
return reactionActions
end
local success = false
if (action == "addrole") then
local role = guild:getRole(value)
if (not role) then
commandMessage:reply(string.format("Invalid role %s", value))
return
end
local roleValue = tostring(role.id)
local reactionActions = GetReactionActionsConfig(message.channel.id, message.id, emoji.Name)
if (reactionActions.AddRoles) then
local found = false
for _, role in pairs(reactionActions.AddRoles) do
if (role == roleValue) then
found = true
break
end
end
if (reactionActions.RemoveRoles) then
for key, role in pairs(reactionActions.RemoveRoles) do
if (role == roleValue) then
table.remove(reactionActions.RemoveRoles, key)
end
end
end
if (not found) then
table.insert(reactionActions.AddRoles, tostring(role.id))
end
else
reactionActions.AddRoles = {roleValue}
end
success = true
commandMessage:reply(string.format("Reactions on %s for %s will now adds role %s (%s)", Bot:GenerateMessageLink(message), emoji.MentionString, role.name, role.id))
elseif (action == "removerole") then
local role = guild:getRole(value)
if (not role) then
commandMessage:reply(string.format("Invalid role %s", value))
return
end
local roleValue = tostring(role.id)
local reactionActions = GetReactionActionsConfig(message.channel.id, message.id, emoji.Name)
if (reactionActions.RemoveRoles) then
local found = false
for _, role in pairs(reactionActions.RemoveRoles) do
if (role == roleValue) then
found = true
break
end
end
if (reactionActions.AddRoles) then
for key, role in pairs(reactionActions.AddRoles) do
if (role == roleValue) then
table.remove(reactionActions.AddRoles, key)
end
end
end
if (not found) then
table.insert(reactionActions.RemoveRoles, tostring(role.id))
end
else
reactionActions.RemoveRoles = {roleValue}
end
success = true
commandMessage:reply(string.format("Reactions on %s for %s will now remove role %s (%s)", Bot:GenerateMessageLink(message), emoji.MentionString, role.name, role.id))
elseif (action == "send") then
if (not value) then
commandMessage:reply("Empty message")
return
end
local reactionActions = GetReactionActionsConfig(message.channel.id, message.id, emoji.Name)
reactionActions.SendMessage = value
success = true
commandMessage:reply(string.format("Reactions on %s for %s will now send private message: %s", Bot:GenerateMessageLink(message), emoji.MentionString, value))
elseif (action == "clear") then
local reactionActions = GetReactionActionsConfig(message.channel.id, message.id, emoji.Name, true)
if (reactionActions) then
reactionActions.AddRoles = nil
reactionActions.RemoveRoles = nil
reactionActions.SendMessage = nil
end
success = true
commandMessage:reply(string.format("Reactions actions on %s for %s have been cleared", Bot:GenerateMessageLink(message), emoji.MentionString))
else
commandMessage:reply("Invalid action (must be addrole/clear/removerole/send)")
end
if (success) then
self:SaveGuildConfig(guild)
commandMessage:reply(string.format("Configuration of module %s has been saved, use the `!reload %s` command to activate it", self.Name, self.Name))
end
end
})
return true
end
function Module:GetReactionActions(guild, channelId, messageId, reaction, noCreate)
local reactionKey = string.format("%s_%s_%s", channelId, messageId, reaction)
local data = self:GetData(guild)
local roleActions = data.ReactionActions[reactionKey]
if (not roleActions and not noCreate) then
roleActions = {}
roleActions.Add = {}
roleActions.Remove = {}
data.ReactionActions[reactionKey] = roleActions
end
return roleActions
end
function Module:OnEnable(guild)
local config = self:GetConfig(guild)
local data = self:GetData(guild)
data.ReactionActions = {}
--[[if (config.ChannelConfig) then
self:LogInfo(guild, "Converting old config format to new config format...")
local guildConfig = {}
for channelId,messagetable in pairs(config.ChannelConfig) do
local channelMessages = {}
guildConfig[channelId] = channelMessages
for messageId,reactionTable in pairs(messagetable) do
local messageActions = {}
channelMessages[messageId] = messageActions
for k,reactionInfo in pairs(reactionTable) do
local reactionActions = {}
messageActions[reactionInfo.reaction] = reactionActions
if (reactionInfo.roles) then
for k,roleId in pairs(reactionInfo.roles) do
if (roleId:sub(1,1) ~= "-") then
reactionActions.AddRoles = reactionActions.AddRoles or {}
table.insert(reactionActions.AddRoles, roleId)
else
roleId = roleId:sub(2)
reactionActions.RemoveRoles = reactionActions.RemoveRoles or {}
table.insert(reactionActions.RemoveRoles, roleId)
end
end
end
if (reactionInfo.message) then
reactionActions.SendMessage = reactionInfo.message
end
end
end
end
config.ReactionActions = guildConfig
config.ChannelConfig = nil
self:SaveConfig(guild)
end]]
self:LogInfo(guild, "Processing roles...")
local ProcessRole = function (channelId, messageId, reaction, roleId, remove)
if (guild:getRole(roleId)) then
local roleActions = self:GetReactionActions(guild, channelId, messageId, reaction)
if (not remove) then
table.insert(roleActions.Add, roleId)
else
table.insert(roleActions.Remove, roleId)
end
else
self:LogWarning(guild, "Role %s not found", roleId)
end
end
for channelId,messageTable in pairs(config.ReactionActions) do
for messageId,reactionTable in pairs(messageTable) do
for reaction, actions in pairs(reactionTable) do
local hasActions = false
if (actions.AddRoles) then
for _,roleId in pairs(actions.AddRoles) do
ProcessRole(channelId, messageId, reaction, roleId, false)
hasActions = true
end
end
if (actions.RemoveRoles) then
for _,roleId in pairs(actions.RemoveRoles) do
ProcessRole(channelId, messageId, reaction, roleId, true)
hasActions = true
end
end
if (actions.SendMessage) then
local roleActions = self:GetReactionActions(guild, channelId, messageId, reaction)
roleActions.Message = actions.SendMessage
hasActions = true
end
if (not hasActions) then
reactionTable[reaction] = nil
end
end
if (next(reactionTable) == nil) then
messageTable[messageId] = nil
end
end
if (next(messageTable) == nil) then
config.ReactionActions[channelId] = nil
end
end
self:LogInfo(guild, "Adding emojis to concerned messages...")
-- Make sure reactions are present on messages
for channelId,messageTable in pairs(config.ReactionActions) do
local channel = guild:getChannel(channelId)
if (channel) then
for messageId,reactionTable in pairs(messageTable) do
local message = channel:getMessage(messageId)
if (message) then
local hasReaction = {}
for k,reaction in pairs(message.reactions) do
if (reaction.me) then
local emoji = bot:GetEmojiData(guild, reaction.emojiName)
if (emoji) then
hasReaction[emoji.Name] = true
else
self:LogError(guild, "Found reaction which does not exist in guild: %s", reaction.emojiName)
end
end
end
for reaction, _ in pairs(reactionTable) do
local emoji = bot:GetEmojiData(guild, reaction)
if (emoji) then
if (not hasReaction[emoji.Name]) then
local success, err = message:addReaction(emoji.Emoji or emoji.Id)
if (not success) then
self:LogWarning(guild, "Failed to add reaction %s on message %s (channel: %s): %s", emoji.Name, message.id, message.channel.id, err)
end
end
else
self:LogError(guild, "Emoji \"%s\" does not exist", reaction.emojiName)
end
end
else
self:LogError(guild, "Message %s no longer exists in channel %s", messageId, channelId)
end
end
else
self:LogError(guild, "Channel %s no longer exists", channelId)
end
end
return true
end
function Module:HandleReactionAdd(guild, userId, channelId, messageId, reactionName)
if (client.user.id == userId) then
return
end
local roleActions = self:GetReactionActions(guild, channelId, messageId, reactionName, true)
if (not roleActions) then
return
end
local member = guild:getMember(userId)
for k,roleId in pairs(roleActions.Add) do
local role = guild:getRole(roleId)
if (role) then
self:LogInfo(guild, "Adding %s%s to %s", role.name, (role.color ~= 0) and " (colored)" or "", member.tag)
local success, err = member:addRole(roleId)
if (not success) then
self:LogWarning(guild, "Failed to add role %s to %s: %s", role.name, member.tag, err)
end
else
self:LogWarning(guild, "Role %s appears to have been removed", roleId)
end
end
for k,roleId in pairs(roleActions.Remove) do
local role = guild:getRole(roleId)
if (role) then
self:LogInfo(guild, "Removing %s%s from %s", role.name, (role.color ~= 0) and " (colored)" or "", member.tag)
local success, err = member:removeRole(roleId)
if (not success) then
self:LogWarning(guild, "Failed to remove role % from %s: %s", role.name, member.tag, err)
end
else
self:LogWarning(guild, "Role %s appears to have been removed", roleId)
end
end
if (roleActions.Message) then
local privateChannel = member.user:getPrivateChannel()
if (privateChannel) then
local success, err = privateChannel:send(string.format("[From %s]\n%s", guild.name, roleActions.Message))
if (not success) then
self:LogWarning(guild, "Failed to send reaction message to %s (maybe user disabled private messages from this server?): %s", member.user.tag, err)
end
else
self:LogWarning(guild, "Failed to get private channel with %s", member.user.tag)
end
end
end
function Module:HandleReactionRemove(guild, userId, channelId, messageId, reactionName)
if (client.user.id == userId) then
return
end
local roleActions = self:GetReactionActions(guild, channelId, messageId, reactionName, true)
if (not roleActions) then
return
end
local member = guild:getMember(userId)
for k,roleId in pairs(roleActions.Add) do
local role = guild:getRole(roleId)
if (role) then
self:LogInfo(guild, "Removing %s%s from %s", role.name, (role.color ~= 0) and " (colored)" or "", member.tag)
local success, err = member:removeRole(roleId)
if (not success) then
self:LogWarning(guild, "Failed to remove role %s from %s: %s", role.name, member.tag, err)
end
else
self:LogWarning(guild, "Role %s appears to have been removed", roleId)
end
end
for k,roleId in pairs(roleActions.Remove) do
local role = guild:getRole(roleId)
if (role) then
self:LogInfo(guild, "Adding back %s%s to %s", role.name, (role.color ~= 0) and " (colored)" or "", member.tag)
local success, err = member:addRole(roleId)
if (not success) then
self:LogWarning(guild, "Failed to add role %s to %s: %s", role.name, member.tag, err)
end
else
self:LogWarning(guild, "Role %s appears to have been removed", roleId)
end
end
end
function Module:OnReactionAdd(reaction, userId)
if (reaction.message.channel.type ~= enums.channelType.text) then
return
end
local emoji = bot:GetEmojiData(reaction.message.guild, reaction.emojiName)
if (not emoji) then
return
end
self:HandleReactionAdd(reaction.message.channel.guild, userId, reaction.message.channel.id, reaction.message.id, emoji.Name)
end
function Module:OnReactionAddUncached(channel, messageId, reactionIdOrName, userId)
if (channel.type ~= enums.channelType.text) then
return
end
local emoji = bot:GetEmojiData(channel.guild, reactionIdOrName)
if (not emoji) then
self:LogWarning(channel.guild, "Emoji %s was used but not found in guild", reactionIdOrName)
return
end
self:HandleReactionAdd(channel.guild, userId, channel.id, messageId, emoji.Name)
end
function Module:OnReactionRemove(reaction, userId)
if (reaction.message.channel.type ~= enums.channelType.text) then
return
end
local emoji = bot:GetEmojiData(reaction.message.guild, reaction.emojiName)
if (not emoji) then
self:LogWarning(reaction.message.guild, "Emoji %s was used but not found in guild", reaction.emojiName)
return
end
self:HandleReactionRemove(reaction.message.channel.guild, userId, reaction.message.channel.id, reaction.message.id, emoji.Name)
end
function Module:OnReactionRemoveUncached(channel, messageId, reactionIdOrName, userId)
if (channel.type ~= enums.channelType.text) then
return
end
local emoji = bot:GetEmojiData(channel.guild, reactionIdOrName)
if (not emoji) then
self:LogWarning(channel.guild, "Emoji %s was used but not found in guild", reactionIdOrName)
return
end
self:HandleReactionRemove(channel.guild, userId, channel.id, messageId, emoji.Name)
end
|
AddCSLuaFile( )
DEFINE_BASECLASS("base_aperture_ent")
local WireAddon = WireAddon or WIRE_CLIENT_INSTALLED
ENT.PrintName = "Пневмотическая вентиляция"
ENT.IsAperture = true
ENT.IsConnectable = true
local SUCK_RADIUS = 150
if WireAddon then
ENT.WireDebugName = ENT.PrintName
end
function ENT:SetupDataTables()
self:NetworkVar("Bool", 0, "Enable")
self:NetworkVar("Bool", 1, "Toggle")
self:NetworkVar("Bool", 2, "StartEnabled")
self:NetworkVar("Bool", 3, "IgnoreAlive")
end
function ENT:Enable(enable)
if self:GetEnable() != enable then
if enable then
self:EmitSound("TA:TubeSuck")
else
self:StopSound("TA:TubeSuck")
end
self:SetEnable(enable)
end
end
function ENT:EnableEX(enable)
if self:GetToggle() then
if enable then
self:Enable(not self:GetEnable())
end
return true
end
if self:GetStartEnabled() then enable = !enable end
self:Enable(enable)
end
local function FilterValid(pipe, ent, routeInx)
if not pipe.DivventFilter then return true end
if not pipe.DivventFilter[routeInx] then return true end
local filters = pipe.DivventFilter[routeInx]
for k,v in pairs(filters) do
local filterType = v.filterType
local text = v.text
local min, max = v.min, v.max
if filterType == 1 then
if ent:GetModel() == string.lower(text) then return true end
elseif filterType == 2 then
if ent:GetClass() == text then return true end
elseif filterType == 3 then
local physObj = ent:GetPhysicsObject()
if IsValid(physObj) then
local mass = physObj:GetMass()
if mass >= min and mass < max then return true end
end
elseif filterType == 4 then
local radius = ent:GetModelRadius()
if radius >= min and radius < max then return true end
elseif filterType == 5 then
if ent:IsPlayer() or ent:IsNPC() then return true end
elseif filterType == 6 then
if not ent:IsPlayer() and not ent:IsNPC() then return true end
end
end
end
local function CalcPipeFlow(info, inx, ent, pointIgnore, ignore, checkEntFilter, onePath)
local pointInfo = info[inx]
local pointIgnore = pointIgnore and pointIgnore or {[inx] = true}
local returnDat = {}
local dirtbl = {}
local splits = 0
for k,v in pairs(pointInfo.connected) do
if not pointIgnore[v] and (not IsValid(checkEntFilter) or FilterValid(ent, checkEntFilter, v)) then
splits = splits + 1
table.insert(dirtbl, v)
end
end
if onePath then
local stop = false
while true do
if #dirtbl == 0 then return returnDat end
local rand = math.random(1, #dirtbl)
local dirinx = dirtbl[rand]
local outinx = info[dirinx].outinx
local pos = info[dirinx].pos
pointIgnore[dirinx] = true
if outinx then
local exitPipe = ent:GetNWEntity("TA:ConnectedPipe:"..outinx)
local exitPipeInx = ent:GetNWInt("TA:ConnectedPipeInx:"..outinx)
table.insert(returnDat, ent:LocalToWorld(pointInfo.pos))
if IsValid(exitPipe) then
if exitPipe:GetClass() != "ent_diversity_vent" then
local path = CalculateFlows(exitPipe, exitPipeInx, ignore, _, checkEntFilter, onePath)
if path then
table.Add(returnDat, path)
return returnDat
else table.remove(dirtbl, rand) end
end
else
local wpos = ent:LocalToWorld(pos)
table.insert(returnDat, wpos)
return returnDat
end
else
table.remove(dirtbl, rand)
table.insert(returnDat, ent:LocalToWorld(pointInfo.pos))
table.Add(returnDat, CalcPipeFlow(info, dirinx, ent, pointIgnore, ignore, checkEntFilter, onePath))
end
end
else
for k,v in pairs(dirtbl) do
local outinx = info[v].outinx
local pos = info[v].pos
pointIgnore[v] = true
if outinx then
local exitPipe = ent:GetNWEntity("TA:ConnectedPipe:"..outinx)
local exitPipeInx = ent:GetNWInt("TA:ConnectedPipeInx:"..outinx)
table.insert(returnDat, ent:LocalToWorld(pointInfo.pos))
if IsValid(exitPipe) then
if exitPipe:GetClass() != "ent_diversity_vent" then
local path = CalculateFlows(exitPipe, exitPipeInx, ignore, _, checkEntFilter)
if splits > 1 then table.Add(returnDat, {path}) else table.Add(returnDat, path) end
end
else
local wpos = ent:LocalToWorld(pos)
if splits > 1 then table.insert(returnDat, {wpos}) else table.insert(returnDat, wpos) end
end
else
table.insert(returnDat, ent:LocalToWorld(pointInfo.pos))
table.Add(returnDat, CalcPipeFlow(info, v, ent, pointIgnore, ignore, checkEntFilter))
end
end
end
-- if #returnDat == 0 then
-- table.insert(returnDat, ent:LocalToWorld(pointInfo.pos))
-- end
return returnDat
end
function CalculateFlows(ent, index, ignore, startent, checkEntFilter, onePath)
if IsValid(startent) and not IsValid(startent:GetNWEntity("TA:ConnectedPipe:1")) then return end
local ent = ent and ent or startent:GetNWEntity("TA:ConnectedPipe:1")
local index = index and index or startent:GetNWInt("TA:ConnectedPipeInx:1")
local ignore = ignore and ignore or {}
if IsValid(startent) then ignore[startent:EntIndex().."|"..1] = true end
if ignore[ent:EntIndex().."|"..index] then return {} end
ignore[ent:EntIndex().."|"..index] = true
local info = ent:GetModelFlowData()
return CalcPipeFlow(info, index, ent, nil, ignore, checkEntFilter, onePath)
end
function CalculateFlow(flowstbl)
local flow = {}
for k,v in pairs(flowstbl) do
if istable(v) then
local randtbl = {}
for i=k,#flowstbl do
if istable(flowstbl[i]) then table.insert(randtbl, i) end
end
local rand = randtbl[math.random(1, #randtbl)]
table.Add(flow, CalculateFlow(flowstbl[rand]))
break
else
table.insert(flow, v)
end
end
return flow
end
function ENT:Initialize()
self.BaseClass.Initialize(self)
if SERVER then
self:SetModel("models/aperture/vacum_flange_a.mdl")
self:PhysicsInitStatic(SOLID_VPHYSICS)
self:SetMoveType(MOVETYPE_VPHYSICS)
self:SetSolid(SOLID_VPHYSICS)
self:SetCollisionGroup(COLLISION_GROUP_WORLD)
if self:GetStartEnabled() then self:Enable(true) end
if not WireAddon then return end
self.Inputs = Wire_CreateInputs(self, {"Enable"})
end
if CLIENT then
end
end
function ENT:HandleEntities(ent, portalable, fromportal)
if portalable and ent:GetClass() == "prop_portal" then
local portalOther = ent:GetNWEntity("Potal:Other")
if IsValid(portalOther) then
local entities = ents.FindInSphere(portalOther:GetPos(), SUCK_RADIUS)
local effectdata = EffectData()
effectdata:SetOrigin(portalOther:GetPos())
effectdata:SetNormal(portalOther:GetForward())
util.Effect("tube_suck_effect", effectdata)
for k,v in pairs(entities) do
self:HandleEntities(v, false, portalOther)
end
end
end
if ent.IsAperture then return end
if not IsValid(ent:GetPhysicsObject()) then return end
if self:GetIgnoreAlive() and (ent:IsPlayer() or ent:IsNPC()) then return end
if LIB_APERTURE.DIVVENT_ENTITIES[ent] then return end
if not IsValid(self:GetNWEntity("TA:ConnectedPipe:1")) then return end
if not ent:GetPhysicsObject():IsMotionEnabled() then return end
-- if not ent:IsPlayer() then return end
if ent:GetMoveType() == MOVETYPE_PUSH then return end
local flow = {}
-- if vent is from portal then suck at portal first
if IsValid(fromportal) then
table.insert(flow, fromportal:LocalToWorld(Vector(-(ent:GetModelScale() + 40), 0, 0)))
else
flow = CalculateFlows(nil, nil, nil, self, ent, true)
end
LIB_APERTURE.DIVVENT_ENTITIES[ent] = {flow = flow, vent = self, index = 1}
end
-- no more client side
if CLIENT then return end
function ENT:UpdatePipe(updateConnected)
end
function ENT:Think()
self:NextThink(CurTime() + 0.1)
-- skip if disabled
if not self:GetEnable() then return end
local effectdata = EffectData()
effectdata:SetOrigin(self:GetPos())
effectdata:SetNormal(self:GetRight())
util.Effect("tube_suck_effect", effectdata)
local entities = ents.FindInSphere(self:LocalToWorld(Vector(0, -SUCK_RADIUS, 0)), SUCK_RADIUS)
for k,v in pairs(entities) do
self:HandleEntities(v, true)
end
return true
end
numpad.Register("DiversityVent_Enable", function(pl, ent, keydown)
if not IsValid(ent) then return false end
ent:EnableEX(keydown)
return true
end)
function ENT:OnRemove()
self:StopSound("TA:TubeSuck")
end
|
object_tangible_item_rare_loot_chest_2 = object_tangible_item_shared_rare_loot_chest_2:new {
objectMenuComponent = "Rarelootcrate2MenuComponent",
}
ObjectTemplates:addTemplate(object_tangible_item_rare_loot_chest_2, "object/tangible/item/rare_loot_chest_2.iff")
|
package("mma")
set_homepage("https://github.com/jdumas/mma")
set_description("A self-contained C++ implementation of MMA and GCMMA.")
set_license("MIT")
add_urls("https://github.com/jdumas/mma.git")
add_versions("2018.08.01", "aa51333f942220ac98e5957accb1b7e60590ec6f")
if is_plat("windows") then
add_configs("shared", {description = "Build shared library.", default = false, type = "boolean", readonly = true})
end
on_install(function (package)
io.writefile("xmake.lua", [[
add_rules("mode.debug", "mode.release")
set_languages("cxx11")
target("mma")
set_kind("$(kind)")
add_files("src/mma/MMASolver.cpp")
add_headerfiles("src/(mma/MMASolver.h)")
target("gcmma")
set_kind("$(kind)")
add_files("src/gcmma/GCMMASolver.cpp")
add_headerfiles("src/(gcmma/GCMMASolver.h)")
]])
import("package.tools.xmake").install(package)
end)
on_test(function (package)
assert(package:has_cxxtypes("MMASolver", {includes = "mma/MMASolver.h"}))
end)
|
-- things to NOT do
--
-- dont assign newindex to userdata
--gameserver.onpacket = 'lol'
--
-- use . not : for calling go userdata
--gameserver:ANYTHING()
-- item handling stuff?
loot = require('loot')
items = require('items')
coll = require('collision')
collide = coll.collide
-- load our only map..
map = require('map1')
map.load()
-- get a debug shell after loading
if gs.Debug() == true then
debug.debug()
end
|
local test = require 'test'
local mach = require 'mach'
describe('test', function()
it('should call the provided function', function()
local f = mach.mock_function()
f:should_be_called_with(3):when(function()
test(f)
end)
end)
end)
|
-- antspawn.lua - Antenna spawner
-- This file is under copyright, and is bound to the agreement stated in the EULA.
-- Any 3rd party content has been used as either public domain or with permission.
-- © Copyright 2016-2017 Aritz Beobide-Cardinal All rights reserved.
function ARCPhone.SpawnAntennas()
local shit = file.Read(ARCPhone.Dir.."/saved_atms/"..string.lower(game.GetMap())..".txt", "DATA" )
if !shit then
ARCPhone.Msg("Cannot spawn Antennas. No file associated with this map.")
return false
end
local atmdata = util.JSONToTable(shit)
if !atmdata then
ARCPhone.Msg("Cannot spawn Antennas. Corrupt file associated with this map.")
return false
end
for _, oldatms in pairs( ents.FindByClass("sent_arc_phone_antenna") ) do
oldatms.ARCPhone_MapEntity = false
oldatms:Remove()
end
ARCPhone.Msg("Spawning Map Antennas...")
for i=1,atmdata.atmcount do
local shizniggle = ents.Create("sent_arc_phone_antenna")
if !IsValid(shizniggle) then
atmdata.atmcount = 1
ARCPhone.Msg("Antennas failed to spawn.")
return false end
if atmdata.pos[i] && atmdata.angles[i] then
shizniggle:SetPos(atmdata.pos[i]+Vector(0,0,ARCLib.BoolToNumber(!atmdata.NewATMModel)*8.6))
shizniggle:SetAngles(atmdata.angles[i])
shizniggle:SetPos(shizniggle:GetPos()+(shizniggle:GetRight()*ARCLib.BoolToNumber(!atmdata.NewATMModel)*-4.1)+(shizniggle:GetForward()*ARCLib.BoolToNumber(!atmdata.NewATMModel)*19))
shizniggle:Spawn()
shizniggle:Activate()
else
shizniggle:Remove()
atmdata.atmcount = 1
ARCPhone.Msg("Corrupt File")
return false
end
local phys = shizniggle:GetPhysicsObject()
if IsValid(phys) then
phys:EnableMotion( false )
end
shizniggle.ARCPhone_MapEntity = true
shizniggle.ARitzDDProtected = true
end
return true
end
function ARCPhone.SaveAntennas()
ARCPhone.Msg("Saving Antennas...")
local atmdata = {}
atmdata.angles = {}
atmdata.pos = {}
local atms = ents.FindByClass("sent_arc_phone_antenna")
atmdata.atmcount = table.maxn(atms)
atmdata.NewATMModel = true
if atmdata.atmcount <= 0 then
ARCPhone.Msg("No Antennas to save!")
return false
end
for i=1,atmdata.atmcount do
local phys = atms[i]:GetPhysicsObject()
if IsValid(phys) then
phys:EnableMotion( false )
end
atms[i].ARCPhone_MapEntity = true
atms[i].ARitzDDProtected = true
atmdata.pos[i] = atms[i]:GetPos()
atmdata.angles[i] = atms[i]:GetAngles()
end
PrintTable(atmdata)
local savepos = ARCPhone.Dir.."/saved_atms/"..string.lower(game.GetMap())..".txt"
file.Write(savepos,util.TableToJSON(atmdata))
if file.Exists(savepos,"DATA") then
ARCPhone.Msg("Antennas Saved in: "..savepos)
return true
else
ARCPhone.Msg("Error while saving map.")
return false
end
end
function ARCPhone.UnSaveAntennas()
ARCPhone.Msg("UnSaving Antennas...")
local atms = ents.FindByClass("sent_arc_phone_antenna")
if table.maxn(atms) <= 0 then
ARCPhone.Msg("No Antennas to Unsave!")
return false
end
for i=1,table.maxn(atms) do
local phys = atms[i]:GetPhysicsObject()
if IsValid(phys) then
phys:EnableMotion( true )
end
atms[i].ARCPhone_MapEntity = false
atms[i].ARitzDDProtected = false
end
local savepos = ARCPhone.Dir.."/saved_atms/"..string.lower(game.GetMap())..".txt"
file.Delete(savepos)
return true
end
function ARCPhone.ClearAntennas()
for _, oldatms in pairs( ents.FindByClass("sent_arc_phone_antenna") ) do
oldatms.ARCPhone_MapEntity = false
oldatms:Remove()
end
ARCPhone.Msg("All Antennas Removed.")
end
|
#!/usr/bin/env lua
local function with_command(command, fn)
io.stderr:write("> ", command, "\n")
local handle, err = io.popen(command)
if not handle then
io.stderr:write(err)
os.exit(1)
end
local result = fn(handle)
handle:close()
return result
end
local build = os.getenv("GITHUB_RUN_NUMBER") or "0-dev"
local version = "1.0.0." .. build
local url = "https://raw.githubusercontent.com/SquidDev-CC/metis/dev/"
local function to_package(dep)
return dep:sub(7):gsub("%.", "-")
end
local function map_concat(tbls, fn, sep)
local out = ""
for i = 1, #tbls do
if i > 1 then out = out .. sep end
out = out .. fn(tbls[i])
end
return out
end
local function packman_name(x) return "metis/" .. x end
local function ccpt_name(x) return ("%q"):format("ccpt:metis/" .. x) end
local kind, filename = ...
if not filename then kind, filename = nil, kind end
if not kind then kind = "packman" end
if kind ~= "packman" and kind ~= "ccpt" then
io.stderr:write("Unknown repo kind ", kind, "\n")
return os.exit(1)
end
if filename and filename ~= "-" then io.output(filename) end
local modules = {}
with_command("git ls-files", function(handle)
for file in handle:lines() do
if file:sub(1, 4) == "src/" and file:sub(-4) == ".lua" then
local module = file:sub(5, -5):gsub("/", ".")
modules[module] = file
end
end
end)
if kind == "ccpt" then
io.write("{\n")
end
local packages = {}
for module, file in pairs(modules) do
local contents = string.dump(loadfile(file))
table.insert(packages, (to_package(module)))
local deps = {}
for require in contents:gmatch('(metis%.[a-z.]+)') do
if not modules[require] then
io.stderr:write(("Unknown module %q\n"):format(require))
os.exit(1)
end
if not deps[require] then
deps[require] = true
deps[#deps + 1] = to_package(require)
end
end
if kind == "packman" then
io.write("name = ", to_package(module), "\n")
io.write("\ttype = raw\n")
io.write("\t\turl = ", url, file, "\n")
io.write("\t\tfilename = ", file:sub(5), "\n")
io.write("\ttarget = /usr/modules/\n")
io.write("\tcategory = lib\n")
io.write("\tversion = ", version, "\n")
io.write("\tdependencies = ", #deps == 0 and "none" or map_concat(deps, packman_name, " "), "\n")
io.write("\tsize = ", #contents, "\n")
io.write("end\n\n")
elseif kind == "ccpt" then
io.write(' "', to_package(module), '": {\n')
io.write(' "plugins": ["files"],\n')
io.write(' "version": "' .. version .. '",\n')
io.write(' "files": [\n')
io.write(' ["', url, file, '","/usr/modules/', file:sub(5), '"]\n')
io.write(' ],\n')
io.write(' "dependencies": [', map_concat(deps, ccpt_name, ", "), ']\n')
io.write(' },\n')
end
end
if kind == "packman" then
io.write("name = metis-full\n")
io.write("\ttype = meta\n")
io.write("\tcategory = lib\n")
io.write("\tversion = ", version, "\n")
io.write("\tdependencies = ", map_concat(packages, packman_name, " "), "\n")
io.write("\tsize = 0\n")
io.write("end\n\n")
elseif kind == "ccpt" then
io.write(' "metis-full": {\n')
io.write(' "plugins": [],\n')
io.write(' "version": "' .. version .. '",\n')
io.write(' "dependencies": [', map_concat(packages, ccpt_name, ", "), '],\n')
io.write(' "description": "All packages of metis"\n')
io.write(' }\n')
io.write("}\n")
end
|
local lir = require('lir')
local actions = require('lir.actions')
return function()
local ctx = lir.get_context()
actions.cd()
vim.fn['deol#cd'](ctx.dir)
end
|
local parse_http_req_headers = require "kong.plugins.zipkin.parse_http_req_headers"
local to_hex = require "resty.string".to_hex
local fmt = string.format
local function to_hex_first_3(arr)
return { arr[1] and to_hex(arr[1]) or nil,
arr[2] and to_hex(arr[2]) or nil,
arr[3] and to_hex(arr[3]) or nil,
arr[4] }
end
local trace_id = "0000000000000001"
local trace_id_32 = "00000000000000000000000000000001"
local parent_id = "0000000000000002"
local span_id = "0000000000000003"
local non_hex_id = "vvvvvvvvvvvvvvvv"
local too_short_id = "123"
local too_long_id = "1234567890123456789012345678901234567890" -- 40 digits
describe("zipkin header parsing", function()
_G.kong = {
log = {},
}
describe("b3 single header parsing", function()
local warn
before_each(function()
warn = spy.on(kong.log, "warn")
end)
it("1-char", function()
local t = { parse_http_req_headers({ b3 = "1" }) }
assert.same({ nil, nil, nil, true }, t)
assert.spy(warn).not_called()
t = { parse_http_req_headers({ b3 = "d" }) }
assert.same({ nil, nil, nil, true }, t)
assert.spy(warn).not_called()
t = { parse_http_req_headers({ b3 = "0" }) }
assert.same({ nil, nil, nil, false }, t)
assert.spy(warn).not_called()
end)
it("4 fields", function()
local b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "1", parent_id)
local t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({ trace_id, span_id, parent_id, true }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("4 fields inside tracestate", function()
local b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "1", parent_id)
local t = { parse_http_req_headers({ tracestate = "b3=" .. b3 }) }
assert.same({ trace_id, span_id, parent_id, true }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("32-digit trace_id", function()
local b3 = fmt("%s-%s-%s-%s", trace_id_32, span_id, "1", parent_id)
local t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({ trace_id_32, span_id, parent_id, true }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("trace_id and span_id, no sample or parent_id", function()
local b3 = fmt("%s-%s", trace_id, span_id)
local t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({ trace_id, span_id }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("32-digit trace_id and span_id, no sample or parent_id", function()
local b3 = fmt("%s-%s", trace_id_32, span_id)
local t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({ trace_id_32, span_id }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("trace_id, span_id and sample, no parent_id", function()
local b3 = fmt("%s-%s-%s", trace_id, span_id, "1")
local t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({ trace_id, span_id, nil, true }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("32-digit trace_id, span_id and sample, no parent_id", function()
local b3 = fmt("%s-%s-%s", trace_id_32, span_id, "1")
local t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({ trace_id_32, span_id, nil, true }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("sample debug = always sample", function()
local b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "d", parent_id)
local t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({ trace_id, span_id, parent_id, true }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("sample 0 = don't sample", function()
local b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "0", parent_id)
local t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({ trace_id, span_id, parent_id, false }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("sample 0 overriden by x-b3-sampled", function()
local b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "0", parent_id)
local t = { parse_http_req_headers({ b3 = b3, ["x-b3-sampled"] = "1" }) }
assert.same({ trace_id, span_id, parent_id, true }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
describe("errors", function()
it("requires trace id", function()
local t = { parse_http_req_headers({ b3 = "" }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
end)
it("rejects existing but invalid trace_id", function()
local t = { parse_http_req_headers({ b3 = non_hex_id .. "-" .. span_id }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
t = { parse_http_req_headers({ b3 = too_short_id .. "-" .. span_id }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
-- too long
t = { parse_http_req_headers({ b3 = too_long_id .. "-" .. span_id }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
end)
it("requires span_id", function()
local t = { parse_http_req_headers({ b3 = trace_id .. "-" }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
end)
it("rejects existing but invalid span_id", function()
local t = { parse_http_req_headers({ b3 = trace_id .. non_hex_id }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
t = { parse_http_req_headers({ b3 = trace_id .. too_short_id }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
t = { parse_http_req_headers({ b3 = trace_id .. too_long_id }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
end)
it("rejects invalid sampled section", function()
local b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "x", parent_id)
local t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
end)
it("rejects invalid parent_id section", function()
local b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "d", non_hex_id)
local t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "d", too_short_id)
t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
b3 = fmt("%s-%s-%s-%s", trace_id, span_id, "d", too_long_id)
t = { parse_http_req_headers({ b3 = b3 }) }
assert.same({}, t)
assert.spy(warn).called_with("b3 single header invalid; ignoring.")
end)
end)
end)
describe("W3C header parsing", function()
local warn
before_each(function()
warn = spy.on(kong.log, "warn")
end)
it("valid traceparent with sampling", function()
local traceparent = fmt("00-%s-%s-01", trace_id_32, parent_id)
local t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({ trace_id_32, nil, parent_id, true }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("valid traceparent without sampling", function()
local traceparent = fmt("00-%s-%s-00", trace_id_32, parent_id)
local t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({ trace_id_32, nil, parent_id, false }, to_hex_first_3(t))
assert.spy(warn).not_called()
end)
it("sampling with mask", function()
local traceparent = fmt("00-%s-%s-09", trace_id_32, parent_id)
local t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same(true, t[4])
assert.spy(warn).not_called()
end)
it("no sampling with mask", function()
local traceparent = fmt("00-%s-%s-08", trace_id_32, parent_id)
local t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same(false, t[4])
assert.spy(warn).not_called()
end)
describe("errors", function()
it("rejects W3C versions other than 00", function()
local traceparent = fmt("01-%s-%s-00", trace_id_32, parent_id)
local t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C Trace Context version; ignoring.")
end)
it("rejects invalid header", function()
local traceparent = "vv-00000000000000000000000000000001-0000000000000001-00"
local t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C traceparent header; ignoring.")
traceparent = "00-vvvvvvvvvvvvvvvvvvvvvvvvvvvvvvvv-0000000000000001-00"
t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C traceparent header; ignoring.")
traceparent = "00-00000000000000000000000000000001-vvvvvvvvvvvvvvvv-00"
t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C traceparent header; ignoring.")
traceparent = "00-00000000000000000000000000000001-0000000000000001-vv"
t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C traceparent header; ignoring.")
end)
it("rejects invalid trace IDs", function()
local traceparent = fmt("00-%s-%s-00", too_short_id, parent_id)
local t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C trace context trace ID; ignoring.")
traceparent = fmt("00-%s-%s-00", too_long_id, parent_id)
t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C trace context trace ID; ignoring.")
-- cannot be all zeros
traceparent = fmt("00-00000000000000000000000000000000-%s-00", too_long_id, parent_id)
t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C trace context trace ID; ignoring.")
end)
it("rejects invalid parent IDs", function()
local traceparent = fmt("00-%s-%s-00", trace_id_32, too_short_id)
local t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C trace context parent ID; ignoring.")
traceparent = fmt("00-%s-%s-00", trace_id_32, too_long_id)
t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C trace context parent ID; ignoring.")
-- cannot be all zeros
traceparent = fmt("00-%s-0000000000000000-01", trace_id_32)
t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C trace context parent ID; ignoring.")
end)
it("rejects invalid trace flags", function()
local traceparent = fmt("00-%s-%s-000", trace_id_32, parent_id)
local t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C trace context flags; ignoring.")
traceparent = fmt("00-%s-%s-0", trace_id_32, parent_id)
t = { parse_http_req_headers({ traceparent = traceparent }) }
assert.same({}, t)
assert.spy(warn).was_called_with("invalid W3C trace context flags; ignoring.")
end)
end)
end)
end)
|
-----------------------------------------------------------
-- PROJECT: MTA:TD - Test and Debug Framework
--
-- LICENSE: See LICENSE in top level directory
-- PURPOSE: The backend interface (communicates with the backend)
------------------------------------------------------------
MTATD.Backend = MTATD.Class()
-----------------------------------------------------------
-- Launches the test and debug framework
-----------------------------------------------------------
function MTATD.Backend:constructor(host, port)
-- Build base URL
self._baseUrl = ("http://%s:%d/"):format(host, port)
-- Connect to backend
self:connect(host, port)
-- Create subsystems
self._debug = MTATD.MTADebug:new(self)
end
-----------------------------------------------------------
-- Stops the test and debug framework
-----------------------------------------------------------
function MTATD.Backend:destructor()
-- Destroy debugger
self._debug:delete()
end
-----------------------------------------------------------
-- Connects to the backend via HTTP
--
-- host (string): The hostname or IP
-- port (number): The port
-----------------------------------------------------------
function MTATD.Backend:connect(host, port)
-- Make initial request to check if the backend is running
-- TODO
end
-----------------------------------------------------------
-- Sends a request with data to the backend
--
-- name (string): The request identifier (use <MODULE>/<action>)
-- data (table): The data that is sent to the backend
-- (must be serializable using toJSON)
-- callback (function(responseData)): Called when the
-- unserialized response arrives.
-- If not provided, returns the response object synchronously
-----------------------------------------------------------
function MTATD.Backend:request(name, data, callback)
local responseObject = nil
local serialized = toJSON(data):gsub("%[(.*)%]", "%1") -- Fix object being embedded into a JSON array
local result = fetchRemote(self._baseUrl..name,
function(response, errno)
if errno ~= 0 then
error("Could not reach backend (code "..errno..") with "..self._baseUrl..name)
responseObject = false -- Make sure we don't run into a freeze'
return
end
-- Unserialize response and call callback
local obj = fromJSON("["..response.."]")
if callback then
callback(obj)
else
responseObject = obj
end
end,
serialized
)
if not callback then
repeat
debugSleep(25)
until responseObject ~= nil
return responseObject
else
return result
end
end
function MTATD.Backend:reportTestResults(testResults)
-- Build JSON object
--[[local data = {}
for testSuite, results in pairs(testResults) do
-- Reformat data
-- TODO
end]]
self:request("MTAUnit/report_test_results", testResults)
end
|
function Initialize()
Max = SELF:GetNumberOption('Max')
Trigger = SELF:GetNumberOption('Trigger', Max)
Speed = SELF:GetNumberOption('Speed', 1)
end
function Update()
local Input = SELF:GetNumberOption('Input')
if Input < Max then
return Input
elseif Input < Trigger then
return Max
end
return Max * (1 - (Input - Trigger) * Speed)
end |
-- local function data(file, tag, names, stripFunc, postFunc)
local parser = require "otherData.featParser"
local names =
{
"Trickster",
"Bag of Tricks",
"Stacked Deck",
"Flourish",
"Encore Performance",
"Sleight"
}
local m = string.match
local function strip(parser, str)
-- local firstFeat = parser.names[1]
return m(str, "(.-)Mind Games\r\n")
end
local function fixStackedDeck(feats)
-- fix up the stupid Stacked Deck table
local stackedDeck
-- still haven't mastered next...
for k, v in ipairs(feats) do
if v.name == "Stacked Deck" then
stackedDeck = v
end
end
-- strip table from effect description
local fx, tblStr = m(stackedDeck.fx, "(.-) Condition Effect (.+)")
local status = {{"Condition", "Effect"}}
local strs =
{
"Bad Dreams",
"Whenever",
"Paralysis",
"The",
"Confuse",
"The",
"$"
}
-- build the stable
for n = 1, #strs - 2, 2 do
local start1 = strs[n]
local start2 = strs[n+1]
local finish = strs[n+2]
local ptn = string.format("(%s.-)(%s.-)%s", start1, start2, finish)
local a, b = m(tblStr, ptn)
table.insert(status, {a, b})
end
stackedDeck.fx = fx
stackedDeck.tbl = status
end
local function post(feats, str)
local ex = {}
local exStr = m(str, "(Mind Games.+)Trickster Techniques\r\n")
local techStrs = {}
table.insert(techStrs, m(exStr, "^(.-)Escape Artist"))
table.insert(techStrs, m(exStr, "(Escape Artist.-)Shell Game"))
table.insert(techStrs, m(exStr, "(Shell Game.-)Impromptu Trick"))
table.insert(techStrs, m(exStr, "(Impromptu Trick.+)"))
local techs = {}
for k, s in ipairs(techStrs) do
local tech = {}
tech.name = m(s, "^(.-)\r\n")
tech.freq = m(s, tech.name .. "\r\n(.-)\r\n")
local fx = m(s, "Effect: (.+)")
-- shell game has target instead of trigger
if tech.name == "Shell Game" then
tech.target = m(s, "Target: (.-)Effect:")
else
tech.trigger = m(s, "Trigger: (.-)Effect:")
end
tech.fx = fx
-- cleanup
for i, j in pairs(tech) do
j = string.gsub(j, "\r\n", " ")
j = m(j, "%s*(.+%S)")
tech[i] = j
end
table.insert(techs, tech)
end
fixStackedDeck(feats)
ex.techs = techs
return ex
end
return parser("trickster.txt", "Trickster Class", names, strip, post) |
--[[
TQAE - Tiny QuickApp emulator for the Fibaro Home Center 3
Copyright (c) 2021 Jan Gabrielsson
Email: jan@gabrielsson.com
MIT License
Synchronous timers and IO support - simulates asynchronous calls with short repeated IO timeouts
--]]
local EM,FB=...
local LOG,Devices,debugFlags = EM.LOG,EM.Devices,EM.debugFlags
local timers
local socket = require("socket")
local getContext,procs = EM.getContext,EM.procs
local function IDF() end
local function killTimers() timers.reset() end
local function checkForExit(cf,co,stat,res,...)
local ctx = EM.procs[co]
if not stat then
if type(res)=='table' and res.type then
killTimers()
if ctx.cont then ctx.cont() end
if cf then coroutine.yield(co) end
else
EM.checkErr(ctx.env.__TAG,false,res)
end
end
return stat,res,...
end
local function timerCall(t,args)
local co,ctx = table.unpack(args)
if EM.cfg.lateTimer then EM.timerCheckFun(t) end
local stat,res = coroutine.resume(co)
ctx.timers[t]=nil
checkForExit(false,co,stat,res)
end
local function setTimeout(fun,ms,tag,ctx)
ctx = ctx or procs[coroutine.running()]
local co = coroutine.create(fun)
local v = EM.makeTimer(ms/1000+EM.clock(),co,ctx,tag,timerCall,{co,ctx})
ctx.timers[v] = true
procs[co] = ctx
return timers.queue(v)
end
local sysCtx = {env={__TAG='SYSTEM'},dev={}, timers={}}
local function systemTimer(fun,ms,tag) return setTimeout(fun,ms,tag or nil,sysCtx) end
local function clearTimeout(ref) timers.dequeue(ref) end
local function fibaroSleep(ms) -- We lock all timers/coroutines except the one resuming the sleep for us
local r,co;
co,r = coroutine.running(),EM.setTimeout(function() timers.lock(r,false) coroutine.resume(co) end,ms)
timers.lock(r,true);
coroutine.yield(co)
end
local function exit(status)
LOG.sys("exit(%s)",status or 0)
error({type='exit'})
end
local function createLock() return { release=IDF, get=IDF } end
local function restartQA(D)
timers.clearTimers(D.dev.id)
EM.runQA(D.id,D.cont)
coroutine.yield()
end
local function start(fun)
timers = EM.utilities.timerQueue()
local clock = EM.clock
EM.running = true
systemTimer(fun,0,"user")
-- Timer loop - core of emulator, run each coroutine until none left or all locked
while(EM.running) do -- Loop as long as there are user timers and execute them when their time is up
local t,time = timers.peek() -- Look at first enabled/unlocked task in queue
if time ~= nil then
local now = clock()
if time <= now then -- Times up?
timers.dequeue(t) -- Remove task from queue
t.fun(t,t.args) -- ...and run it
else
socket.sleep(time-now) -- "sleep" until next timer in line is up
end
else socket.sleep(0.01) end
end
for k,_ in pairs(Devices) do Devices[k]=nil end -- Save and clear directory of Devices
end
local CO = coroutine
local function cocreate(fun,...)
local co = CO.create(fun,...)
EM.proces[co]=getContext()
return co
end
local function resume(co,...)
return checkForExit(true,co,coroutine.resume(co,...))
end
EM.userCoroutines = {resume=resume,yield=CO.yield,create=cocreate,status=CO.status,running=CO.running}
EM.start = start
EM.setTimeout = setTimeout
EM.clearTimeout = clearTimeout
EM.systemTimer = systemTimer
EM.exit = exit
EM.restartQA = restartQA
EM.createLock = createLock
FB.__fibaroSleep = fibaroSleep
EM.checkForExit = checkForExit |
-- --------------------
-- TellMeWhen
-- Originally by Nephthys of Hyjal <lieandswell@yahoo.com>
-- Other contributions by:
-- Sweetmms of Blackrock, Oozebull of Twisting Nether, Oodyboo of Mug'thol,
-- Banjankri of Blackrock, Predeter of Proudmoore, Xenyr of Aszune
-- Currently maintained by
-- Cybeloras of Aerie Peak/Detheroc/Mal'Ganis
-- --------------------
if not TMW then return end
local TMW = TMW
local L = TMW.L
local print = TMW.print
local format = format
local isNumber = TMW.isNumber
-- SHOWN: "shown"
do
local Processor = TMW.Classes.IconDataProcessor:New("SHOWN", "shown")
Processor.dontInherit = true
-- Processor:CompileFunctionSegment(t) is default.
-- The default state is hidden, so reflect this.
TMW.Classes.Icon.attributes.shown = false
end
-- STATE: "state"
do
local Processor = TMW.Classes.IconDataProcessor:New("STATE", "state")
Processor:DeclareUpValue("stateDataNone", {Alpha = 0, Color = "ffffffff", Texture=""})
Processor.dontInherit = true
Processor:RegisterAsStateArbitrator(100, nil, false, function(icon, panelInfo)
return panelInfo.supplementalData
end)
-- Processor:CompileFunctionSegment(t) is default.
function Processor:CompileFunctionSegment(t)
-- GLOBALS: state
t[#t+1] = [[
--if state ~= nil then
local stateData = type(state) == 'table' and state or (state == 0 and stateDataNone or icon.States[state])
if attributes.state ~= stateData then
attributes.state = stateData
TMW:Fire(STATE.changedEvent, icon, stateData, state)
doFireIconUpdated = true
end
--end
--]]
end
TMW:RegisterCallback("TMW_ICON_SETUP_PRE", function(event, icon)
icon:SetInfo("state", 0)
end)
end
-- CALCULATEDSTATE: "calculatedState"
do
local Processor = TMW.Classes.IconDataProcessor:New("CALCULATEDSTATE", "calculatedState")
Processor.dontInherit = true
end
-- ALPHAOVERRIDE: "alphaOverride"
do
local Processor = TMW.Classes.IconDataProcessor:New("ALPHAOVERRIDE", "alphaOverride")
Processor:RegisterAsStateArbitrator(0, nil, true)
Processor.dontInherit = true
Processor:DeclareUpValue("alphaOverrideStates", setmetatable({}, {
__index = function(self, k)
if not k then return nil end
self[k] = {Alpha = k, Color = "ffffffff", Texture=""}
return self[k]
end
}))
-- Processor:CompileFunctionSegment(t) is default.
function Processor:CompileFunctionSegment(t)
-- GLOBALS: alphaOverride
t[#t+1] = [[
local stateData = type(alphaOverride) == 'table' and alphaOverride or alphaOverrideStates[alphaOverride]
if attributes.alphaOverride ~= stateData then
attributes.alphaOverride = stateData
TMW:Fire(STATE.changedEvent, icon, stateData, alphaOverride)
doFireIconUpdated = true
end
--]]
end
end
-- REALALPHA: "realAlpha"
do
local Processor = TMW.Classes.IconDataProcessor:New("REALALPHA", "realAlpha")
Processor.dontInherit = true
Processor:AssertDependency("SHOWN")
TMW.Classes.Icon.attributes.realAlpha = 0
Processor:RegisterIconEvent(11, "OnShow", {
category = L["EVENT_CATEGORY_VISIBILITY"],
text = L["SOUND_EVENT_ONSHOW"],
desc = L["SOUND_EVENT_ONSHOW_DESC"],
})
Processor:RegisterIconEvent(12, "OnHide", {
category = L["EVENT_CATEGORY_VISIBILITY"],
text = L["SOUND_EVENT_ONHIDE"],
desc = L["SOUND_EVENT_ONHIDE_DESC"],
settings = {
OnlyShown = false,
},
applyDefaultsToSetting = function(EventSettings)
EventSettings.OnlyShown = false
end,
})
Processor:RegisterIconEvent(13, "OnAlphaInc", {
category = L["EVENT_CATEGORY_VISIBILITY"],
text = L["SOUND_EVENT_ONALPHAINC"],
desc = L["SOUND_EVENT_ONALPHAINC_DESC"],
settings = {
Operator = true,
Value = true,
CndtJustPassed = true,
PassingCndt = true,
},
valueName = L["ALPHA"],
valueSuffix = "%",
conditionChecker = function(icon, eventSettings)
return TMW.CompareFuncs[eventSettings.Operator](icon.attributes.realAlpha * 100, eventSettings.Value)
end,
})
Processor:RegisterIconEvent(14, "OnAlphaDec", {
category = L["EVENT_CATEGORY_VISIBILITY"],
text = L["SOUND_EVENT_ONALPHADEC"],
desc = L["SOUND_EVENT_ONALPHADEC_DESC"],
settings = {
Operator = true,
Value = true,
CndtJustPassed = true,
PassingCndt = true,
},
valueName = L["ALPHA"],
valueSuffix = "%",
conditionChecker = function(icon, eventSettings)
return TMW.CompareFuncs[eventSettings.Operator](icon.attributes.realAlpha * 100, eventSettings.Value)
end,
})
function Processor:CompileFunctionSegment(t)
-- GLOBALS: realAlpha
t[#t+1] = [[
if realAlpha ~= attributes.realAlpha then
local oldalpha = attributes.realAlpha or 0
attributes.realAlpha = realAlpha
-- detect events that occured, and handle them if they did
if realAlpha == 0 then
if EventHandlersSet.OnHide then
icon:QueueEvent("OnHide")
end
elseif oldalpha == 0 then
if EventHandlersSet.OnShow then
icon:QueueEvent("OnShow")
end
elseif realAlpha > oldalpha then
if EventHandlersSet.OnAlphaInc then
icon:QueueEvent("OnAlphaInc")
end
else -- it must be less than, because it isnt greater than and it isnt the same
if EventHandlersSet.OnAlphaDec then
icon:QueueEvent("OnAlphaDec")
end
end
TMW:Fire(REALALPHA.changedEvent, icon, realAlpha, oldalpha)
doFireIconUpdated = true
end
--]]
end
TMW:RegisterCallback("TMW_INITIALIZE", function()
local IconPosition_Sortable = TMW.C.GroupModule_IconPosition_Sortable
if IconPosition_Sortable then
IconPosition_Sortable:RegisterIconSorter("alpha", {
DefaultOrder = -1,
[1] = L["UIPANEL_GROUPSORT_alpha_1"],
[-1] = L["UIPANEL_GROUPSORT_alpha_-1"],
}, function(iconA, iconB, attributesA, attributesB, order)
local a, b = attributesA.realAlpha, attributesB.realAlpha
if a ~= b then
return a*order < b*order
end
end)
IconPosition_Sortable:RegisterIconSorter("shown", {
DefaultOrder = -1,
[1] = L["UIPANEL_GROUPSORT_shown_1"],
[-1] = L["UIPANEL_GROUPSORT_shown_-1"],
}, function(iconA, iconB, attributesA, attributesB, order)
local a, b = (attributesA.shown and attributesA.realAlpha > 0) and 1 or 0, (attributesB.shown and attributesB.realAlpha > 0) and 1 or 0
if a ~= b then
return a*order < b*order
end
end)
IconPosition_Sortable:RegisterIconSortPreset(L["UIPANEL_GROUP_QUICKSORT_SHOWN"], {
{ Method = "shown", Order = -1 },
{ Method = "id", Order = 1 }
})
end
end)
Processor:RegisterDogTag("TMW", "IsShown", {
code = function(icon)
icon = TMW.GUIDToOwner[icon]
if icon then
local attributes = icon.attributes
return not not attributes.shown and attributes.realAlpha > 0
else
return false
end
end,
arg = {
'icon', 'string', '@req',
},
events = TMW:CreateDogTagEventString("SHOWN", "REALALPHA"),
ret = "boolean",
doc = L["DT_DOC_IsShown"] .. "\r\n \r\n" .. L["DT_INSERTGUID_GENERIC_DESC"],
example = '[IsShown] => "true"; [IsShown(icon="TMW:icon:1I7MnrXDCz8T")] => "false"',
category = L["ICON"],
})
Processor:RegisterDogTag("TMW", "Opacity", {
code = function(icon)
icon = TMW.GUIDToOwner[icon]
if icon then
return icon.attributes.realAlpha
else
return 0
end
end,
arg = {
'icon', 'string', '@req',
},
events = TMW:CreateDogTagEventString("REALALPHA"),
ret = "number",
doc = L["DT_DOC_Opacity"] .. "\r\n \r\n" .. L["DT_INSERTGUID_GENERIC_DESC"],
example = '[Opacity] => "1"; [Opacity(icon="TMW:icon:1I7MnrXDCz8T")] => "0.42"',
category = L["ICON"],
})
end
-- CONDITION: "conditionFailed"
do
local Processor = TMW.Classes.IconDataProcessor:New("CONDITION", "conditionFailed")
Processor.dontInherit = true
-- Processor:CompileFunctionSegment(t) is default.
end
-- DURATION: "start, duration"
do
local Processor = TMW.Classes.IconDataProcessor:New("DURATION", "start, duration")
Processor:DeclareUpValue("OnGCD", TMW.OnGCD)
TMW.Classes.Icon.attributes.start = 0
TMW.Classes.Icon.attributes.duration = 0
Processor:RegisterIconEvent(21, "OnStart", {
category = L["EVENT_CATEGORY_TIMER"],
text = L["SOUND_EVENT_ONSTART"],
desc = L["SOUND_EVENT_ONSTART_DESC"],
})
Processor:RegisterIconEvent(22, "OnFinish", {
category = L["EVENT_CATEGORY_TIMER"],
text = L["SOUND_EVENT_ONFINISH"],
desc = L["SOUND_EVENT_ONFINISH_DESC"],
})
Processor:RegisterIconEvent(23, "OnDuration", {
category = L["EVENT_CATEGORY_TIMER"],
text = L["SOUND_EVENT_ONDURATION"],
desc = L["SOUND_EVENT_ONDURATION_DESC"],
settings = {
Operator = true,
Value = true,
CndtJustPassed = function(check)
check:Disable()
check:SetAlpha(1)
end,
PassingCndt = function(check)
check:Disable()
check:SetAlpha(1)
end,
},
blacklistedOperators = {
["~="] = true,
["=="] = true,
},
valueName = L["DURATION"],
conditionChecker = function(icon, eventSettings)
local attributes = icon.attributes
local d = attributes.duration - (TMW.time - attributes.start)
d = d > 0 and d or 0
return TMW.CompareFuncs[eventSettings.Operator](d, eventSettings.Value)
end,
applyDefaultsToSetting = function(EventSettings)
EventSettings.CndtJustPassed = true
EventSettings.PassingCndt = true
end,
})
function Processor:CompileFunctionSegment(t)
-- GLOBALS: start, duration
t[#t+1] = [[
duration = duration or 0
start = start or 0
if duration == 0.001 then duration = 0 end -- hardcode fix for tricks of the trade. nice hardcoding on your part too, blizzard
local d
if start == TMW.time then
d = duration
else
d = duration - (TMW.time - start)
end
d = d > 0 and d or 0
if EventHandlersSet.OnDuration then
if d ~= icon.__lastDur then
icon:QueueEvent("OnDuration")
icon.__lastDur = d
end
end
if attributes.start ~= start or attributes.duration ~= duration then
local realDuration = icon:OnGCD(duration) and 0 or duration -- the duration of the cooldown, ignoring the GCD
if icon.__realDuration ~= realDuration then
-- detect events that occured, and handle them if they did
if realDuration == 0 then
if EventHandlersSet.OnFinish then
icon:QueueEvent("OnFinish")
end
else
if EventHandlersSet.OnStart then
icon:QueueEvent("OnStart")
end
end
icon.__realDuration = realDuration
end
attributes.start = start
attributes.duration = duration
TMW:Fire(DURATION.changedEvent, icon, start, duration, d)
doFireIconUpdated = true
end
--]]
end
function Processor:OnImplementIntoIcon(icon)
if icon.EventHandlersSet.OnDuration then
for _, EventSettings in TMW:InNLengthTable(icon.Events) do
if EventSettings.Event == "OnDuration" then
self:RegisterDurationTrigger(icon, EventSettings.Value)
end
end
end
end
---------------------------------
-- Duration triggers
---------------------------------
-- Duration triggers. Register a duration trigger to cause a call to
-- icon:SetInfo("start, duration", icon.attributes.start, icon.attributes.duration)
-- when the icon reaches the specified duration.
local DurationTriggers = {}
Processor.DurationTriggers = DurationTriggers
function Processor:RegisterDurationTrigger(icon, duration)
if not DurationTriggers[icon] then
DurationTriggers[icon] = {}
end
if not TMW.tContains(DurationTriggers[icon], duration) then
tinsert(DurationTriggers[icon], duration)
end
end
function Processor:OnUnimplementFromIcon(icon)
if DurationTriggers[icon] then
wipe(DurationTriggers[icon])
end
end
TMW:RegisterCallback("TMW_ONUPDATE_TIMECONSTRAINED_PRE", function(event, time, Locked)
for icon, durations in pairs(DurationTriggers) do
if #durations > 0 then
local lastCheckedDuration = durations.last or 0
local currentIconDuration = icon.attributes.duration - (time - icon.attributes.start)
if currentIconDuration < 0 then currentIconDuration = 0 end
-- If the duration didn't change (i.e. it is 0) then don't even try.
if currentIconDuration ~= lastCheckedDuration then
for i = 1, #durations do
local durationToCheck = durations[i]
-- print(icon, currentIconDuration, lastCheckedDuration, durationToCheck)
if currentIconDuration <= durationToCheck and -- Make sure we are at or have passed the duration we want to trigger at
(lastCheckedDuration > durationToCheck -- Make sure that we just reached this duration (so it doesn't continually fire)
or lastCheckedDuration < currentIconDuration -- or make sure that the duration increased since the last time we checked the triggers.
) then
if icon:IsControlled() then
icon.group.Controller.NextUpdateTime = 0
else
icon.NextUpdateTime = 0
end
-- print(icon, "TRIGGER")
--icon:Update()
--icon:SetInfo("start, duration", icon.attributes.start, icon.attributes.duration)
break
end
end
end
durations.last = currentIconDuration
end
end
end)
TMW:RegisterCallback("TMW_INITIALIZE", function()
local IconPosition_Sortable = TMW.C.GroupModule_IconPosition_Sortable
if IconPosition_Sortable then
IconPosition_Sortable:RegisterIconSorter("duration", {
DefaultOrder = 1,
[1] = L["UIPANEL_GROUPSORT_duration_1"],
[-1] = L["UIPANEL_GROUPSORT_duration_-1"],
}, function(iconA, iconB, attributesA, attributesB, order)
local time = TMW.time
local durationA = attributesA.duration
local durationB = attributesB.duration
durationA = iconA:OnGCD(durationA) and 0 or durationA - (time - attributesA.start)
durationB = iconB:OnGCD(durationB) and 0 or durationB - (time - attributesB.start)
if durationA ~= durationB then
return durationA*order < durationB*order
end
end)
IconPosition_Sortable:RegisterIconSortPreset(L["UIPANEL_GROUP_QUICKSORT_DURATION"], {
{ Method = "shown", Order = -1 },
{ Method = "duration", Order = 1 },
{ Method = "id", Order = 1 }
})
end
end)
local OnGCD = TMW.OnGCD
Processor:RegisterDogTag("TMW", "Duration", {
code = function(icon, gcd)
icon = TMW.GUIDToOwner[icon]
if icon then
local attributes = icon.attributes
local duration = attributes.duration
local remaining = duration - (TMW.time - attributes.start)
if remaining <= 0 or (not gcd and icon:OnGCD(duration)) then
return 0
end
-- cached version of tonumber()
return isNumber[format("%.1f", remaining)] or 0
else
return 0
end
end,
arg = {
'icon', 'string', '@req',
'gcd', 'boolean', true,
},
events = "FastUpdate",
ret = "number",
doc = L["DT_DOC_Duration"] .. "\r\n \r\n" .. L["DT_INSERTGUID_GENERIC_DESC"],
example = '[Duration] => "1.435"; [Duration(gcd=false)] => "0"; [Duration:TMWFormatDuration] => "1.4"; [Duration(icon="TMW:icon:1I7MnrXDCz8T")] => "97.32156"; [Duration(icon="TMW:icon:1I7MnrXDCz8T"):TMWFormatDuration] => "1:37"',
category = L["ICON"],
})
TMW:RegisterCallback("TMW_ICON_SETUP_POST", function(event, icon)
if not TMW.Locked then
icon:SetInfo("start, duration", 0, 0)
end
end)
end
-- REVERSE: "reverse"
do
local Processor = TMW.Classes.IconDataProcessor:New("REVERSE", "reverse")
-- Processor:CompileFunctionSegment(t) is default.
TMW:RegisterCallback("TMW_ICON_DISABLE", function(event, icon)
icon:SetInfo("reverse", nil)
end)
end
-- SPELL: "spell"
do
local Processor = TMW.Classes.IconDataProcessor:New("SPELL", "spell")
function Processor:CompileFunctionSegment(t)
-- GLOBALS: spell
t[#t+1] = [[
if attributes.spell ~= spell then
attributes.spell = spell
if EventHandlersSet.OnSpell then
icon:QueueEvent("OnSpell")
end
TMW:Fire(SPELL.changedEvent, icon, spell)
doFireIconUpdated = true
end
--]]
end
Processor:RegisterIconEvent(31, "OnSpell", {
category = L["EVENT_CATEGORY_CHANGED"],
text = L["SOUND_EVENT_ONSPELL"],
desc = L["SOUND_EVENT_ONSPELL_DESC"],
})
Processor:RegisterDogTag("TMW", "Spell", {
code = function(icon, link)
icon = TMW.GUIDToOwner[icon]
if icon then
local name, checkcase = icon.typeData:FormatSpellForOutput(icon, icon.attributes.spell, link)
name = name or ""
if checkcase and name ~= "" then
name = TMW:RestoreCase(name)
end
return name
else
return ""
end
end,
arg = {
'icon', 'string', '@req',
'link', 'boolean', false,
},
events = TMW:CreateDogTagEventString("SPELL"),
ret = "string",
doc = L["DT_DOC_Spell"] .. "\r\n \r\n" .. L["DT_INSERTGUID_GENERIC_DESC"],
example = ('[Spell] => %q; [Spell(link=true)] => %q; [Spell(icon="TMW:icon:1I7MnrXDCz8T")] => %q; [Spell(icon="TMW:icon:1I7MnrXDCz8T", link=true)] => %q'):format(GetSpellInfo(2139), GetSpellLink(2139), GetSpellInfo(1766), GetSpellLink(1766)),
category = L["ICON"],
})
TMW:RegisterCallback("TMW_ICON_DISABLE", function(event, icon)
icon:SetInfo("spell", nil)
end)
end
-- SPELLCHARGES: "charges, maxCharges"
do
local Processor = TMW.Classes.IconDataProcessor:New("SPELLCHARGES", "charges, maxCharges")
function Processor:CompileFunctionSegment(t)
-- GLOBALS: charges, maxCharges
t[#t+1] = [[
if attributes.charges ~= charges or attributes.maxCharges ~= maxCharges then
attributes.charges = charges
attributes.maxCharges = maxCharges
TMW:Fire(SPELLCHARGES.changedEvent, icon, charges, maxCharges)
doFireIconUpdated = true
end
--]]
end
TMW:RegisterCallback("TMW_ICON_DISABLE", function(event, icon)
icon:SetInfo("charges, maxCharges", nil, nil)
end)
end
-- VALUE: "value, maxValue, valueColor"
do
local Processor = TMW.Classes.IconDataProcessor:New("VALUE", "value, maxValue, valueColor")
function Processor:CompileFunctionSegment(t)
-- GLOBALS: value, maxValue, valueColor
t[#t+1] = [[
if attributes.value ~= value or attributes.maxValue ~= maxValue or attributes.valueColor ~= valueColor then
attributes.value = value
attributes.maxValue = maxValue
attributes.valueColor = valueColor
TMW:Fire(VALUE.changedEvent, icon, value, maxValue, valueColor)
doFireIconUpdated = true
end
--]]
end
TMW:RegisterCallback("TMW_ICON_DISABLE", function(event, icon)
icon:SetInfo("value, maxValue, valueColor", nil, nil, nil)
end)
TMW:RegisterCallback("TMW_INITIALIZE", function()
local IconPosition_Sortable = TMW.C.GroupModule_IconPosition_Sortable
if IconPosition_Sortable then
IconPosition_Sortable:RegisterIconSorter("value", {
DefaultOrder = -1,
[1] = L["UIPANEL_GROUPSORT_value_1"],
[-1] = L["UIPANEL_GROUPSORT_value_-1"],
}, function(iconA, iconB, attributesA, attributesB, order)
local a, b = attributesA.value, attributesB.value
if a ~= b then
return a*order < b*order
end
end)
IconPosition_Sortable:RegisterIconSorter("valuep", {
DefaultOrder = -1,
[1] = L["UIPANEL_GROUPSORT_valuep_1"],
[-1] = L["UIPANEL_GROUPSORT_valuep_-1"],
}, function(iconA, iconB, attributesA, attributesB, order)
if attributesA.maxValue == 0 or attributesB.maxValue == 0 then
return false
end
local a, b = attributesA.value / attributesA.maxValue, attributesB.value / attributesB.maxValue
if a ~= b then
return a*order < b*order
end
end)
end
end)
Processor:RegisterDogTag("TMW", "Value", {
code = function(icon)
icon = TMW.GUIDToOwner[icon]
local value = icon and icon.attributes.value or 0
return isNumber[value] or value
end,
arg = {
'icon', 'string', '@req',
},
events = TMW:CreateDogTagEventString("VALUE"),
ret = "number",
doc = L["DT_DOC_Value"] .. "\r\n \r\n" .. L["DT_INSERTGUID_GENERIC_DESC"],
example = '[Value] => "256891"; [Value(icon="TMW:icon:1I7MnrXDCz8T")] => "2"',
category = L["ICON"],
})
Processor:RegisterDogTag("TMW", "ValueMax", {
code = function(icon)
icon = TMW.GUIDToOwner[icon]
local maxValue = icon and icon.attributes.maxValue or 0
return isNumber[maxValue] or maxValue
end,
arg = {
'icon', 'string', '@req',
},
events = TMW:CreateDogTagEventString("VALUE"),
ret = "number",
doc = L["DT_DOC_ValueMax"] .. "\r\n \r\n" .. L["DT_INSERTGUID_GENERIC_DESC"],
example = '[ValueMax] => "312856"; [ValueMax(icon="TMW:icon:1I7MnrXDCz8T")] => "3"',
category = L["ICON"],
})
end
-- STACK: "stack, stackText"
do
local Processor = TMW.Classes.IconDataProcessor:New("STACK", "stack, stackText")
function Processor:CompileFunctionSegment(t)
--GLOBALS: stack, stackText
t[#t+1] = [[
if attributes.stack ~= stack or attributes.stackText ~= stackText then
local old = attributes.stack
attributes.stack = stack
attributes.stackText = stackText
if EventHandlersSet.OnStack then
icon:QueueEvent("OnStack")
end
if (not old or (stack and stack > old)) and EventHandlersSet.OnStackIncrease then
icon:QueueEvent("OnStackIncrease")
elseif (not stack or (old and stack < old)) and EventHandlersSet.OnStackDecrease then
icon:QueueEvent("OnStackDecrease")
end
TMW:Fire(STACK.changedEvent, icon, stack, stackText)
doFireIconUpdated = true
end
--]]
end
Processor:RegisterIconEvent(51, "OnStack", {
category = L["EVENT_CATEGORY_CHANGED"],
text = L["SOUND_EVENT_ONSTACK"],
desc = L["SOUND_EVENT_ONSTACK_DESC"],
settings = {
Operator = true,
Value = true,
CndtJustPassed = true,
PassingCndt = true,
},
valueName = L["STACKS"],
conditionChecker = function(icon, eventSettings)
local count = icon.attributes.stack or 0
return TMW.CompareFuncs[eventSettings.Operator](count, eventSettings.Value)
end,
})
Processor:RegisterIconEvent(51.1, "OnStackIncrease", {
category = L["EVENT_CATEGORY_CHANGED"],
text = L["SOUND_EVENT_ONSTACKINC"],
desc = L["SOUND_EVENT_ONSTACK_DESC"],
settings = {
Operator = true,
Value = true,
CndtJustPassed = true,
PassingCndt = true,
},
valueName = L["STACKS"],
conditionChecker = function(icon, eventSettings)
local count = icon.attributes.stack or 0
return TMW.CompareFuncs[eventSettings.Operator](count, eventSettings.Value)
end,
})
Processor:RegisterIconEvent(51.2, "OnStackDecrease", {
category = L["EVENT_CATEGORY_CHANGED"],
text = L["SOUND_EVENT_ONSTACKDEC"],
desc = L["SOUND_EVENT_ONSTACK_DESC"],
settings = {
Operator = true,
Value = true,
CndtJustPassed = true,
PassingCndt = true,
},
valueName = L["STACKS"],
conditionChecker = function(icon, eventSettings)
local count = icon.attributes.stack or 0
return TMW.CompareFuncs[eventSettings.Operator](count, eventSettings.Value)
end,
})
Processor:RegisterDogTag("TMW", "Stacks", {
code = function(icon)
icon = TMW.GUIDToOwner[icon]
local stacks = icon and icon.attributes.stackText or 0
return isNumber[stacks] or stacks
end,
arg = {
'icon', 'string', '@req',
},
events = TMW:CreateDogTagEventString("STACK"),
ret = "number",
doc = L["DT_DOC_Stacks"] .. "\r\n \r\n" .. L["DT_INSERTGUID_GENERIC_DESC"],
example = '[Stacks] => "9"; [Stacks(icon="TMW:icon:1I7MnrXDCz8T")] => "3"',
category = L["ICON"],
})
TMW:RegisterCallback("TMW_INITIALIZE", function()
local IconPosition_Sortable = TMW.C.GroupModule_IconPosition_Sortable
if IconPosition_Sortable then
IconPosition_Sortable:RegisterIconSorter("stacks", {
DefaultOrder = -1,
[1] = L["UIPANEL_GROUPSORT_stacks_1"],
[-1] = L["UIPANEL_GROUPSORT_stacks_-1"],
}, function(iconA, iconB, attributesA, attributesB, order)
local a, b = attributesA.stack or 0, attributesB.stack or 0
if a ~= b then
return a*order < b*order
end
end)
end
end)
TMW:RegisterCallback("TMW_ICON_SETUP_POST", function(event, icon)
if not TMW.Locked then
icon:SetInfo("stack, stackText", nil, nil)
end
end)
TMW:RegisterCallback("TMW_ICON_DISABLE", function(event, icon)
icon:SetInfo("stack, stackText", nil, nil)
end)
end
-- TEXTURE: "texture"
do
local Processor = TMW.Classes.IconDataProcessor:New("TEXTURE", "texture")
function Processor:CompileFunctionSegment(t)
-- GLOBALS: texture
t[#t+1] = [[
if texture ~= nil and attributes.texture ~= texture then
attributes.texture = texture
TMW:Fire(TEXTURE.changedEvent, icon, texture)
doFireIconUpdated = true
end
--]]
end
end
-- UNIT: "unit, GUID"
do
local Processor = TMW.Classes.IconDataProcessor:New("UNIT", "unit, GUID")
Processor:DeclareUpValue("UnitGUID", UnitGUID)
Processor:DeclareUpValue("playerGUID", UnitGUID('player'))
function Processor:CompileFunctionSegment(t)
-- GLOBALS: unit, GUID
t[#t+1] = [[
GUID = GUID or (unit and (unit == "player" and playerGUID or UnitGUID(unit)))
if attributes.unit ~= unit or attributes.GUID ~= GUID then
local previousUnit = attributes.unit
attributes.previousUnit = previousUnit
attributes.unit = unit
attributes.GUID = GUID
if EventHandlersSet.OnUnit then
icon:QueueEvent("OnUnit")
end
TMW:Fire(UNIT.changedEvent, icon, unit, previousUnit, GUID)
doFireIconUpdated = true
end
--]]
end
Processor:RegisterIconEvent(41, "OnUnit", {
category = L["EVENT_CATEGORY_CHANGED"],
text = L["SOUND_EVENT_ONUNIT"],
desc = L["SOUND_EVENT_ONUNIT_DESC"],
})
Processor:RegisterDogTag("TMW", "Unit", {
code = function(icon)
icon = TMW.GUIDToOwner[icon]
if icon then
return icon.attributes.unit or ""
else
return ""
end
end,
arg = {
'icon', 'string', '@req',
},
events = TMW:CreateDogTagEventString("UNIT"),
ret = "string",
doc = L["DT_DOC_Unit"] .. "\r\n \r\n" .. L["DT_INSERTGUID_GENERIC_DESC"],
example = '[Unit] => "target"; [Unit:Name] => "Kobold"; [Unit(icon="TMW:icon:1I7MnrXDCz8T")] => "focus"; [Unit(icon="TMW:icon:1I7MnrXDCz8T"):Name] => "Gamon"',
category = L["ICON"],
})
Processor:RegisterDogTag("TMW", "PreviousUnit", {
code = function(icon)
icon = TMW.GUIDToOwner[icon]
if icon then
return icon.__lastUnitChecked or ""
else
return ""
end
end,
arg = {
'icon', 'string', '@req',
},
events = TMW:CreateDogTagEventString("UNIT"),
ret = "string",
doc = L["DT_DOC_PreviousUnit"] .. "\r\n \r\n" .. L["DT_INSERTGUID_GENERIC_DESC"],
example = '[PreviousUnit] => "target"; [PreviousUnit:Name] => "Kobold"; [PreviousUnit(icon="TMW:icon:1I7MnrXDCz8T")] => "focus"; [PreviousUnit(icon="TMW:icon:1I7MnrXDCz8T"):Name] => "Gamon"',
category = L["ICON"],
})
TMW:RegisterCallback("TMW_ICON_DISABLE", function(event, icon)
icon:SetInfo("unit, GUID", nil, nil)
end)
end
-- DOGTAGUNIT: "dogTagUnit"
do
local DogTag = LibStub("LibDogTag-3.0")
local Processor = TMW.Classes.IconDataProcessor:New("DOGTAGUNIT", "dogTagUnit")
Processor:AssertDependency("UNIT")
--Here's the hook (the whole point of this thing)
local Hook = TMW.Classes.IconDataProcessorHook:New("UNIT_DOGTAGUNIT", "UNIT")
Hook:DeclareUpValue("DogTag", DogTag)
Hook:DeclareUpValue("TMW_UNITS", TMW.UNITS)
Hook:RegisterCompileFunctionSegmentHook("post", function(Processor, t)
-- GLOBALS: unit
t[#t+1] = [[
local dogTagUnit
local typeData = icon.typeData
if not typeData or typeData.unitType == "unitid" then
dogTagUnit = unit
if not DogTag.IsLegitimateUnit[dogTagUnit] then
dogTagUnit = dogTagUnit and TMW_UNITS:TestUnit(dogTagUnit)
if not DogTag.IsLegitimateUnit[dogTagUnit] then
dogTagUnit = "player"
end
end
else
dogTagUnit = "player"
end
if attributes.dogTagUnit ~= dogTagUnit then
doFireIconUpdated = icon:SetInfo_INTERNAL("dogTagUnit", dogTagUnit) or doFireIconUpdated
end
--]]
end)
end
|
return {'jabot','jabotjes','jabroer','jabbeke','jaber','jabbar','jabotje','jabots','jabroers','jabers'} |
--[[
Copyright (C) 2019 Blue Mountains GmbH
This program is free software: you can redistribute it and/or modify it under the terms of the Onset
Open Source License as published by Blue Mountains GmbH.
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 Onset Open Source License for more details.
You should have received a copy of the Onset Open Source License along with this program. If not,
see https://bluemountains.io/Onset_OpenSourceSoftware_License.txt
]]--
local StreamedAtmIds = { }
local AtmIds = { }
AddRemoteEvent("banking:atmsetup", function(AtmObjects)
AtmIds = AtmObjects
-- Reset the table
StreamedAtmIds = { }
for _,v in pairs(AtmIds) do
-- IsValidObject returns true on the client if this object is streamed in
if IsValidObject(v) then
table.insert(StreamedAtmIds, v)
end
end
end)
AddEvent("OnObjectStreamIn", function(object)
for _,v in pairs(AtmIds) do
if object == v then
table.insert(StreamedAtmIds, v)
break
end
end
end)
AddEvent("OnObjectStreamOut", function(object)
for _,v in pairs(AtmIds) do
if object == v then
table.remove(StreamedAtmIds, tablefind(StreamedAtmIds, v))
break
end
end
end)
local function OnKeyPress(key)
if key == "E" then
local NearestATM = GetNearestATM()
if NearestATM ~= 0 then
CallRemoteEvent("banking:atminteract", NearestATM)
end
end
end
AddEvent("OnKeyPress", OnKeyPress)
function OnBankingWithdrawMoney(value)
CallRemoteEvent("banking:withdraw", math.tointeger(value))
end
AddEvent("OnBankingWithdrawMoney", OnBankingWithdrawMoney)
function GetNearestATM()
local x, y, z = GetPlayerLocation()
for _,v in pairs(StreamedAtmIds) do
local x2, y2, z2 = GetObjectLocation(v)
local dist = GetDistance3D(x, y, z, x2, y2, z2)
if dist < 160.0 then
return v
end
end
return 0
end
function tablefind(tab, el)
for index, value in pairs(tab) do
if value == el then
return index
end
end
end
|
return {
id = "epiccowboy",
name = "Epic Flaming Cowboy Hat of Great Justice",
description = "Feed the flames of justice!",
type = "hat",
rarity = 5,
hidden = false,
}
|
package("curl")
set_homepage("https://curl.se/")
set_description("A command line tool and library for transferring data with URLs")
add_urls("http://117.143.63.254:9012/www/rt-smart/packages/curl-$(version).tar.gz")
add_versions("7.70.0", "ca2feeb8ef13368ce5d5e5849a5fd5e2dd4755fecf7d8f0cc94000a4206fb8e7")
add_patches("7.70.0", path.join(os.scriptdir(), "patches", "7.70.0", "1-rtt-console.patch"), "651617be760341e025a9e4d68278f75b60e856d22558f7e89ba3de30aee2bb0b")
add_deps("zlib", "openssl")
on_install("cross", function (package)
local CROSS_COMPILE="arm-linux-musleabi"
local configs = {"--prefix=" .. package:installdir(), "--target=" .. CROSS_COMPILE, "--host=" .. CROSS_COMPILE, "--build=i686-pc-linux-gnu", "--with-ssl", "--with-zlib"}
local buildenvs = import("package.tools.autoconf").buildenvs(package)
buildenvs.CFLAGS = path.join(buildenvs.CFLAGS, " -I", package:dep("zlib"):installdir("include"), " -I", package:dep("openssl"):installdir("include"))
buildenvs.LIBS = path.join(buildenvs.LDFLAGS, " -static -Wl,--start-group -lc -lgcc -lrtthread -Wl,--end-group")
buildenvs.LDFLAGS = path.join("-L", package:dep("zlib"):installdir("lib"), " -L", package:dep("openssl"):installdir("lib"))
os.vrunv("./configure", configs, {envs = buildenvs})
local makeconfigs = {V=1, CFLAGS = buildenvs.CFLAGS, LDFLAGS = buildenvs.LDFLAGS, LIBS = buildenvs.LIBS}
import("package.tools.make").install(package, makeconfigs)
end)
on_test(function (package)
assert(os.isfile(path.join(package:installdir("bin"), "curl")))
end)
|
core:module("CoreMenuData")
Hooks:Register("CoreMenuData.LoadData")
function Data:_load_data(root, menu_id)
-- Find the child menu with id = menu_id
local menu
for _,c in ipairs(root) do
if c._meta == "menu" and c.id and c.id == menu_id then
menu = c
break
end
end
-- Call a hook here to let us mutate the menu data before it is parsed
Hooks:Call("CoreMenuData.LoadDataMenu", menu_id, menu)
-- Parse the nodes
if menu then
for _,c in ipairs(menu) do
local type = c._meta
if type == "node" then
self:_create_node(file_path, menu_id, c)
elseif type == "default_node" then
self._default_node_name = c.name
end
end
end
end
function Data:load_data(file_path, menu_id)
if PackageManager:has(Idstring("menu"), file_path:id()) then
self:_load_data(PackageManager:script_data(Idstring("menu"), file_path:id()), menu_id)
end
end
function Data:_create_node(file_path, menu_id, c)
local node_class = CoreMenuNode.MenuNode
local type = c.type
if type then
node_class = CoreSerialize.string_to_classtable(type)
end
local name = c.name
if name then
self._nodes[name] = node_class:new(c)
else
Application:error("Menu node without name in '" .. menu_id .. "' in '" .. file_path .. "'")
end
end |
-- This script template has each of the script entry point functions.
-- They are described in detail in VR-Forces Configuration Guide.
-- Some basic VRF Utilities defined in a common module.
require "vrfutil"
-- Global Variables. Global variables get saved when a scenario gets checkpointed.
-- They get re-initialized when a checkpointed scenario is loaded.
-- Current fuel state , denoting ranges rather than fenceposts:
-- 'tiger' - all good/more than the joker parameter
-- 'joker' - less than joker parameter but more than bingo
-- 'bingo' - less than the bingo parameter
state = "tiger"
last_estimate = "tiger"
-- Number of ticks that the state estimate has returned the same state
ticks_stable = 0
-- Task Id for RTB operations
rtb_tid = -1
-- Number of ticks estimations must remain stable for a state change
local required_stable_ticks = 5
-- Task Parameters Available in Script
-- taskParameters.parent Type: Simulation Object - This Embedded Entity's parent object name. (The unit that can recover it.)
-- taskParameters.eeName Type: String - This Embedded Entity's embedded entity name - basically how the parent addresses it within the context of the Embedded Entity system.
-- taskParameters.fuelEcon Type: Real - Km traveled per unit fuel. Usually 1.
-- taskParameters.bingo Type: Real - The fuel safety margin to add to usage estimates before RTB.
-- taskParameters.joker Type: Real - As with bingo fuel but for status messaging. Will be ignored if not greater than bingo fuel.
-- taskParameters.reactivetask_priority Type: Integer
-- taskParameters.reactivetask_enabled Type: Bool (on/off)
function paramsValid()
-- Ideally we'd also check eeName from here, but there's no way to do so.
return taskParameters.parent:isValid()
end
function distToParentInKm()
local myLoc = this:getLocation3D()
local parLoc = taskParameters.parent:getLocation3D()
return myLoc:distanceToLocation3D(parLoc) / 1000
end
function estimateRtbFuel()
return distToParentInKm() / taskParameters.fuelEcon
end
function remainingFuel()
current, full = this:getResourceAmounts("movement|fuel")
return current
end
function estimateFuelState()
local remain = remainingFuel()
local needed = estimateRtbFuel()
if needed + taskParameters.bingo > remain then
return "bingo"
end
if needed + taskParameters.joker > remain then
return "joker"
end
return "tiger"
end
-- Called when reactive task is enabled or changes to the enabled state.
function checkInit()
-- Set the tick period for this script while checking.
vrf:setTickPeriod(0.5)
end
-- Called each tick period for this script while enabled but not in the active state.
function check()
if not paramsValid() then
printWarn("Unable to continue monitoring fuel use...")
vrf:executeSetData("set-reactive-task-disabled", {script_id = "Bingo_Fuel_Monitor", cancel_now = true})
return false
end
local estimate = estimateFuelState()
if estimate ~= last_estimate then
last_estimate = estimate
ticks_stable = 0
return false
end
ticks_stable = ticks_stable + 1
if estimate == state then
return false
end
if ticks_stable < required_stable_ticks then
return false
end
-- Finally we're down to the actual state transitions.
state = estimate
if state == "tiger" then
printInfo("Detected fuel resource reset.")
return false
end
if state == "joker" then
printWarn("Reached Joker fuel condition.")
return false
end
if state == "bingo" then
printWarn("Reached Bingo fuel condition, returning to base")
return true
end
-- Returning true will cause the reactive task to become active and will call init()
-- and tick() until the task completes.
return false
end
-- Called when the task first starts. Never called again.
function init()
-- Set the tick period for this script.
vrf:setTickPeriod(0.5)
end
-- Called each tick while this task is active.
function tick()
if not (state == "bingo") then
printWarn("This reactive task should not be called directly.")
vrf:endTask(false)
return
end
if rtb_tid < 0 then
local parent = taskParameters.parent
printInfo("Recovering '"..taskParameters.eeName.."'.")
rtb_tid = vrf:sendTask(parent, "recover-embedded-entity", {embeddedEntityName = taskParameters.eeName}, true)
end
if not vrf:isTaskRunning(rtb_tid) then
vrf:endTask(vrf:taskResult(rtb_tid))
end
end
-- Called when this task is being suspended, likely by a reaction activating.
function suspend()
-- By default, halt all subtasks and other entity tasks started by this task when suspending.
vrf:stopAllSubtasks()
vrf:stopAllTasks()
end
-- Called when this task is being resumed after being suspended.
function resume()
-- By default, simply call init() to start the task over.
init()
end
-- Called immediately before a scenario checkpoint is saved when
-- this task is active.
-- It is typically not necessary to add code to this function.
function saveState()
end
-- Called immediately after a scenario checkpoint is loaded in which
-- this task is active.
-- It is typically not necessary to add code to this function.
function loadState()
end
-- Called when this task is ending, for any reason.
-- It is typically not necessary to add code to this function.
function shutdown()
end
-- Called whenever the entity receives a text report message while
-- this task is active.
-- message is the message text string.
-- sender is the SimObject which sent the message.
function receiveTextMessage(message, sender)
end
|
-- downloaded from https://gist.github.com/tarleb/afee1b1d97e52aca888f410e77b3624a
local List = require 'pandoc.List'
local utils = require 'pandoc.utils'
local stringify = utils.stringify
function highlighter(given_name_pattern, family_name_pattern)
local highlight_author = function (author)
local given = author.given and stringify(author.given)
local family = author.family and stringify(author.family)
if given and given:match(given_name_pattern) and
family and family:match(family_name_pattern) then
author.given = {pandoc.Strong(setmetatable(author.given, nil))}
author.family = {pandoc.Strong(setmetatable(author.family, nil))}
end
return author
end
return function(reference)
if reference.author and reference.author.map then
reference.author = reference.author:map(highlight_author)
end
return reference
end
end
function Pandoc (doc)
local meta = doc.meta
local fh = io.popen(
"pandoc-citeproc --bib2yaml "
.. stringify(meta.bibliography)
)
if io.type(fh) ~= 'file' then return end
local bibyaml = fh:read('*a')
fh:close()
local references = pandoc.read(bibyaml).meta.references
meta.bibliography = nil
meta.references = references:map(
highlighter(stringify(meta['given-name-pattern']),
stringify(meta['family-name-pattern']))
)
return utils.run_json_filter(
pandoc.Pandoc(doc.blocks, meta),
'pandoc-citeproc'
)
end |
-- Config (Server)
RegisterServerEvent('cnr:police_stations_req')
--- LoadPoliceStations()
-- Sends list of valid police stations to player (if given) or all players
-- @param client The client to send it to. Defaults to all clients if nil
local function LoadPoliceStations(client)
-- SQL: Return list of all stations that are law enforcement related
exports['ghmattimysql']:execute(
"SELECT st.cams,st.zone,st.id,st.agency_id,st.x,st.y,st.z,st.duty_point,a.blip_color,a.blip_sprite "..
"FROM stations st LEFT JOIN agencies a ON a.id = st.agency_id WHERE a.perms & 1",
{}, function(stationList)
local src = client
if not src then src = (-1) end
TriggerClientEvent('cnr:police_stations', src, stationList)
end
)
end
-- Used to trigger LoadPoliceStations()
AddEventHandler('cnr:client_loaded', function()
local client = source
LoadPoliceStations(client)
end)
-- Used to trigger LoadPoliceStations() on resource restart
Citizen.CreateThread(function()
Citizen.Wait(5000)
LoadPoliceStations()
end)
AddEventHandler('cnr:police_stations_req', function(stNumber)
local client = source
print("DEBUG - Player #"..client.." requesting Station #"..stNumber.." information.")
if stNumber then
if stNumber > 0 then
-- SQL: Return station information (armory, vehicles, etc)
exports['ghmattimysql']:execute(
"SELECT * FROM stations WHERE id = @n", {['n'] = stNumber},
function(stationInfo)
if not stationInfo then stationInfo = {} end
if not client then client = (-1) end
TriggerClientEvent('cnr:police_station_info', client, stationInfo[1])
print("DEBUG - Sent player station info: "..json.encode(stationInfo[1]))
end
)
end -- stNumber > 0
end -- stNumber
end) |
local require = require
local assert = assert
local ipairs = ipairs
local tostring = tostring
local coroutine = coroutine
local s_format = string.format
local t_concat = table.concat
local t_insert = table.insert
local n_log = ngx.log
local n_err = ngx.ERR
local n_debug = ngx.DEBUG
local quote_sql_str = ngx.quote_sql_str
-----> 外部引用
-- local c_json = require("cjson.safe")
local lpeg = require 'lpeg'
local r_mysql = require 'resty.mysql'
local o_func = require 'app.store.orm.func'
local namespace = "app.store.drivers.mysql"
local open = function(conf)
local _connect = function()
local db, err = r_mysql:new()
assert(not err, s_format("[%s.open._connect]Failed to create:%s", namespace, err))
local ok, err, errno, sqlstate = db:connect(conf)
assert(ok, s_format("[%s.open._connect]Failed to connect:%s,%s,%s", namespace, err, errno, sqlstate))
if conf.charset then
if db:get_reused_times() == 0 then
db:query("SET NAMES " .. conf.charset)
end
end
return {
conn = db;
query = function(self, str) return db:query(str) end;
set_timeout = function(self, ...) return db:set_timeout(...) end;
set_keepalive = function(self, ...) return db:set_keepalive(...) end;
start_transaction = function() return db:query('BEGIN') end;
commit = function() return db:query('COMMIT') end;
rollback = function() return db:query('ROLLBACK') end;
}
end
local function connect()
local key = "trans_" .. tostring(coroutine.running())
local conn = ngx.ctx[key]
if conn then
return true, conn
end
return false, _connect()
end
local config = function()
return conf
end
local query = function(query_str)
if conf.debug then
n_log(n_debug, s_format("[%s.open.query]SQL:%s", namespace, query_str))
end
local is_trans, db = connect()
db:set_timeout(conf.timeout) -- 1 sec
local res, err, errno, sqlstate = db:query(query_str)
if not res then
err = s_format("[%s.open.query]Bad result: %s,%s,%s", namespace, err, errno, sqlstate)
n_log(n_err, err)
return false, err
end
if err == 'again' then res = { res } end
while err == "again" do
local tmp
tmp, err, errno, sqlstate = db.conn:read_result()
if not tmp then
err = s_format("[%s.open.query.again]Bad result: %s,%s,%s", namespace, err, errno, sqlstate)
n_log(n_err, err)
return false, err
end
t_insert(res, tmp)
end
if not is_trans then
local ok, err = db.conn:set_keepalive(conf.pool_set.max_idle_timeout, conf.pool_set.pool_size)
if not ok then
n_log(n_err, s_format("[%s.open.query]Failed to set keepalive:%s", namespace, err))
end
end
return true, res
end
local escape_identifier = function(id)
local repl = '`%1`'
local openp, endp = lpeg.P'[', lpeg.P']'
local quote_pat = openp * lpeg.C(( 1 - endp)^1) * endp
return lpeg.Cs((quote_pat/repl + 1)^0):match(id)
end
local function escape_literal(val)
local typ = type(val)
if typ == 'boolean' then
return val and 1 or 0
elseif typ == 'string' then
return quote_sql_str(val)
elseif typ == 'number' then
return val
elseif typ == 'nil' then
return "NULL"
elseif typ == 'table' then
if val._type then
return tostring(val)
end
return t_concat(o_func.map(escape_literal, val), ', ')
else
return tostring(val)
end
end
local returning = function(column)
return nil
-- return column
end
local get_schema = function(table_name)
table_name = table_name:gsub('%[?([^%]]+)%]?', "'%1'")
local ok, res = query([[
SELECT column_name, data_type, column_key, character_maximum_length
FROM INFORMATION_SCHEMA.COLUMNS
WHERE table_name = ]]
.. table_name
.. ' GROUP BY column_name ') --' AND table_schema = ' .. escape_literal(conf.database)
assert(ok, res)
local fields = { }
for _, f in ipairs(res) do
fields[f.column_name] = f
-- MYCAT 分区会有多个主键产生,这里暂时先取消判断,改成以ID命名设置的主键为主
-- if f.column_key == 'PRI' then
-- if fields.__pk__ then
-- error(s_format("[%s.open.get_schema]Not implement for tables have multiple pk", namespace))
-- end
-- fields.__pk__ = f.column_name
-- end
if f.column_key == 'PRI' and string.lower(f.column_name) == "id" then
fields.__pk__ = f.column_name
end
end
return fields
end
local limit_all = function()
return '18446744073709551615'
end
return {
connect = connect;
query = query;
get_schema = get_schema;
config = config;
escape_identifier = escape_identifier;
escape_literal = escape_literal;
quote_sql_str = quote_sql_str;
returning = returning;
limit_all = limit_all;
}
end
return open
|
local action = require("game.battle.action.action")
local M = setmetatable({}, {__index = action})
M.super = action
M.__index = M
function M.new()
local o = setmetatable(action.new(), M)
o.type = actiondef.die
o.duration = 2
o.weight = 10
return o
end
function M:enter()
print(self.agent.id ," enter die:"..tostring(self.agent.position))
action.enter(self)
end
function M:execute(delta)
action.execute(self,delta)
end
function M:exit()
action.exit(self)
self:broadcast()
--print(self.agent.id ," exit die")
agentmgr:removeagent(self.agent.id)
end
function M:broadcast()
local data = {
id = self.agent.id,
copy = self.agent.copyid
}
copy:broadcast(msgid.BATTLE_ENTITY_DIE_NOTIFY,data)
end
return M |
local ten1s = tonumber( "1111111111", 2 )
return function ( cu1, cu2 )
return 0x10000 + ( ((cu1 & ten1s) << 10) | (cu2 & ten1s) )
end |
Point = Object:new{x, y}
function Point:copy()
return self:new{x = self.x, y = self.y}
end
function Point:X(x)
if x then self.x = x
else return self.x end
end
function Point:Y(y)
if y then self.y = y
else return self.y end
end
|
-- an example of a minimal scene
-- load resources including a two frame animation used as a button
-- copyright 2016 Samuel Baird MIT Licence
local class = require('core.class')
local app_node = require('lt.app_node')
local tween = require('lt.tween')
return class.derive(app_node, function (title_scene)
function title_scene:prepare()
app.resources.load_spritesheet('assets/output/', 'title')
end
function title_scene:begin()
-- centered background
local img = self.view:add_image('title_screen')
local x, y, width, height = img:bounds()
-- scale up on extreme screen sizes of aspect ratios
if app.screen.width > width then
img.scale_x = app.screen.width / width
end
if app.screen.height > height then
img.scale_y = app.screen.height / height
end
img.x = (app.screen.width - (width * img.scale_x)) * 0.5
img.y = (app.screen.height - (height * img.scale_y)) * 0.5
-- add the clip that will be used as the play button
local button_clip = self.view:add_clip('play_button')
button_clip.x = (app.screen.width - 160) * 0.5
button_clip.y = app.screen.height * 0.5
self:add_button(button_clip, function (button)
button.enabled = false
self:tween(button_clip, tween.easing.interpolate({ 0, -0.2, -0.25, -0.15, 0.25, 1, 1.25}, 30), { y = 400 }, function ()
app:set_scene('game.game_scene')
end)
end)
end
end) |
object_tangible_quest_naboo_theed_stash_peddler_goods = object_tangible_quest_shared_naboo_theed_stash_peddler_goods:new {
}
ObjectTemplates:addTemplate(object_tangible_quest_naboo_theed_stash_peddler_goods, "object/tangible/quest/naboo_theed_stash_peddler_goods.iff")
|
#!/usr/bin/lua
msg = function() local message = os.getenv('PT_message'); return message end
print(msg())
|
local cache = require('cmp.utils.cache')
local misc = require('cmp.utils.misc')
local buffer = require('cmp.utils.buffer')
local api = require('cmp.utils.api')
---@class cmp.WindowStyle
---@field public relative string
---@field public row number
---@field public col number
---@field public width number
---@field public height number
---@field public zindex number|nil
---@class cmp.Window
---@field public name string
---@field public win number|nil
---@field public swin1 number|nil
---@field public swin2 number|nil
---@field public style cmp.WindowStyle
---@field public opt table<string, any>
---@field public buffer_opt table<string, any>
---@field public cache cmp.Cache
local window = {}
---new
---@return cmp.Window
window.new = function()
local self = setmetatable({}, { __index = window })
self.name = misc.id('cmp.utils.window.new')
self.win = nil
self.swin1 = nil
self.swin2 = nil
self.style = {}
self.cache = cache.new()
self.opt = {}
self.buffer_opt = {}
return self
end
---Set window option.
---NOTE: If the window already visible, immediately applied to it.
---@param key string
---@param value any
window.option = function(self, key, value)
if vim.fn.exists('+' .. key) == 0 then
return
end
if value == nil then
return self.opt[key]
end
self.opt[key] = value
if self:visible() then
vim.api.nvim_win_set_option(self.win, key, value)
end
end
---Set buffer option.
---NOTE: If the buffer already visible, immediately applied to it.
---@param key string
---@param value any
window.buffer_option = function(self, key, value)
if vim.fn.exists('+' .. key) == 0 then
return
end
if value == nil then
return self.buffer_opt[key]
end
self.buffer_opt[key] = value
local existing_buf = buffer.get(self.name)
if existing_buf then
vim.api.nvim_buf_set_option(existing_buf, key, value)
end
end
---Set style.
---@param style cmp.WindowStyle
window.set_style = function(self, style)
if vim.o.columns and vim.o.columns <= style.col + style.width then
style.width = vim.o.columns - style.col - 1
end
if vim.o.lines and vim.o.lines <= style.row + style.height then
style.height = vim.o.lines - style.row - 1
end
self.style = style
self.style.zindex = self.style.zindex or 1
end
---Return buffer id.
---@return number
window.get_buffer = function(self)
local buf, created_new = buffer.ensure(self.name)
if created_new then
for k, v in pairs(self.buffer_opt) do
vim.api.nvim_buf_set_option(buf, k, v)
end
end
return buf
end
---Open window
---@param style cmp.WindowStyle
window.open = function(self, style)
if style then
self:set_style(style)
end
if self.style.width < 1 or self.style.height < 1 then
return
end
if self.win and vim.api.nvim_win_is_valid(self.win) then
vim.api.nvim_win_set_config(self.win, self.style)
else
local s = misc.copy(self.style)
s.noautocmd = true
self.win = vim.api.nvim_open_win(self:get_buffer(), false, s)
for k, v in pairs(self.opt) do
vim.api.nvim_win_set_option(self.win, k, v)
end
end
self:update()
end
---Update
window.update = function(self)
if self:has_scrollbar() then
local total = self:get_content_height()
local info = self:info()
local bar_height = math.ceil(info.height * (info.height / total))
local bar_offset = math.min(info.height - bar_height, math.floor(info.height * (vim.fn.getwininfo(self.win)[1].topline / total)))
local style1 = {}
style1.relative = 'editor'
style1.style = 'minimal'
style1.width = 1
style1.height = info.height
style1.row = info.row
style1.col = info.col + info.width - (info.has_scrollbar and 1 or 0)
style1.zindex = (self.style.zindex and (self.style.zindex + 1) or 1)
if self.swin1 and vim.api.nvim_win_is_valid(self.swin1) then
vim.api.nvim_win_set_config(self.swin1, style1)
else
style1.noautocmd = true
self.swin1 = vim.api.nvim_open_win(buffer.ensure(self.name .. 'sbuf1'), false, style1)
vim.api.nvim_win_set_option(self.swin1, 'winhighlight', 'EndOfBuffer:PmenuSbar,Normal:PmenuSbar,NormalNC:PmenuSbar,NormalFloat:PmenuSbar')
end
local style2 = {}
style2.relative = 'editor'
style2.style = 'minimal'
style2.width = 1
style2.height = bar_height
style2.row = info.row + bar_offset
style2.col = info.col + info.width - (info.has_scrollbar and 1 or 0)
style2.zindex = (self.style.zindex and (self.style.zindex + 2) or 2)
if self.swin2 and vim.api.nvim_win_is_valid(self.swin2) then
vim.api.nvim_win_set_config(self.swin2, style2)
else
style2.noautocmd = true
self.swin2 = vim.api.nvim_open_win(buffer.ensure(self.name .. 'sbuf2'), false, style2)
vim.api.nvim_win_set_option(self.swin2, 'winhighlight', 'EndOfBuffer:PmenuThumb,Normal:PmenuThumb,NormalNC:PmenuThumb,NormalFloat:PmenuThumb')
end
else
if self.swin1 and vim.api.nvim_win_is_valid(self.swin1) then
vim.api.nvim_win_hide(self.swin1)
self.swin1 = nil
end
if self.swin2 and vim.api.nvim_win_is_valid(self.swin2) then
vim.api.nvim_win_hide(self.swin2)
self.swin2 = nil
end
end
-- In cmdline, vim does not redraw automatically.
if api.is_cmdline_mode() then
vim.api.nvim_win_call(self.win, function()
vim.cmd([[redraw]])
end)
end
end
---Close window
window.close = function(self)
if self.win and vim.api.nvim_win_is_valid(self.win) then
if self.win and vim.api.nvim_win_is_valid(self.win) then
vim.api.nvim_win_hide(self.win)
self.win = nil
end
if self.swin1 and vim.api.nvim_win_is_valid(self.swin1) then
vim.api.nvim_win_hide(self.swin1)
self.swin1 = nil
end
if self.swin2 and vim.api.nvim_win_is_valid(self.swin2) then
vim.api.nvim_win_hide(self.swin2)
self.swin2 = nil
end
end
end
---Return the window is visible or not.
window.visible = function(self)
return self.win and vim.api.nvim_win_is_valid(self.win)
end
---Return the scrollbar will shown or not.
window.has_scrollbar = function(self)
return (self.style.height or 0) < self:get_content_height()
end
---Return win info.
window.info = function(self)
local border_width = self:get_border_width()
local has_scrollbar = self:has_scrollbar()
return {
row = self.style.row,
col = self.style.col,
width = self.style.width + border_width + (has_scrollbar and 1 or 0),
height = self.style.height,
border_width = border_width,
has_scrollbar = has_scrollbar,
}
end
---Get border width
---@return number
window.get_border_width = function(self)
local border = self.style.border
if type(border) == 'table' then
local new_border = {}
while #new_border < 8 do
for _, b in ipairs(border) do
table.insert(new_border, b)
end
end
border = new_border
end
local w = 0
if border then
if type(border) == 'string' then
if border == 'single' then
w = 2
elseif border == 'solid' then
w = 2
elseif border == 'double' then
w = 2
elseif border == 'rounded' then
w = 2
elseif border == 'shadow' then
w = 1
end
elseif type(border) == 'table' then
local b4 = type(border[4]) == 'table' and border[4][1] or border[4]
if #b4 > 0 then
w = w + 1
end
local b8 = type(border[8]) == 'table' and border[8][1] or border[8]
if #b8 > 0 then
w = w + 1
end
end
end
return w
end
---Get scroll height.
---@return number
window.get_content_height = function(self)
if not self:option('wrap') then
return vim.api.nvim_buf_line_count(self:get_buffer())
end
return self.cache:ensure({
'get_content_height',
self.style.width,
self:get_buffer(),
vim.api.nvim_buf_get_changedtick(self:get_buffer()),
}, function()
local height = 0
local buf = self:get_buffer()
-- The result of vim.fn.strdisplaywidth depends on the buffer it was called
-- in (see comment in cmp.Entry.get_view).
vim.api.nvim_buf_call(buf, function()
for _, text in ipairs(vim.api.nvim_buf_get_lines(buf, 0, -1, false)) do
height = height + math.ceil(math.max(1, vim.fn.strdisplaywidth(text)) / self.style.width)
end
end)
return height
end)
end
return window
|
setTags = function(jid, tags)
-- store the tags list in job hash
redis.call('hset', 'bee:h:jobs:' .. jid,
'tags', cjson.encode(tags))
-- add this job to tag sets
for i, tag in ipairs(tags) do
redis.call('sadd', 'bee:s:tags:' .. tag, jid)
end
end |
function onEvent(name, value1, value2)
removeLuaSprite(value1);
end
|
-- -- half of screen
-- hs.hotkey.bind({'alt', 'cmd'}, 'left', function() hs.window.focusedWindow():moveToUnit({0, 0, 0.5, 1}) end)
-- hs.hotkey.bind({'alt', 'cmd'}, 'right', function() hs.window.focusedWindow():moveToUnit({0.5, 0, 0.5, 1}) end)
-- hs.hotkey.bind({'alt', 'cmd'}, 'up', function() hs.window.focusedWindow():moveToUnit({0, 0, 1, 0.5}) end)
-- hs.hotkey.bind({'alt', 'cmd'}, 'down', function() hs.window.focusedWindow():moveToUnit({0, 0.5, 1, 0.5}) end)
--
-- -- quarter of screen
-- hs.hotkey.bind({'shift', 'alt', 'cmd'}, 'left', function() hs.window.focusedWindow():moveToUnit({0, 0, 0.5, 0.5}) end)
-- hs.hotkey.bind({'shift', 'alt', 'cmd'}, 'right', function() hs.window.focusedWindow():moveToUnit({0.5, 0.5, 0.5, 0.5}) end)
-- hs.hotkey.bind({'shift', 'alt', 'cmd'}, 'up', function() hs.window.focusedWindow():moveToUnit({0.5, 0, 0.5, 0.5}) end)
-- hs.hotkey.bind({'shift', 'alt', 'cmd'}, 'down', function() hs.window.focusedWindow():moveToUnit({0, 0.5, 0.5, 0.5}) end)
--
-- -- full screen
-- hs.hotkey.bind({'alt', 'cmd'}, 'f', function() hs.window.focusedWindow():moveToUnit({0, 0, 1, 1}) end)
--
-- -- center screen
-- hs.hotkey.bind({'alt', 'cmd'}, 'c', function() hs.window.focusedWindow():centerOnScreen() end)
--
-- -- move between displays
-- hs.hotkey.bind({'ctrl', 'alt', 'cmd'}, 'right', function()
-- local win = hs.window.focusedWindow()
-- local next = win:screen():toEast()
-- if next then
-- win:moveToScreen(next, true)
-- end
-- end)
-- hs.hotkey.bind({'ctrl', 'alt', 'cmd'}, 'left', function()
-- local win = hs.window.focusedWindow()
-- local next = win:screen():toWest()
-- if next then
-- win:moveToScreen(next, true)
-- end
-- end)
-- -- grid gui
-- hs.grid.setMargins({w = 0, h = 0})
-- hs.hotkey.bind({'shift', 'cmd'}, 'g', hs.grid.show)
--
-- -- auto layout
-- hs.hotkey.bind({'ctrl', 'alt', 'cmd'}, 'l', function() autoLayout() end)
|
local skynet = require "skynet"
local harbor = require "skynet.harbor"
require "skynet.manager" -- import skynet.monitor
local function monitor_master()
harbor.linkmaster()
print("master is down")
skynet.exit()
end
skynet.start(function()
print("Log server start")
skynet.monitor "simplemonitor"
local log = skynet.newservice("globallog")
skynet.fork(monitor_master)
end)
|
--[[
Variables
]]
local vehiclesCoords = {}
--[[
Events
]]
RegisterNetEvent("caue-phone:vehicleCoords")
AddEventHandler("caue-phone:vehicleCoords", function(identifier, coords)
local src = source
vehiclesCoords[identifier] = coords
end)
--[[
RPCs
]]
RPC.register("caue-phone:getVehicles", function(src)
local cid = exports["caue-base"]:getChar(src, "id")
if not cid then return {} end
local vehicles = MySQL.query.await([[
SELECT v1.id, v1.plate, v1.model, v2.fuel, v2.body_damage, v2.engine_damage, v3.state, v3.garage, v3.coords, v4.price AS payment_price, v4.left AS payment_left, DATEDIFF(FROM_UNIXTIME(UNIX_TIMESTAMP()), FROM_UNIXTIME(v4.last)) AS payment_last
FROM vehicles v1
INNER JOIN vehicles_metadata v2 ON v2.vid = v1.id
INNER JOIN vehicles_garage v3 ON v3.vid = v1.id
INNER JOIN vehicles_payments v4 ON v4.vid = v1.id
WHERE cid = ?
]],
{ cid })
return vehicles
end)
RPC.register("caue-phone:vehicleCoords", function(src, identifier)
if vehiclesCoords[identifier] ~= nil then
return vehiclesCoords[identifier]
end
local garage = exports["caue-vehicles"]:selectVehicle(identifier, "garage", "garage")
local garagePos = exports["caue-vehicles"]:getGarage(garage, "pos")
if garage and garagePos then
return garagePos
end
return false
end)
RPC.register("caue-phone:payVehicle", function(src, identifier)
return exports["caue-vehicles"]:payVehicle(identifier, src)
end)
RPC.register("caue-phone:carshopOutstandings", function(src, group)
local vehicles = MySQL.query.await([[
SELECT v1.vid, v2.plate, v2.model, CONCAT(c1.first_name, c1.last_name) as name, c1.phone, v3.price AS payment_price, v3.left AS payment_left, DATEDIFF(FROM_UNIXTIME(UNIX_TIMESTAMP()), FROM_UNIXTIME(v3.last)) AS payment_last
FROM carshop_logs v1
INNER JOIN vehicles v2 ON v2.id = v1.vid
INNER JOIN characters c1 ON c1.id = v2.cid
INNER JOIN vehicles_payments v3 ON v3.vid = v1.vid
WHERE shop = ?
]],
{ group })
return vehicles
end) |
vim.g.cpp_function_highlight = 1
vim.g.cpp_member_highlight = 1
vim.g.cpp_simple_highlight = 1
|
local mod = mod_loader.mods[modApi.currentMod]
local path = mod.resourcePath
local modUtils = require(path .."scripts/modApiExt/modApiExt")
local selected = require(path .."scripts/libs/selected")
local getQueued = require(path .."scripts/libs/getQueued")
local trait = require(path .."scripts/libs/trait")
local tips = require(path .."scripts/libs/tutorialTips")
local a = ANIMS
local writepath = "img/units/aliens/"
local readpath = path .. writepath
local imagepath = writepath:sub(5,-1)
local this = {}
modApi:appendAsset(writepath .."lmn_blobberling.png", readpath .."blobberling.png")
modApi:appendAsset(writepath .."lmn_blobberlinga.png", readpath .."blobberlinga.png")
modApi:appendAsset(writepath .."lmn_blobberling_death.png", readpath .."blobberling_death.png")
modApi:appendAsset(writepath .."lmn_blobberling_emerge.png", readpath .."blobberling_emerge.png")
modApi:appendAsset(writepath .."lmn_blobberling_Bw.png", readpath .."blobberling_Bw.png")
modApi:appendAsset("img/portraits/enemy/lmn_Blobberling1.png", path .."img/portraits/enemy/Blobberling1.png")
modApi:appendAsset("img/portraits/enemy/lmn_Blobberling2.png", path .."img/portraits/enemy/Blobberling2.png")
modApi:copyAsset("img/combat/icons/icon_kill_glow.png", "img/combat/icons/lmn_blobberling_death.png")
Location["combat/icons/lmn_blobberling_death.png"] = Point(-16,9)
local base = a.EnemyUnit:new{Image = imagepath .."lmn_blobberling.png", PosX = -14, PosY = 7}
local baseEmerge = a.BaseEmerge:new{Image = imagepath .."lmn_blobberling_emerge.png", PosX = -24, PosY = -2}
a.lmn_blobberling = base
a.lmn_blobberlinge = baseEmerge
a.lmn_blobberlinga = base:new{ Image = imagepath .."lmn_blobberlinga.png", NumFrames = 4 }
a.lmn_blobberlingd = base:new{ Image = imagepath .."lmn_blobberling_death.png", PosX = -15, Loop = false, NumFrames = 8, Time = .04 }
a.lmn_blobberlingw = base:new{ Image = imagepath .."lmn_blobberling_Bw.png", PosX = -15, PosY = 14 }
local function isBlobberling(pawn)
return
list_contains(_G[pawn:GetType()].SkillList, "lmn_BlobberlingAtk1") or
list_contains(_G[pawn:GetType()].SkillList, "lmn_BlobberlingAtk2")
end
local pawnTypes = {"lmn_Blobberling1", "lmn_Blobberling2", "lmn_BlobberlingBoss"}
trait:Add{
PawnTypes = "lmn_Blobberling1",
Icon = {"img/combat/icons/icon_explode.png", Point(0,8)},
Description = {"Extremely Volatile", "This unit will always explode on death, dealing 1 damage to adjacent tiles."}
}
trait:Add{
PawnTypes = "lmn_Blobberling2",
Icon = {"img/combat/icons/icon_explode.png", Point(0,8)},
Description = {"Extremely Volatile", "This unit will always explode on death, dealing 2 damage to adjacent tiles."}
}
local function ExplosiveEffect(self, p)
local ret = SkillEffect()
local damage = SpaceDamage(p)
damage.sSound = self.sSound
damage.sAnimation = "explo_fire1"
ret:AddDamage(damage)
for dir = DIR_START, DIR_END do
local curr = p + DIR_VECTORS[dir]
if Board:IsValid(curr) then
local damage = SpaceDamage(curr, self.Damage)
damage.sSound = self.sSound
damage.sAnimation = self.sAnimationPush .."_".. dir
ret:AddDamage(damage)
end
end
return ret
end
lmn_Blobberling1 = Pawn:new{
Name = "Blobberling",
Health = 2,
MoveSpeed = 5,
Damage = 1,
sSound = "/impact/generic/explosion",
sAnimationPush = "exploout1",
Image = "lmn_blobberling",
ImageOffset = 0,
SkillList = { "lmn_BlobberlingAtk1" },
SoundLocation = "/enemy/scarab_1/",
DefaultTeam = TEAM_ENEMY,
ImpactMaterial = IMPACT_BLOB,
Portrait = "enemy/lmn_Blobberling1",
AvoidingMines = true,
Minor = true, -- double explosive? no thanks.
ExplosiveEffect = ExplosiveEffect
}
function lmn_Blobberling1:GetDeathEffect(p)
local ret = self:ExplosiveEffect(p)
ret:AddDelay(0.1)
ret:AddScript(string.format([[
local p, pawnTypes = %s, %s;
local pawn = Board:GetPawn(p);
if pawn and list_contains(pawnTypes, pawn:GetType()) then
Board:RemovePawn(pawn);
end;
]], p:GetString(), save_table(pawnTypes)))
return ret
end
lmn_Blobberling2 = lmn_Blobberling1:new{
Name = "Alpha Blobberling",
Health = 3,
MoveSpeed = 5,
Damage = 2,
sSound = "/impact/generic/explosion",
sAnimationPush = "exploout2",
Image = "lmn_blobberling",
ImageOffset = 1,
SkillList = { "lmn_BlobberlingAtk2" },
SoundLocation = "/enemy/scarab_2/",
DefaultTeam = TEAM_ENEMY,
ImpactMaterial = IMPACT_BLOB,
Tier = TIER_ALPHA,
Portrait = "enemy/lmn_Blobberling2",
}
lmn_Blobberling1_Tip = lmn_Blobberling1:new{ GetDeathEffect = function() return SkillEffect() end }
lmn_Blobberling2_Tip = lmn_Blobberling2:new{ GetDeathEffect = function() return SkillEffect() end }
lmn_BlobberlingAtk1 = SelfTarget:new{
Name = "Unstable Guts",
Description = "Kills itself. Explodes upon death, and deal damage to adjacent tiles.",
Icon = "weapons/enemy_blob1.png",
Damage = 1,
Range = 1,
ScoreFriendlyDamage = -2, -- self damage is also friendly damage. -2
ScoreEnemy = 3, -- low mech score so we only explode on ~2+ mechs.
Class = "Enemy",
LaunchSound = "",
sSound = lmn_Blobberling1.sSound,
sAnimationPush = lmn_Blobberling1.sAnimationPush,
CustomTipImage = "lmn_BlobberlingAtk1_Tip",
ExplosiveEffect = ExplosiveEffect,
TipImage = {
CustomPawn = "lmn_Blobberling1_Tip",
Unit = Point(2,2),
Enemy = Point(1,2),
Building = Point(2,1),
Target = Point(2,2),
}
}
lmn_BlobberlingAtk1.GetTargetScore = Skill.GetTargetScore
function lmn_BlobberlingAtk1:GetSkillEffect(p1, p2)
local ret = self:ExplosiveEffect(p1)
ret.effect:index(1).iDamage = DAMAGE_DEATH
ret.effect:index(1).bHide = true
ret.q_effect = ret.effect
ret.effect = SkillEffect().effect
-- dummy damage to mark the space.
ret:AddQueuedDamage(SpaceDamage(p1))
ret:AddScript(string.format([[
local tips = require(%q .."scripts/libs/tutorialTips");
tips:Trigger("Blobberling_Atk", %s);
]], path, p1:GetString()))
local pawn = Board:GetPawn(p1)
if not pawn then
return ret
end
local pawnId = pawn:GetId()
ret:AddQueuedDelay(0.1)
ret:AddQueuedScript(string.format([[
local pawn = Board:GetPawn(%s);
if pawn then
Board:RemovePawn(pawn);
end
]], pawnId))
return ret
end
lmn_BlobberlingAtk2 = lmn_BlobberlingAtk1:new{
Name = "Volatile Guts",
Damage = 2,
sAnimationPush = lmn_Blobberling2.sAnimationPush,
CustomTipImage = "lmn_BlobberlingAtk2_Tip",
TipImage = {
CustomPawn = "lmn_Blobberling2_Tip",
Unit = Point(2,2),
Enemy = Point(1,2),
Building = Point(2,1),
Target = Point(2,2),
}
}
lmn_BlobberlingAtk1_Tip = lmn_BlobberlingAtk1:new{}
function lmn_BlobberlingAtk1_Tip:GetSkillEffect(p1, p2)
local ret = SkillEffect()
local damage = SpaceDamage(p1, DAMAGE_DEATH)
damage.sSound = self.sSound
damage.sAnimation = "explo_fire1"
ret:AddQueuedDamage(damage)
for dir = DIR_START, DIR_END do
local curr = p1 + DIR_VECTORS[dir]
if Board:IsValid(curr) then
local damage = SpaceDamage(curr, self.Damage)
damage.sSound = self.sSound
damage.sAnimation = self.sAnimationPush .."_".. dir
ret:AddQueuedDamage(damage)
end
end
return ret
end
lmn_BlobberlingAtk2_Tip = lmn_BlobberlingAtk1_Tip:new{
Name = "Volatile Guts",
Damage = 2,
sAnimationPush = "exploout2",
TipImage = lmn_BlobberlingAtk2.TipImage
}
function this:load()
-- this whole thing should probably be exported to some library
-- to enable streamlined additional preview to queued attacks.
modApi:addMissionUpdateHook(function(m)
if m == Mission_test then return end
local pawns = extract_table(Board:GetPawns(TEAM_ANY))
for _, pawnId in ipairs(pawns) do
local pawn = Board:GetPawn(pawnId)
local loc = pawn:GetSpace()
local queuedAttack = getQueued(pawnId) --pawn:GetQueued()
local selected = selected:Get()
local armedWeapon = selected and selected:GetArmedWeaponId() or 0
local isWeaponArmed = armedWeapon > 0
local hasFocus = Board:IsHighlighted(loc) or pawn:IsSelected()
if
isBlobberling(pawn) and
queuedAttack and
not pawn:IsBusy() and
not isWeaponArmed and
Game:GetTeamTurn() == 1 and
loc == queuedAttack.piOrigin
then
local alpha = .25
if not hasFocus then
local d = SpaceDamage(queuedAttack.piOrigin)
d.sImageMark = "combat/icons/lmn_blobberling_death.png"
Board:MarkSpaceDamage(d)
alpha = .75
end
Board:MarkSpaceSimpleColor(queuedAttack.piOrigin, GL_Color(255, 66, 66, alpha))
end
end
end)
modUtils:addPawnTrackedHook(function(m, pawn)
if isBlobberling(pawn) then
tips:Trigger("Blobberling", pawn:GetSpace())
end
end)
end
return this |
--[[
Incorrect login workflow when the mailbox is not provided.
]]
-- User's mailbox number input.
mailbox = storage("get_digits", "digits")
return
{
-- Ask for the mailbox again.
{
action = "get_digits",
min_digits = profile.mailbox_min_digits,
max_digits = profile.mailbox_max_digits,
audio_files = "phrase:login_incorrect_mailbox",
bad_input = "",
timeout = profile.user_input_timeout,
},
{
action = "set_storage",
storage_area = "login_settings",
data = {
mailbox_number = mailbox,
},
},
{
action = "call_sequence",
sequence = "validate_mailbox_login",
},
}
|
local tinsert = table.insert
local tsort = table.sort
local gsub = string.gsub
local match = string.match
local M = {}
function M.sort_pairs(t, f)
local a = {}
for n in pairs(t) do
tinsert(a, n)
end
tsort(a, f)
local i = 0
return function ()
i = i + 1
if a[i] == nil then
return nil
else
return a[i], t[a[i]]
end
end
end
function M.swap_key_value(t)
local ret = {}
for k,v in pairs(t) do
ret[v] = k
end
return ret
end
---------------------------------
-- table.tostring(tbl)
---------------------------------
-- fork from http://lua-users.org/wiki/TableUtils
local function append_result(result, ...)
local n = select('#', ...)
for i=1,n do
result.i = result.i + 1
result[result.i] = select(i, ...)
end
end
local function val_to_str(v, result, depth)
local tp = type(v)
if "string" == tp then
v = gsub(v, "\n", "\\n")
if match(gsub(v, "[^'\"]", ""), '^"+$') then
append_result(result, "'")
append_result(result, v)
append_result(result, "'")
else
append_result(result, '"')
v = gsub(v, '"', '\\"')
append_result(result, v)
append_result(result, '"')
end
elseif "table" == tp then
M.tostring_tbl(v, result, depth)
elseif "function" == tp then
append_result(result, '"', tostring(v), '"')
else
append_result(result, tostring(v))
end
end
local function key_to_str(k, result, depth)
if "string" == type(k) and match(k, "^[_%a][_%a%d]*$") then
append_result(result, k)
else
append_result(result, "[")
val_to_str(k, result, depth)
append_result(result, "]")
end
end
local MAX_STR_TBL_CNT = 1024*1024 -- result has 1M element
M.tostring_tbl = function (tbl, result, depth)
if not result.i then
result.i = 0
end
depth = (depth or 0) + 1
if depth > 50 then
return
end
append_result(result, "{")
for k,v in pairs(tbl) do
if result.i > MAX_STR_TBL_CNT then
break
end
key_to_str(k, result, depth)
append_result(result, "=")
val_to_str(v, result, depth)
append_result(result, ",")
end
append_result(result, "}")
end
M.concat_tostring_tbl = function (result)
result.i = nil
return table.concat(result, "")
end
M.tostring = function(tbl)
local result = {}
result.i = 0
val_to_str(tbl, result)
return M.concat_tostring_tbl(result)
end
return M
|
local ffi = require("ffi")
local setmetatable = setmetatable
local error = error
local type = type
local print = print
local setmetatable = setmetatable
local rawget = rawget
local memory = memory
local TArrayMT = {}
function TArrayMT.__index(self, idx)
if type(idx) == "number" then
if idx < self.Count and idx >= 0 then
if self.Data[idx] ~= nil then
return self.Data[idx]
end
else
print("[TArray] Warning: Index out of range")
end
return nil
end
return rawget(self, idx)
--error("TArray must be indexed by number")
end
-- Using pairs is probably slower than a normal for loop, but it's a tad more convenient
local function TArrayIter(obj, k)
if k < (obj.Count - 1) then -- If current index is before the last index
k = k + 1
local v = obj.Data[k]
if v ~= nil then
return k, v
else
return TArrayIter(obj, k)
end
end
end
function TArrayMT.__pairs(self)
return TArrayIter, self, -1 -- neg 1 because TArrayIter will increment this to 0
end
function TArrayMT.__ipairs(self)
return TArrayIter, self, -1 -- neg 1 because TArrayIter will increment this to 0
end
function TArrayMT.__len(self)
return self.Count
end
function TArrayMT.__gc(self)
print(string.format("TArray GC: %d, 0x%X", self.Count, PtrToNum(self.Data)))
memory.Free(self.Data)
end
ffi.metatype("struct TArray", TArrayMT)
local TArray = {}
function TArray.Create(innerType, cdata)
local type = ffi.typeof([[
struct {
$* Data;
int Count;
int Max;
}]], ffi.typeof(innerType))
local type_mt = ffi.metatype(type, TArrayMT)
local type_ptr = ffi.typeof("$ *", type_mt)
local data = ffi.cast(type_ptr, cdata)
--[[
local mt = {
__index = data,
__newindex = function(self, k, v)
error("Cannot set property '" .. k .. "' on TArray")
end,
--__pairs = TArrayMT.__pairs,
}
]]
--local mt = TArrayMT
--return setmetatable({}, mt)
local mt = {}
function mt.__index(self, idx)
return data[0][idx]
end
return setmetatable({}, mt)
end
TArray.BaseMT = TArrayMT
return TArray
|
-- Copyright 2021 SmartThings
--
-- 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 capabilities = require "st.capabilities"
--- @type st.zwave.CommandClass
local cc = require "st.zwave.CommandClass"
local FIBARO_WALL_PLUG_FINGERPRINTS = {
{mfr = 0x010F, prod = 0x1401, model = 0x1001}, -- Fibaro Outlet
{mfr = 0x010F, prod = 0x1401, model = 0x2000}, -- Fibaro Outlet
}
local function can_handle_fibaro_wall_plug(opts, driver, device, ...)
for _, fingerprint in ipairs(FIBARO_WALL_PLUG_FINGERPRINTS) do
if device:id_match(fingerprint.mfr, fingerprint.prod, fingerprint.model) then
return true
end
end
return false
end
local function component_to_endpoint(device, component_id)
if component_id == "main" then
return {1}
else
return {2}
end
end
local function endpoint_to_component(device, ep)
local switch_comp = string.format("smartplug%d", ep - 1)
if device.profile.components[switch_comp] ~= nil then
return switch_comp
else
return "main"
end
end
local function device_init(self, device)
device:set_component_to_endpoint_fn(component_to_endpoint)
device:set_endpoint_to_component_fn(endpoint_to_component)
end
local fibaro_wall_plug = {
NAME = "fibaro wall plug us",
lifecycle_handlers = {
init = device_init
},
can_handle = can_handle_fibaro_wall_plug,
}
return fibaro_wall_plug
|
--[[
---------------------------------------------------
LUXART VEHICLE CONTROL (FOR FIVEM)
---------------------------------------------------
Last revision: MAY 01 2017 (VERS. 1.01)
Coded by Lt.Caine
---------------------------------------------------
NOTES
LVC will automatically apply to all emergency vehicles (vehicle class 18)
---------------------------------------------------
CONTROLS
Right indicator: = (Next Custom Radio Track)
Left indicator: - (Previous Custom Radio Track)
Hazard lights: Backspace (Phone Cancel)
Toggle emergency lights: Y (Text Chat Team)
Airhorn: E (Horn)
Toggle siren: , (Previous Radio Station)
Manual siren / Change siren tone: N (Next Radio Station)
Auxiliary siren: Down Arrow (Phone Up)
---------------------------------------------------
]]
local count_bcast_timer = 0
local delay_bcast_timer = 200
local count_sndclean_timer = 0
local delay_sndclean_timer = 400
local actv_ind_timer = false
local count_ind_timer = 0
local delay_ind_timer = 180
local actv_lxsrnmute_temp = false
local srntone_temp = 0
local dsrn_mute = true
local state_indic = {}
local state_lxsiren = {}
local state_pwrcall = {}
local state_airmanu = {}
local ind_state_o = 0
local ind_state_l = 1
local ind_state_r = 2
local ind_state_h = 3
local snd_lxsiren = {}
local snd_pwrcall = {}
local snd_airmanu = {}
-- these models will use their real wail siren, as determined by their assigned audio hash in vehicles.meta
local eModelsWithFireSrn =
{
"FIRETRUK",
}
-- models listed below will use AMBULANCE_WARNING as auxiliary siren
-- unlisted models will instead use the default wail as the auxiliary siren
local eModelsWithPcall =
{
"AMBULANCE",
"FIRETRUK",
"LGUARD",
}
---------------------------------------------------------------------
function ShowDebug(text)
SetNotificationTextEntry("STRING")
AddTextComponentString(text)
DrawNotification(false, false)
end
---------------------------------------------------------------------
function useFiretruckSiren(veh)
local model = GetEntityModel(veh)
for i = 1, #eModelsWithFireSrn, 1 do
if model == GetHashKey(eModelsWithFireSrn[i]) then
return true
end
end
return false
end
---------------------------------------------------------------------
function usePowercallAuxSrn(veh)
local model = GetEntityModel(veh)
for i = 1, #eModelsWithPcall, 1 do
if model == GetHashKey(eModelsWithPcall[i]) then
return true
end
end
return false
end
---------------------------------------------------------------------
function CleanupSounds()
if count_sndclean_timer > delay_sndclean_timer then
count_sndclean_timer = 0
for k, v in pairs(state_lxsiren) do
if v > 0 then
if not DoesEntityExist(k) or IsEntityDead(k) then
if snd_lxsiren[k] ~= nil then
StopSound(snd_lxsiren[k])
ReleaseSoundId(snd_lxsiren[k])
snd_lxsiren[k] = nil
state_lxsiren[k] = nil
end
end
end
end
for k, v in pairs(state_pwrcall) do
if v == true then
if not DoesEntityExist(k) or IsEntityDead(k) then
if snd_pwrcall[k] ~= nil then
StopSound(snd_pwrcall[k])
ReleaseSoundId(snd_pwrcall[k])
snd_pwrcall[k] = nil
state_pwrcall[k] = nil
end
end
end
end
for k, v in pairs(state_airmanu) do
if v == true then
if not DoesEntityExist(k) or IsEntityDead(k) or IsVehicleSeatFree(k, -1) then
if snd_airmanu[k] ~= nil then
StopSound(snd_airmanu[k])
ReleaseSoundId(snd_airmanu[k])
snd_airmanu[k] = nil
state_airmanu[k] = nil
end
end
end
end
else
count_sndclean_timer = count_sndclean_timer + 1
end
end
---------------------------------------------------------------------
function TogIndicStateForVeh(veh, newstate)
if DoesEntityExist(veh) and not IsEntityDead(veh) then
if newstate == ind_state_o then
SetVehicleIndicatorLights(veh, 0, false) -- R
SetVehicleIndicatorLights(veh, 1, false) -- L
elseif newstate == ind_state_l then
SetVehicleIndicatorLights(veh, 0, false) -- R
SetVehicleIndicatorLights(veh, 1, true) -- L
elseif newstate == ind_state_r then
SetVehicleIndicatorLights(veh, 0, true) -- R
SetVehicleIndicatorLights(veh, 1, false) -- L
elseif newstate == ind_state_h then
SetVehicleIndicatorLights(veh, 0, true) -- R
SetVehicleIndicatorLights(veh, 1, true) -- L
end
state_indic[veh] = newstate
end
end
---------------------------------------------------------------------
function TogMuteDfltSrnForVeh(veh, toggle)
if DoesEntityExist(veh) and not IsEntityDead(veh) then
DisableVehicleImpactExplosionActivation(veh, toggle)
end
end
---------------------------------------------------------------------
function SetLxSirenStateForVeh(veh, newstate)
if DoesEntityExist(veh) and not IsEntityDead(veh) then
if newstate ~= state_lxsiren[veh] then
if snd_lxsiren[veh] ~= nil then
StopSound(snd_lxsiren[veh])
ReleaseSoundId(snd_lxsiren[veh])
snd_lxsiren[veh] = nil
end
if newstate == 1 then
if useFiretruckSiren(veh) then
TogMuteDfltSrnForVeh(veh, false)
else
snd_lxsiren[veh] = GetSoundId()
PlaySoundFromEntity(snd_lxsiren[veh], "VEHICLES_HORNS_SIREN_1", veh, 0, 0, 0)
TogMuteDfltSrnForVeh(veh, true)
end
elseif newstate == 2 then
snd_lxsiren[veh] = GetSoundId()
PlaySoundFromEntity(snd_lxsiren[veh], "VEHICLES_HORNS_SIREN_2", veh, 0, 0, 0)
TogMuteDfltSrnForVeh(veh, true)
elseif newstate == 3 then
snd_lxsiren[veh] = GetSoundId()
if useFiretruckSiren(veh) then
PlaySoundFromEntity(snd_lxsiren[veh], "VEHICLES_HORNS_AMBULANCE_WARNING", veh, 0, 0, 0)
else
PlaySoundFromEntity(snd_lxsiren[veh], "VEHICLES_HORNS_POLICE_WARNING", veh, 0, 0, 0)
end
TogMuteDfltSrnForVeh(veh, true)
else
TogMuteDfltSrnForVeh(veh, true)
end
state_lxsiren[veh] = newstate
end
end
end
---------------------------------------------------------------------
function TogPowercallStateForVeh(veh, toggle)
if DoesEntityExist(veh) and not IsEntityDead(veh) then
if toggle == true then
if snd_pwrcall[veh] == nil then
snd_pwrcall[veh] = GetSoundId()
if usePowercallAuxSrn(veh) then
PlaySoundFromEntity(snd_pwrcall[veh], "VEHICLES_HORNS_AMBULANCE_WARNING", veh, 0, 0, 0)
else
PlaySoundFromEntity(snd_pwrcall[veh], "VEHICLES_HORNS_SIREN_1", veh, 0, 0, 0)
end
end
else
if snd_pwrcall[veh] ~= nil then
StopSound(snd_pwrcall[veh])
ReleaseSoundId(snd_pwrcall[veh])
snd_pwrcall[veh] = nil
end
end
state_pwrcall[veh] = toggle
end
end
---------------------------------------------------------------------
function SetAirManuStateForVeh(veh, newstate)
if DoesEntityExist(veh) and not IsEntityDead(veh) then
if newstate ~= state_airmanu[veh] then
if snd_airmanu[veh] ~= nil then
StopSound(snd_airmanu[veh])
ReleaseSoundId(snd_airmanu[veh])
snd_airmanu[veh] = nil
end
if newstate == 1 then
snd_airmanu[veh] = GetSoundId()
if useFiretruckSiren(veh) then
PlaySoundFromEntity(snd_airmanu[veh], "VEHICLES_HORNS_FIRETRUCK_WARNING", veh, 0, 0, 0)
else
PlaySoundFromEntity(snd_airmanu[veh], "SIRENS_AIRHORN", veh, 0, 0, 0)
end
elseif newstate == 2 then
snd_airmanu[veh] = GetSoundId()
PlaySoundFromEntity(snd_airmanu[veh], "VEHICLES_HORNS_SIREN_1", veh, 0, 0, 0)
elseif newstate == 3 then
snd_airmanu[veh] = GetSoundId()
PlaySoundFromEntity(snd_airmanu[veh], "VEHICLES_HORNS_SIREN_2", veh, 0, 0, 0)
end
state_airmanu[veh] = newstate
end
end
end
---------------------------------------------------------------------
RegisterNetEvent("lvc_TogIndicState_c")
AddEventHandler("lvc_TogIndicState_c", function(sender, newstate)
local player_s = GetPlayerFromServerId(sender)
local ped_s = GetPlayerPed(player_s)
if DoesEntityExist(ped_s) and not IsEntityDead(ped_s) then
if ped_s ~= GetPlayerPed(-1) then
if IsPedInAnyVehicle(ped_s, false) then
local veh = GetVehiclePedIsUsing(ped_s)
TogIndicStateForVeh(veh, newstate)
end
end
end
end)
---------------------------------------------------------------------
RegisterNetEvent("lvc_TogDfltSrnMuted_c")
AddEventHandler("lvc_TogDfltSrnMuted_c", function(sender, toggle)
local player_s = GetPlayerFromServerId(sender)
local ped_s = GetPlayerPed(player_s)
if DoesEntityExist(ped_s) and not IsEntityDead(ped_s) then
if ped_s ~= GetPlayerPed(-1) then
if IsPedInAnyVehicle(ped_s, false) then
local veh = GetVehiclePedIsUsing(ped_s)
TogMuteDfltSrnForVeh(veh, toggle)
end
end
end
end)
---------------------------------------------------------------------
RegisterNetEvent("lvc_SetLxSirenState_c")
AddEventHandler("lvc_SetLxSirenState_c", function(sender, newstate)
local player_s = GetPlayerFromServerId(sender)
local ped_s = GetPlayerPed(player_s)
if DoesEntityExist(ped_s) and not IsEntityDead(ped_s) then
if ped_s ~= GetPlayerPed(-1) then
if IsPedInAnyVehicle(ped_s, false) then
local veh = GetVehiclePedIsUsing(ped_s)
SetLxSirenStateForVeh(veh, newstate)
end
end
end
end)
---------------------------------------------------------------------
RegisterNetEvent("lvc_TogPwrcallState_c")
AddEventHandler("lvc_TogPwrcallState_c", function(sender, toggle)
local player_s = GetPlayerFromServerId(sender)
local ped_s = GetPlayerPed(player_s)
if DoesEntityExist(ped_s) and not IsEntityDead(ped_s) then
if ped_s ~= GetPlayerPed(-1) then
if IsPedInAnyVehicle(ped_s, false) then
local veh = GetVehiclePedIsUsing(ped_s)
TogPowercallStateForVeh(veh, toggle)
end
end
end
end)
---------------------------------------------------------------------
RegisterNetEvent("lvc_SetAirManuState_c")
AddEventHandler("lvc_SetAirManuState_c", function(sender, newstate)
local player_s = GetPlayerFromServerId(sender)
local ped_s = GetPlayerPed(player_s)
if DoesEntityExist(ped_s) and not IsEntityDead(ped_s) then
if ped_s ~= GetPlayerPed(-1) then
if IsPedInAnyVehicle(ped_s, false) then
local veh = GetVehiclePedIsUsing(ped_s)
SetAirManuStateForVeh(veh, newstate)
end
end
end
end)
---------------------------------------------------------------------
Citizen.CreateThread(function()
while true do
CleanupSounds()
----- IS IN VEHICLE -----
local playerped = GetPlayerPed(-1)
if IsPedInAnyVehicle(playerped, false) then
----- IS DRIVER -----
local veh = GetVehiclePedIsUsing(playerped)
if GetPedInVehicleSeat(veh, -1) == playerped then
DisableControlAction(0, 81, true)
DisableControlAction(0, 84, true) -- INPUT_VEH_PREV_RADIO_TRACK
DisableControlAction(0, 83, true) -- INPUT_VEH_NEXT_RADIO_TRACK
if state_indic[veh] ~= ind_state_o and state_indic[veh] ~= ind_state_l and state_indic[veh] ~= ind_state_r and state_indic[veh] ~= ind_state_h then
state_indic[veh] = ind_state_o
end
-- INDIC AUTO CONTROL
if actv_ind_timer == true then
if state_indic[veh] == ind_state_l or state_indic[veh] == ind_state_r then
if GetEntitySpeed(veh) < 6 then
count_ind_timer = 0
else
if count_ind_timer > delay_ind_timer then
count_ind_timer = 0
actv_ind_timer = false
state_indic[veh] = ind_state_o
PlaySoundFrontend(-1, "NAV_UP_DOWN", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
TogIndicStateForVeh(veh, state_indic[veh])
count_bcast_timer = delay_bcast_timer
else
count_ind_timer = count_ind_timer + 1
end
end
end
end
--- IS EMERG VEHICLE ---
if GetVehicleClass(veh) == 18 then
local actv_manu = false
local actv_horn = false
DisableControlAction(0, 86, true) -- INPUT_VEH_HORN
DisableControlAction(0, 172, true) -- INPUT_CELLPHONE_UP
--DisableControlAction(0, 173, true) -- INPUT_CELLPHONE_DOWN
--DisableControlAction(0, 174, true) -- INPUT_CELLPHONE_LEFT
--DisableControlAction(0, 175, true) -- INPUT_CELLPHONE_RIGHT
DisableControlAction(0, 81, true) -- INPUT_VEH_NEXT_RADIO
DisableControlAction(0, 82, true) -- INPUT_VEH_PREV_RADIO
-- DisableControlAction(0, 19, true) -- INPUT_CHARACTER_WHEEL
DisableControlAction(0, 85, true) -- INPUT_VEH_RADIO_WHEEL
SetVehRadioStation(veh, "OFF")
SetVehicleRadioEnabled(veh, false)
if state_lxsiren[veh] ~= 1 and state_lxsiren[veh] ~= 2 and state_lxsiren[veh] ~= 3 then
state_lxsiren[veh] = 0
end
if state_pwrcall[veh] ~= true then
state_pwrcall[veh] = false
end
if state_airmanu[veh] ~= 1 and state_airmanu[veh] ~= 2 and state_airmanu[veh] ~= 3 then
state_airmanu[veh] = 0
end
if useFiretruckSiren(veh) and state_lxsiren[veh] == 1 then
TogMuteDfltSrnForVeh(veh, false)
dsrn_mute = false
else
TogMuteDfltSrnForVeh(veh, true)
dsrn_mute = true
end
if not IsVehicleSirenOn(veh) and state_lxsiren[veh] > 0 then
PlaySoundFrontend(-1, "NAV_UP_DOWN", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
SetLxSirenStateForVeh(veh, 0)
count_bcast_timer = delay_bcast_timer
end
if not IsVehicleSirenOn(veh) and state_pwrcall[veh] == true then
PlaySoundFrontend(-1, "NAV_UP_DOWN", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
TogPowercallStateForVeh(veh, false)
count_bcast_timer = delay_bcast_timer
end
----- CONTROLS -----
if not IsPauseMenuActive() then
-- TOG DFLT SRN LIGHTS
if IsDisabledControlJustReleased(0, 85) then
if IsVehicleSirenOn(veh) then
PlaySoundFrontend(-1, "NAV_UP_DOWN", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
SetVehicleSiren(veh, false)
else
PlaySoundFrontend(-1, "NAV_LEFT_RIGHT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
SetVehicleSiren(veh, true)
count_bcast_timer = delay_bcast_timer
end
-- TOG LX SIREN
elseif IsDisabledControlJustReleased(0, 172) then
local cstate = state_lxsiren[veh]
if cstate == 0 then
if IsVehicleSirenOn(veh) then
PlaySoundFrontend(-1, "NAV_LEFT_RIGHT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1) -- on
SetLxSirenStateForVeh(veh, 1)
count_bcast_timer = delay_bcast_timer
end
else
PlaySoundFrontend(-1, "NAV_UP_DOWN", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1) -- off
SetLxSirenStateForVeh(veh, 0)
count_bcast_timer = delay_bcast_timer
end
-- POWERCALL
-- elseif IsDisabledControlJustReleased(0, 173) then
-- if state_pwrcall[veh] == true then
-- PlaySoundFrontend(-1, "NAV_UP_DOWN", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
-- TogPowercallStateForVeh(veh, false)
-- count_bcast_timer = delay_bcast_timer
-- else
-- if IsVehicleSirenOn(veh) then
-- PlaySoundFrontend(-1, "NAV_LEFT_RIGHT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
-- TogPowercallStateForVeh(veh, true)
-- count_bcast_timer = delay_bcast_timer
-- end
-- end
end
-- BROWSE LX SRN TONES
if state_lxsiren[veh] > 0 then
if IsDisabledControlJustReleased(0, 47) then
if IsVehicleSirenOn(veh) then
local cstate = state_lxsiren[veh]
local nstate = 1
PlaySoundFrontend(-1, "NAV_LEFT_RIGHT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1) -- on
if cstate == 1 then
nstate = 2
elseif cstate == 2 then
nstate = 3
else
nstate = 1
end
SetLxSirenStateForVeh(veh, nstate)
count_bcast_timer = delay_bcast_timer
end
end
end
-- MANU
-- if state_lxsiren[veh] < 1 then
-- if IsDisabledControlPressed(0, 80) then
-- actv_manu = true
-- else
-- actv_manu = false
-- end
-- else
-- actv_manu = false
-- end
-- HORN
if IsDisabledControlPressed(0, 86) then
actv_horn = true
else
actv_horn = false
end
end
---- ADJUST HORN / MANU STATE ----
local hmanu_state_new = 0
if actv_horn == true and actv_manu == false then
hmanu_state_new = 1
elseif actv_horn == false and actv_manu == true then
hmanu_state_new = 2
elseif actv_horn == true and actv_manu == true then
hmanu_state_new = 3
end
if hmanu_state_new == 1 then
if not useFiretruckSiren(veh) then
if state_lxsiren[veh] > 0 and actv_lxsrnmute_temp == false then
srntone_temp = state_lxsiren[veh]
SetLxSirenStateForVeh(veh, 0)
actv_lxsrnmute_temp = true
end
end
else
if not useFiretruckSiren(veh) then
if actv_lxsrnmute_temp == true then
SetLxSirenStateForVeh(veh, srntone_temp)
actv_lxsrnmute_temp = false
end
end
end
if state_airmanu[veh] ~= hmanu_state_new then
SetAirManuStateForVeh(veh, hmanu_state_new)
count_bcast_timer = delay_bcast_timer
end
end
--- IS ANY LAND VEHICLE ---
if GetVehicleClass(veh) ~= 14 and GetVehicleClass(veh) ~= 15 and GetVehicleClass(veh) ~= 16 and GetVehicleClass(veh) ~= 21 then
----- CONTROLS -----
if not IsPauseMenuActive() then
-- IND L
if IsDisabledControlJustReleased(0, 174) then -- INPUT_VEH_PREV_RADIO_TRACK
local cstate = state_indic[veh]
if cstate == ind_state_l then
state_indic[veh] = ind_state_o
actv_ind_timer = false
PlaySoundFrontend(-1, "NAV_UP_DOWN", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
else
state_indic[veh] = ind_state_l
actv_ind_timer = true
PlaySoundFrontend(-1, "NAV_LEFT_RIGHT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
end
TogIndicStateForVeh(veh, state_indic[veh])
count_ind_timer = 0
count_bcast_timer = delay_bcast_timer
-- IND R
elseif IsDisabledControlJustReleased(0, 175) then -- INPUT_VEH_NEXT_RADIO_TRACK
local cstate = state_indic[veh]
if cstate == ind_state_r then
state_indic[veh] = ind_state_o
actv_ind_timer = false
PlaySoundFrontend(-1, "NAV_UP_DOWN", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
else
state_indic[veh] = ind_state_r
actv_ind_timer = true
PlaySoundFrontend(-1, "NAV_LEFT_RIGHT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
end
TogIndicStateForVeh(veh, state_indic[veh])
count_ind_timer = 0
count_bcast_timer = delay_bcast_timer
-- IND H
elseif IsControlJustReleased(0, 173) then -- INPUT_FRONTEND_CANCEL / Backspace
if GetLastInputMethod(0) then -- last input was with kb
local cstate = state_indic[veh]
if cstate == ind_state_h then
state_indic[veh] = ind_state_o
PlaySoundFrontend(-1, "NAV_UP_DOWN", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
else
state_indic[veh] = ind_state_h
PlaySoundFrontend(-1, "NAV_LEFT_RIGHT", "HUD_FRONTEND_DEFAULT_SOUNDSET", 1)
end
TogIndicStateForVeh(veh, state_indic[veh])
actv_ind_timer = false
count_ind_timer = 0
count_bcast_timer = delay_bcast_timer
end
end
end
----- AUTO BROADCAST VEH STATES -----
if count_bcast_timer > delay_bcast_timer then
count_bcast_timer = 0
--- IS EMERG VEHICLE ---
if GetVehicleClass(veh) == 18 then
TriggerServerEvent("lvc_TogDfltSrnMuted_s", dsrn_mute)
TriggerServerEvent("lvc_SetLxSirenState_s", state_lxsiren[veh])
TriggerServerEvent("lvc_TogPwrcallState_s", state_pwrcall[veh])
TriggerServerEvent("lvc_SetAirManuState_s", state_airmanu[veh])
end
--- IS ANY OTHER VEHICLE ---
TriggerServerEvent("lvc_TogIndicState_s", state_indic[veh])
else
count_bcast_timer = count_bcast_timer + 1
end
end
end
end
Citizen.Wait(0)
end
end) |
require("tests/testsuite")
local document = Cmd.ImportODTFile("testdocs/testdoc.odt")
local expected = [[
%% This document automatically generated by WordGrinder 0.8.
\documentclass{article}
\usepackage{xunicode, setspace, xltxtra}
\sloppy
\onehalfspacing
\begin{document}
\title{testdoc.odt}
\author{(no author)}
\maketitle
\section{Heading 1}
This is \textbf{bold }\textit{\textbf{bolditalic }}\textit{\textbf{\underline{bolditalicunderline }}}\textit{\underline{italicunderline }}\underline{underline} }plain
normal text
\begin{enumerate}
\item[\textbullet]{bullet}
\item[\textbullet]{bullet}
\item[\textbullet]{no bullet}
\item[\textbullet]{no bullet}
\item{number}
\item{number}
\item[\textbullet]{nothing}
\item{number}
\item[\textbullet]{bullet}
\end{enumerate}
normal text
\end{document}
]]
DocumentSet:setCurrent("testdoc.odt")
local output = Cmd.ExportToLatexString()
AssertEquals(expected, output)
|
local fio = require('fio')
local socket = require('socket')
local t = require('luatest')
local g = t.group()
local helpers = require('test.helper')
local server
local tmpdir
g.before_all = function()
tmpdir = fio.tempdir()
server = helpers.Server:new({
alias = 'server',
workdir = tmpdir,
command = helpers.entrypoint('srv_basic'),
advertise_port = 13301,
http_port = 8080,
cluster_cookie = 'super-cluster-cookie',
env = {
TARANTOOL_CONSOLE_SOCK = fio.pathjoin(tmpdir, '/foo.sock'),
NOTIFY_SOCKET = fio.pathjoin(tmpdir, '/notify.sock')
},
})
local notify_socket = socket('AF_UNIX', 'SOCK_DGRAM', 0)
t.assert(notify_socket, 'Can not create socket')
t.assert(notify_socket:bind('unix/', server.env.NOTIFY_SOCKET), notify_socket:error())
server:start()
t.helpers.retrying({}, function()
t.assert(notify_socket:readable(1), "Socket isn't readable")
t.assert_str_matches(notify_socket:recv(), 'READY=1')
end)
end
g.after_all = function()
server:stop()
fio.rmtree(tmpdir)
end
g.test_console_sock = function()
local s = socket.tcp_connect('unix/', fio.pathjoin(tmpdir, 'foo.sock'))
t.assert(s)
local greeting = s:read('\n')
t.assert(greeting)
t.assert_str_matches(greeting:strip(), 'Tarantool.*%(Lua console%)')
end
|
dofile_once("[POLYTOOLS_PATH]disco_util/disco_util.lua")
local polytools = dofile_once("[POLYTOOLS_PATH]polytools.lua")
local self = Entity.Current()
polytools.load(self, self.var_str.polydata)
|
local Dictionary = script.Parent
local Llama = Dictionary.Parent
local t = require(Llama.t)
local validate = t.tuple(t.table, t.callback)
local function map(dictionary, mapper)
assert(validate(dictionary, mapper))
local new = {}
for key, value in pairs(dictionary) do
local newValue, newKey = mapper(value, key)
new[newKey or key] = newValue
end
return new
end
return map |
local current_folder = ... and (...):match '(.-%.?)[^%.]+$' or ''
local Layout = require(current_folder .. ".Layout")
local Rectangle = require(current_folder .. ".Rectangle")
local imgui = require(current_folder .. ".imgui")
local os = require(current_folder .. ".os")
local Scrollpane = {}
local scrollbar_margin = 7
local scroll_delta = 2
local scrollwheel_multipliers = {
mac = 4,
win = 16,
linux = 16,
}
local scrollwheel_multiplier = scrollwheel_multipliers[os.os] or 1
local function handle_input(state, scrollpane_state)
assert(state.input)
local scroll_dx = state.input.mouse.wheel_dx
local scroll_dy = state.input.mouse.wheel_dy
-- Scroll horizontally instead of vertically when shift is pressed
if (os.win or os.linux) and scroll_dx == 0 then
if imgui.is_key_pressed(state, "lshift") or
imgui.is_key_pressed(state, "rshift")
then
scroll_dx = -scroll_dy
scroll_dy = 0
end
end
-- Only handle image panning if the mousewheel was triggered inside
-- this widget.
if Scrollpane.is_mouse_inside_widget(state, scrollpane_state) then
local threshold = 3
if scroll_dx ~= 0 then
scrollpane_state.tx = scrollpane_state.x + scrollwheel_multiplier*scroll_dx
elseif math.abs(scrollpane_state.last_dx) > threshold then
scrollpane_state.tx = scrollpane_state.x + scrollpane_state.last_dx
end
if scroll_dy ~= 0 then
scrollpane_state.ty = scrollpane_state.y - scrollwheel_multiplier*scroll_dy
elseif math.abs(scrollpane_state.last_dy) > threshold then
scrollpane_state.ty = scrollpane_state.y + scrollpane_state.last_dy
end
end
end
-- Moves the viewport's focus by the given delta as far as possible
-- without violating the bounds set in the scrollpane state
local move_viewport_within_bounds = function(sp_state, dx, dy)
local new_x, new_y = sp_state.x + dx, sp_state.y + dy
if sp_state.min_x then
new_x = math.max(sp_state.min_x, new_x)
end
if sp_state.min_y then
new_y = math.max(sp_state.min_y, new_y)
end
if sp_state.max_x then
new_x = math.min(sp_state.max_x - sp_state.w, new_x)
end
if sp_state.max_y then
new_y = math.min(sp_state.max_y - sp_state.h, new_y)
end
sp_state.x = new_x
sp_state.y = new_y
end
function Scrollpane.move_viewport(sp_state, dx, dy)
move_viewport_within_bounds(sp_state, dx, dy)
sp_state.tx = sp_state.x
sp_state.ty = sp_state.y
end
-- Move the scrollpane to focus on the given bounds.
-- Might be restricted by the inner bounds in the scrollpane_state
-- (i.e. when moving to the first item, it will not center the viewport on
-- that item, but rather have the viewport's upper bound line up with the upper
-- bound of that item.)
local apply_focus = function(gui_state, scrollpane_state)
assert(gui_state)
assert(scrollpane_state)
assert(scrollpane_state.focus)
local bounds = scrollpane_state.focus
-- We cannot focus on a specific element if we don't know the viewport's
-- dimensions
if not (scrollpane_state.w or scrollpane_state.h) then return end
-- Try to center the scrollpane viewport on the given bounds, but without
-- exceeding the limits set in the scrollpane state
local center_bounds = {}
center_bounds.x, center_bounds.y = Rectangle.center(bounds)
-- This works because the scrollpane has x, y, w and h
local center_vp = {}
center_vp.x, center_vp.y = Rectangle.center(scrollpane_state)
local dx, dy = center_bounds.x - center_vp.x, center_bounds.y - center_vp.y
local x, y = scrollpane_state.x + dx, scrollpane_state.y + dy
-- In immediate mode both the current and the target location are changed
if bounds.mode and bounds.mode == "immediate" then
move_viewport_within_bounds(scrollpane_state, dx, dy)
end
-- Otherwise only the target position is changed
scrollpane_state.tx = x
scrollpane_state.ty = y
scrollpane_state.focus = nil
end
-- Mode can be either "immediate" or "transition". Immediate makes the viewport
-- jump to the target position on the next frame, while transition causes a
-- smoother transition.
Scrollpane.set_focus = function(scrollpane_state, bounds, mode)
scrollpane_state.focus = {
x = bounds.x,
y = bounds.y,
w = bounds.w or 0,
h = bounds.h or 0,
mode = mode,
}
end
Scrollpane.is_in_viewport = function(scrollpane_state, bounds)
return Rectangle.contains(scrollpane_state, bounds.x, bounds.y, bounds.w, bounds.h)
end
Scrollpane.move_into_view = function(scrollpane_state, bounds, mode)
if Scrollpane.is_in_viewport(scrollpane_state, bounds) then return
else
scrollpane_state.focus = {
x = bounds.x,
y = bounds.y,
w = bounds.w,
h = bounds.h,
mode = mode,
}
end
end
Scrollpane.is_mouse_inside_widget = function(gui_state, scrollpane_state, mx, my)
if not gui_state or not gui_state.input then return false end
-- We cannot check this until the scrollpane was drawn once
if not (scrollpane_state.transform and scrollpane_state.w and
scrollpane_state.h)
then
return false
end
return imgui.is_mouse_in_rect(gui_state, 0, 0,
scrollpane_state.w, scrollpane_state.h, mx, my,
scrollpane_state.transform)
end
Scrollpane.init_scrollpane_state = function(x, y, min_x, min_y, max_x, max_y)
return {
x = x or 0, -- the x offset of the viewport
y = y or 0, -- the y offset of the viewport
-- If any of the following are set to nil, then the viewport's movement
-- is not restricted.
min_x = min_x, -- the x coordinate below which the viewport cannot be moved
min_y = min_y, -- the y coordinate below which the viewport cannot be moved
max_x = max_x, -- the x coordinate above which the viewport cannot be moved
max_y = max_y, -- the y coordinate above which the viewport cannot be moved
-- the dimensions of the scrollpane's viewport. will be updated
-- automatically
w = nil,
h = nil,
-- We need a reference to the transformation transform that is being used
-- when the scrollpane starts.
transform = nil,
-- whether the scrollpane needed scrollbars in the last frame
had_vertical = false,
had_horizontal = false,
-- Scrolling behavior
tx = 0, -- target translate translation in x
ty = 0, -- target translate translation in y
last_dx = 0, -- last translate speed in x
last_dy = 0, -- last translate speed in y
-- Focus, will be applied on the next frame
focus = nil,
}
end
Scrollpane.start = function(state, x, y, w, h, scrollpane_state)
scrollpane_state = scrollpane_state or Scrollpane.init_scrollpane_state()
assert(state)
assert(scrollpane_state)
x = x or state.layout.next_x
y = y or state.layout.next_y
w = w or state.layout.max_w
h = h or state.layout.max_h
-- Start a layout that contains this scrollpane
Layout.start(state, x, y, w, h)
love.graphics.clear(state.style.palette.scrollpane_background)
-- Calculate the dimension of the viewport, based on whether the viewport
-- needed a scrollbar in the last frame
local inner_w = w
if scrollpane_state.had_vertical then inner_w = inner_w - scrollbar_margin end
local inner_h = h
if scrollpane_state.had_horizontal then inner_h = inner_h - scrollbar_margin end
-- The scrollpane's content will not see any input unless the mouse is in
-- the scrollpane's area
scrollpane_state.covered_input = not imgui.is_mouse_in_rect(state, 0, 0, inner_w, inner_h)
if scrollpane_state.covered_input then
imgui.cover_input(state)
end
-- Start a layout that encloses the viewport's content
Layout.start(state, 0, 0, inner_w, inner_h)
-- Update the scrollpane's viewport width and height
scrollpane_state.w = state.layout.max_w
scrollpane_state.h = state.layout.max_h
-- Update the scrollpane's transform transform
scrollpane_state.transform = state.transform:clone()
-- Apply focus if there is one
if scrollpane_state.focus then
apply_focus(state, scrollpane_state)
end
-- Note the flipped signs
love.graphics.translate(-scrollpane_state.x, -scrollpane_state.y)
return scrollpane_state
end
Scrollpane.finish = function(state, scrollpane_state, content_w, content_h)
-- If the content defined advance values in x and y, we can detect whether
-- we need to draw scroll bars at all.
content_w = content_w or state.layout.adv_x
content_h = content_h or state.layout.adv_y
-- Finish the layout that encloses the viewport's content
Layout.finish(state)
if scrollpane_state.covered_input then
imgui.uncover_input(state)
end
local x = state.layout.next_x
local y = state.layout.next_y
local w = state.layout.max_w
local h = state.layout.max_h
local inner_w = state.layout.max_w - (scrollpane_state.had_vertical and
scrollbar_margin or 0)
local inner_h = state.layout.max_h - (scrollpane_state.had_horizontal and
scrollbar_margin or 0)
-- we have to take cases into account where the viewport can move beyond
-- the content
local total_content_h = content_h
if scrollpane_state.dragging_vertical_height then
total_content_h = scrollpane_state.dragging_vertical_height
elseif scrollpane_state.y < 0 then
total_content_h = total_content_h + math.abs(scrollpane_state.y)
scrollpane_state.extra_v_lead = math.abs(scrollpane_state.y)
elseif scrollpane_state.y > content_h - inner_h then
total_content_h = total_content_h + scrollpane_state.y - (content_h - inner_h)
end
local has_vertical = scrollpane_state.is_dragging_vertical or total_content_h > inner_h
-- we have to take cases into account where the viewport can move beyond
-- the content
local total_content_w = content_w
if scrollpane_state.dragging_horizontal_width then
total_content_w = scrollpane_state.dragging_horizontal_width
elseif scrollpane_state.x < 0 then
total_content_w = total_content_w + math.abs(scrollpane_state.x)
scrollpane_state.extra_h_lead = math.abs(scrollpane_state.x)
elseif scrollpane_state.x > content_w - inner_w then
total_content_w = total_content_w + scrollpane_state.x - (content_w - inner_w)
end
local has_horizontal = scrollpane_state.is_dragging_horizontal or total_content_w > inner_w
local quads = state.style.quads.scrollpane
local function viewport_from_scrollbar(sb_pos, sb_area, total_sb_size,
total_content_size, inner_size)
-- Limit it to the same bounds that we used when drawing it
sb_pos = math.max(0, math.min(sb_area - total_sb_size, sb_pos))
-- Reverse all calculations that we did to draw the scrollbar
-- in order to get the new viewport position
local new_rel_vp_pos = sb_pos / (sb_area - total_sb_size)
local new_vp_pos = new_rel_vp_pos * (total_content_size - inner_size)
return new_vp_pos
end
local function get_button_state(bounds, was_pressed)
local button_state = "default"
if state and state.input then
if imgui.is_mouse_in_rect(state, bounds.x, bounds.y, bounds.w, bounds.h) then
button_state = "hovered"
if state.input.mouse.buttons and state.input.mouse.buttons[1]
and state.input.mouse.buttons[1].presses >= 1 then
button_state = "pressed"
end
end
if state.input.mouse.buttons and state.input.mouse.buttons[1] then
if was_pressed and not state.input.mouse.buttons[1].pressed then
button_state = "default"
elseif was_pressed then
button_state = "pressed"
end
end
end
return button_state
end
-- Render the vertical scrollbar if necessary
if has_vertical then
local height = h
if has_horizontal then height = height - scrollbar_margin end
-- scrollbar
love.graphics.draw(state.style.stylesheet, quads.scrollbar_v.background,
x + w - scrollbar_margin, y + scrollbar_margin,
0, 1, height - 2*scrollbar_margin)
-- The area in which the scrollbar can be moved around
local sb_area = height - 2*scrollbar_margin - 2
-- The maximum scrollbar height needs to leave room for the top and
-- bottom sprite, as well as a one pixel margin to either side
local max_sb_height = sb_area -
state.style.raw_quads.scrollpane.scrollbar_v.bottom.h -
state.style.raw_quads.scrollpane.scrollbar_v.top.h
local sb_height = math.floor((inner_h / total_content_h) * max_sb_height)
sb_height = math.max(1, sb_height)
-- Relative viewport position: 0 when the viewport shows the very
-- beginning of the content, 1 when the viewport shows the very end of
-- the content
local rel_vp_pos =
(scrollpane_state.y + (scrollpane_state.extra_v_lead or 0)) /
(total_content_h - inner_h)
-- crop to [0, 1]
rel_vp_pos = math.min(1, math.max(0, rel_vp_pos))
local total_sb_height = sb_height +
state.style.raw_quads.scrollpane.scrollbar_v.bottom.h +
state.style.raw_quads.scrollpane.scrollbar_v.top.h
local sb_start = rel_vp_pos * (sb_area - total_sb_height)
local sb_y = scrollbar_margin + 1 + sb_start
love.graphics.draw(state.style.stylesheet, quads.scrollbar_v.top,
x + w - scrollbar_margin, sb_y)
sb_y = sb_y + state.style.raw_quads.scrollpane.scrollbar_v.top.h
love.graphics.draw(state.style.stylesheet, quads.scrollbar_v.center,
x + w - scrollbar_margin, sb_y, 0, 1, sb_height)
sb_y = sb_y + sb_height
love.graphics.draw(state.style.stylesheet, quads.scrollbar_v.bottom,
x + w - scrollbar_margin, sb_y)
local sb_end = sb_y + state.style.raw_quads.scrollpane.scrollbar_v.bottom.h
-- Move viewport when mouse was dragged
if state and state.input and state.input.mouse.buttons[1] then
-- Update drag state
if state.input.mouse.buttons[1].presses >= 1 and
state.input.mouse.buttons[1].pressed and
imgui.is_mouse_in_rect(state, x + w - scrollbar_margin, sb_start + scrollbar_margin + 1,
scrollbar_margin, sb_end - (sb_start + scrollbar_margin + 1))
then
scrollpane_state.is_dragging_vertical = true
scrollpane_state.dragging_vertical_height = total_content_h
elseif state.input.mouse.buttons[1].releases > 1 or
not state.input.mouse.buttons[1].pressed
then
scrollpane_state.is_dragging_vertical = false
scrollpane_state.dragging_vertical_height = nil
scrollpane_state.extra_v_lead = nil
end
if scrollpane_state.is_dragging_vertical then
-- Calculate the desired viewport position from the moved scrollbar
local _, dy = state.transform:unproject_dimensions(0, state.input.mouse.dy)
-- local dy = state.input.mouse.dy
if dy ~= 0 then
-- Calculate the scrollbar position with this delta applied
local new_sb = sb_start + dy
local new_vp_y = viewport_from_scrollbar(
new_sb, sb_area, total_sb_height, total_content_h, inner_h)
if scrollpane_state.extra_v_lead then
new_vp_y = new_vp_y - scrollpane_state.extra_v_lead
end
-- Move viewport to that position
move_viewport_within_bounds(scrollpane_state, 0, new_vp_y - scrollpane_state.y)
scrollpane_state.ty = scrollpane_state.y
end
elseif state.input.mouse.buttons[1].presses >= 1 and
imgui.is_mouse_in_rect(state,
x + w - scrollbar_margin, scrollbar_margin + 1,
scrollbar_margin, sb_area)
then
-- Move viewport to click position. The scrollbar should be
-- centered around the click position.
local _, my = state.transform:unproject(0, state.input.mouse.y)
-- Subtract margin and offset
my = my - scrollbar_margin - 1
-- Subtract half of the scrollbar to center scrollbar around mouse
my = my - .5 * total_sb_height
local new_vp_y = viewport_from_scrollbar(
my, sb_area, total_sb_height, total_content_h, inner_h)
-- Move viewport to that position
move_viewport_within_bounds(scrollpane_state, 0, new_vp_y - scrollpane_state.y)
scrollpane_state.ty = scrollpane_state.y
end
end
-- buttons
do
local bounds = {
x = x + w - scrollbar_margin, y = y,
w = scrollbar_margin, h = scrollbar_margin}
local button_state = get_button_state(bounds, scrollpane_state.scrolling_up)
scrollpane_state.scrolling_up = button_state == "pressed"
if scrollpane_state.scrolling_up then
move_viewport_within_bounds(scrollpane_state, 0, -scroll_delta)
scrollpane_state.ty = scrollpane_state.y
end
love.graphics.draw(state.style.stylesheet, quads.buttons.up[button_state],
x + w - scrollbar_margin, y)
end
do
local bounds = {
x = x + w - scrollbar_margin, y = y + height - scrollbar_margin,
w = scrollbar_margin, h = scrollbar_margin}
local button_state = get_button_state(bounds, scrollpane_state.scrolling_down)
scrollpane_state.scrolling_down = button_state == "pressed"
if scrollpane_state.scrolling_down then
move_viewport_within_bounds(scrollpane_state, 0, scroll_delta)
scrollpane_state.ty = scrollpane_state.y
end
love.graphics.draw(state.style.stylesheet, quads.buttons.down[button_state],
x + w - scrollbar_margin, y + height - scrollbar_margin)
end
end
-- Render the horizontal scrollbar if necessary
if has_horizontal then
local width = w
if has_vertical then width = width - scrollbar_margin end
-- scrollbar
love.graphics.draw(state.style.stylesheet, quads.scrollbar_h.background,
x + scrollbar_margin, y + h - scrollbar_margin,
0, width - 2*scrollbar_margin, 1)
-- The area in which the scrollbar can be moved around
local sb_area = width - 2*scrollbar_margin - 2
-- The maximum scrollbar width needs to leave room for the left and
-- right sprite, as well as a one pixel margin to either side
local max_sb_width = sb_area -
state.style.raw_quads.scrollpane.scrollbar_h.left.w -
state.style.raw_quads.scrollpane.scrollbar_h.right.w
local sb_width = math.floor((inner_w / total_content_w) * max_sb_width)
sb_width = math.max(1, sb_width)
-- Relative viewport position: 0 when the viewport shows the very
-- beginning of the content, 1 when the viewport shows the very end of
-- the content
local rel_vp_pos =
(scrollpane_state.x + (scrollpane_state.extra_h_lead or 0)) /
(total_content_w - inner_w)
-- crop to [0, 1]
rel_vp_pos = math.min(1, math.max(0, rel_vp_pos))
local total_sb_width = sb_width +
state.style.raw_quads.scrollpane.scrollbar_h.left.w +
state.style.raw_quads.scrollpane.scrollbar_h.right.w
local sb_start = rel_vp_pos * (sb_area - total_sb_width)
local sb_x = scrollbar_margin + 1 + sb_start
love.graphics.draw(state.style.stylesheet, quads.scrollbar_h.left,
sb_x, y + h - scrollbar_margin)
sb_x = sb_x + state.style.raw_quads.scrollpane.scrollbar_h.left.w
love.graphics.draw(state.style.stylesheet, quads.scrollbar_h.center,
sb_x, y + h - scrollbar_margin, 0, sb_width, 1)
sb_x = sb_x + sb_width
love.graphics.draw(state.style.stylesheet, quads.scrollbar_h.right,
sb_x, y + h - scrollbar_margin)
local sb_end = sb_x + state.style.raw_quads.scrollpane.scrollbar_h.right.w
-- Move viewport when mouse was dragged
if state and state.input and state.input.mouse.buttons[1] then
-- Update drag state
if state.input.mouse.buttons[1].presses >= 1 and
state.input.mouse.buttons[1].pressed and
imgui.is_mouse_in_rect(state, sb_start + scrollbar_margin + 1, y + h - scrollbar_margin,
sb_end - (sb_start + scrollbar_margin + 1), scrollbar_margin)
then
scrollpane_state.is_dragging_horizontal = true
scrollpane_state.dragging_horizontal_width = total_content_w
elseif state.input.mouse.buttons[1].releases > 1 or
not state.input.mouse.buttons[1].pressed
then
scrollpane_state.is_dragging_horizontal = false
scrollpane_state.dragging_horizontal_width = nil
scrollpane_state.extra_h_lead = nil
end
if scrollpane_state.is_dragging_horizontal then
-- Calculate the desired viewport position from the moved scrollbar
local dx, _ = state.transform:unproject_dimensions(state.input.mouse.dx, 0)
if dx ~= 0 then
-- Calculate the scrollbar position with this delta applied
local new_sb = sb_start + dx
local new_vp_x = viewport_from_scrollbar(
new_sb, sb_area, total_sb_width, total_content_w, inner_w)
if scrollpane_state.extra_h_lead then
new_vp_x = new_vp_x - scrollpane_state.extra_h_lead
end
-- Move viewport to that position
move_viewport_within_bounds(scrollpane_state, new_vp_x - scrollpane_state.x, 0)
scrollpane_state.tx = scrollpane_state.x
end
elseif state.input.mouse.buttons[1].presses >= 1 and
imgui.is_mouse_in_rect(state,
scrollbar_margin + 1, y + h - scrollbar_margin,
sb_area, scrollbar_margin)
then
-- Move viewport to click position. The scrollbar should be
-- centered around the click position.
local mx, _ = state.transform:unproject(state.input.mouse.x, 0)
-- Subtract margin and offset
mx = mx - scrollbar_margin - 1
-- Subtract half of the scrollbar to center scrollbar around mouse
mx = mx - .5 * total_sb_width
local new_vp_x = viewport_from_scrollbar(
mx, sb_area, total_sb_width, total_content_w, inner_w)
-- Move viewport to that position
move_viewport_within_bounds(scrollpane_state, new_vp_x - scrollpane_state.x, 0)
scrollpane_state.tx = scrollpane_state.x
end
end
-- buttons
do
local bounds = {
x = x, y = y + h - scrollbar_margin,
w = scrollbar_margin, h = scrollbar_margin}
local button_state = get_button_state(bounds, scrollpane_state.scrolling_left)
scrollpane_state.scrolling_left = button_state == "pressed"
if scrollpane_state.scrolling_left then
move_viewport_within_bounds(scrollpane_state, -scroll_delta, 0)
scrollpane_state.tx = scrollpane_state.x
end
love.graphics.draw(state.style.stylesheet, quads.buttons.left[button_state],
x, y + h - scrollbar_margin)
end
do
local bounds = {
x = x + width - scrollbar_margin, y = y + h - scrollbar_margin,
w = scrollbar_margin, h = scrollbar_margin}
local button_state = get_button_state(bounds, scrollpane_state.scrolling_right)
scrollpane_state.scrolling_right = button_state == "pressed"
if scrollpane_state.scrolling_right then
move_viewport_within_bounds(scrollpane_state, scroll_delta, 0)
scrollpane_state.tx = scrollpane_state.x
end
love.graphics.draw(state.style.stylesheet, quads.buttons.right[button_state],
x + width - scrollbar_margin, y + h - scrollbar_margin)
end
end
-- Render the little corner if we have both a vertical and horizontal
-- scrollbar
if has_vertical and has_horizontal then
love.graphics.draw(state.style.stylesheet, quads.corner,
x + w - scrollbar_margin, y + h - scrollbar_margin)
end
scrollpane_state.had_vertical = has_vertical
scrollpane_state.had_horizontal = has_horizontal
if state and state.input then
handle_input(state, scrollpane_state)
end
-- Image panning
local friction = 0.5
-- Gently pan to target position
local dx = friction * (scrollpane_state.tx - scrollpane_state.x)
local dy = friction * (scrollpane_state.ty - scrollpane_state.y)
-- Apply the translation change
move_viewport_within_bounds(scrollpane_state, dx, dy)
-- Remember the last delta to possibly trigger floating in the next frame
scrollpane_state.last_dx = dx
scrollpane_state.last_dy = dy
-- This layout always fills the available space
state.layout.adv_x = state.layout.max_w
state.layout.adv_y = state.layout.max_h
Layout.finish(state)
end
return Scrollpane |
#!/usr/bin/env lua
local dkjson = require "dkjson"
local function load_keymap(target, target_map, macos)
_G.MACOS = macos
package.loaded["core.keymap"] = nil
local keymap = require "core.keymap"
if target then
keymap.map = {}
require(target)
end
target_map = target_map or {}
-- keymap.reverse_map does not do this?
for key, actions in pairs(keymap.map) do
for _, action in ipairs(actions) do
target_map[action] = target_map[action] or {}
table.insert(target_map[action], key)
end
end
return target_map
end
local function normalize(map)
local result = {}
for action, keys in pairs(map) do
local uniq = {}
local r = { combination = {}, action = action }
for _, v in ipairs(keys) do
if not uniq[v] then
uniq[v] = true
r.combination[#r.combination+1] = v
end
end
result[#result+1] = r
end
table.sort(result, function(a, b) return a.action < b.action end)
return result
end
local function process_module(mod, filename)
local map = {}
load_keymap(mod, map)
load_keymap(mod, map, true)
map = normalize(map)
local f = assert(io.open(filename, "wb"))
f:write(dkjson.encode(map, { indent = true }))
f:close()
end
print("Warning: this is not guaranteed to work outside lite-xl's own keymap. Proceed with caution")
local LITE_ROOT = arg[1]
if not LITE_ROOT then
error("LITE_ROOT is not given")
end
package.path = package.path .. ";" .. LITE_ROOT .. "/?.lua;" .. LITE_ROOT .. "/?/init.lua"
-- fix core.command (because we don't want load the entire thing)
package.loaded["core.command"] = {}
if #arg > 1 then
for i = 2, #arg do
process_module(arg[i], arg[i] .. ".json")
print(string.format("Exported keymap in %q.", arg[i]))
end
else
process_module(nil, "core.keymap.json")
print("Exported the default keymap.")
end
|
-- ========================================================================
-- $File: jcslove_debug.lua $
-- $Date: 2016-09-10 15:30:42 $
-- $Revision: 1.3.0 $
-- $Creator: Jen-Chieh Shen $
-- $Notice: See LICENSE.txt for modification and distribution information $
-- Copyright (c) 2016 by Shen, Jen-Chieh $
-- ========================================================================
jcslove_debug =
{
-- global macros
DEBUG = false,
}
DEBUG_COLOR =
{
r = 127,
g = 127,
b = 127,
a = 127,
}
------------------------------------------------
-- Set the color to debug color set.
------------------------------------------------
function jcslove_debug.DebugColor()
love.graphics.setColor(
DEBUG_COLOR.r,
DEBUG_COLOR.g,
DEBUG_COLOR.b,
DEBUG_COLOR.a)
end
------------------------------------------------
-- Print out the Error Log
------------------------------------------------
-- @param str: message to print
------------------------------------------------
function jcslove_debug.Error(str)
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
print("Error: " .. str)
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
end
------------------------------------------------
-- Print out the Warning Log
------------------------------------------------
-- @param str: message to print
------------------------------------------------
function jcslove_debug.Warning(str)
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
print("Warnging: " .. str)
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
end
------------------------------------------------
-- Print out the Informational Log
------------------------------------------------
-- @param str: message to print
------------------------------------------------
function jcslove_debug.Informational(str)
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
print("Informational: " .. str)
print("=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=-=")
end
|
local gl = require('galaxyline')
local gls = gl.section
local diagnostic = require('galaxyline.provider_diagnostic')
gl.short_line_list = {
'LuaTree',
'vista',
'dbui',
'startify',
'term',
'nerdtree',
'fugitive',
'fugitiveblame',
'plug'
}
-- VistaPlugin = extension.vista_nearest
local colors = {
bg = '#5C687A',
line_bg = '#16191d',
fg = '#8FBCBB',
fg_green = '#65a380',
yellow = '#E5C07B',
cyan = '#70C0BA',
darkblue = '#83A598',
green = '#98C379',
orange = '#FF8800',
purple = '#C678DD',
magenta = '#C858E9',
blue = '#73BA9F',
red = '#D54E53'
}
local function has_file_type()
local f_type = vim.bo.filetype
if not f_type or f_type == '' then
return false
end
return true
end
local buffer_not_empty = function()
if vim.fn.empty(vim.fn.expand('%:t')) ~= 1 then
return true
end
return false
end
-- insert_left insert item at the left panel
local function insert_left(element)
table.insert(gls.left, element)
end
-- insert_blank_line_at_left insert blank line with
-- line_bg color.
local function insert_blank_line_at_left()
insert_left {
Space = {
provider = function()
return ' '
end,
highlight = {colors.line_bg, colors.line_bg}
}
}
end
-- insert_right insert given item into galaxyline.right
local function insert_right(element)
table.insert(gls.right, element)
end
-- insert_blank_line_at_left insert blank line with
-- line_bg color.
local function insert_blank_line_at_right()
insert_right {
Space = {
provider = function()
return ' '
end,
highlight = {colors.line_bg, colors.line_bg}
}
}
end
-----------------------------------------------------
----------------- start insert ----------------------
-----------------------------------------------------
--{ mode panel start
insert_left {
Start = {
provider = function()
return ' '
end,
highlight = {colors.line_bg}
}
}
insert_blank_line_at_left()
insert_left {
ViMode = {
icon = function()
local icons = {
n = ' ',
i = ' ',
c = 'ﲵ ',
V = ' ',
[''] = ' ',
v = ' ',
C = 'ﲵ ',
R = ' ',
t = ' '
}
return icons[vim.fn.mode()]
end,
provider = function()
-- auto change color according the vim mode
local alias = {
n = 'N',
i = 'I',
c = 'C',
V = 'VL',
[''] = 'V',
v = 'V',
C = 'C',
['r?'] = ':CONFIRM',
rm = '--MORE',
R = 'R',
Rv = 'R&V',
s = 'S',
S = 'S',
['r'] = 'HIT-ENTER',
[''] = 'SELECT',
t = 'T',
['!'] = 'SH'
}
local mode_color = {
n = colors.yellow,
i = colors.green,
v = colors.blue,
[''] = colors.blue,
V = colors.blue,
c = colors.magenta,
no = colors.red,
s = colors.orange,
S = colors.orange,
[''] = colors.orange,
ic = colors.yellow,
R = colors.purple,
Rv = colors.purple,
cv = colors.red,
ce = colors.red,
r = colors.cyan,
rm = colors.cyan,
['r?'] = colors.cyan,
['!'] = colors.red,
t = colors.red
}
local vim_mode = vim.fn.mode()
vim.api.nvim_command('hi GalaxyViMode guifg=' .. mode_color[vim_mode])
return alias[vim_mode]
end,
highlight = {colors.line_bg, colors.line_bg}
}
}
insert_blank_line_at_left()
insert_left {
Separa = {
provider = function()
return ' '
end,
highlight = {colors.line_bg}
}
}
--mode panel end}
-- {information panel start
insert_left {
Start = {
provider = function()
return ' '
end,
highlight = {colors.line_bg}
}
}
insert_left {
FileIcon = {
provider = 'FileIcon',
condition = buffer_not_empty,
highlight = {require('galaxyline.provider_fileinfo').get_file_icon_color, colors.line_bg}
}
}
insert_left {
BufferType = {
provider = 'FileTypeName',
condition = has_file_type,
highlight = {colors.fg, colors.line_bg}
}
}
insert_blank_line_at_left()
insert_left {
GitIcon = {
provider = function()
return ' '
end,
condition = require('galaxyline.provider_vcs').check_git_workspace,
highlight = {colors.orange, colors.line_bg}
}
}
insert_left {
GitBranch = {
provider = 'GitBranch',
condition = require('galaxyline.provider_vcs').check_git_workspace,
highlight = {'#8FBCBB', colors.line_bg}
}
}
insert_blank_line_at_left()
local checkwidth = function()
local squeeze_width = vim.fn.winwidth(0) / 2
if squeeze_width > 40 then
return true
end
return false
end
insert_left {
DiffAdd = {
provider = 'DiffAdd',
condition = checkwidth,
icon = ' ',
highlight = {colors.green, colors.line_bg}
}
}
insert_left {
DiffModified = {
provider = 'DiffModified',
condition = checkwidth,
icon = ' ',
highlight = {colors.orange, colors.line_bg}
}
}
insert_left {
DiffRemove = {
provider = 'DiffRemove',
condition = checkwidth,
icon = ' ',
highlight = {colors.red, colors.line_bg}
}
}
DiagnosticError = diagnostic.get_diagnostic_error
DiagnosticWarn = diagnostic.get_diagnostic_warn
DiagnosticHint = diagnostic.get_diagnostic_hint
DiagnosticInfo = diagnostic.get_diagnostic_info
insert_left {
DiagnosticError = {
provider = 'DiagnosticError',
icon = ' ',
highlight = {colors.red, colors.line_bg}
}
}
insert_left {
DiagnosticWarn = {
provider = 'DiagnosticWarn',
condition = checkwidth,
icon = ' ',
highlight = {colors.yellow, colors.line_bg}
}
}
insert_left {
DiagnosticInfo = {
provider = DiagnosticInfo,
condition = checkwidth,
highlight = {colors.green, colors.line_bg},
icon = ' '
}
}
insert_left {
DiagnosticHint = {
provider = DiagnosticHint,
condition = checkwidth,
highlight = {colors.white, colors.line_bg},
icon = ' '
}
}
insert_left {
Separa = {
provider = function()
return ' '
end,
highlight = {colors.line_bg}
}
}
-- left information panel end}
insert_right {
Start = {
provider = function()
return ' '
end,
highlight = {colors.line_bg}
}
}
insert_blank_line_at_right()
insert_right {
FileFormat = {
provider = 'FileFormat',
condition = checkwidth,
highlight = {colors.fg, colors.line_bg, 'bold'}
}
}
insert_blank_line_at_right()
insert_right {
LineInfo = {
provider = 'LineColumn',
separator = ' ',
condition = checkwidth,
separator_highlight = {colors.green, colors.line_bg},
highlight = {colors.fg, colors.line_bg}
}
}
insert_right {
PerCent = {
provider = 'LinePercent',
separator = '',
separator_highlight = {colors.blue, colors.line_bg},
highlight = {colors.cyan, colors.line_bg, 'bold'}
}
}
insert_right {
Encode = {
provider = 'FileEncode',
separator = '',
condition = checkwidth,
separator_highlight = {colors.blue, colors.line_bg},
highlight = {colors.cyan, colors.line_bg, 'bold'}
}
}
insert_blank_line_at_right()
insert_right {
Separa = {
provider = function()
return ' '
end,
highlight = {colors.line_bg}
}
}
|
--
-- Created by IntelliJ IDEA.
-- User: wei
-- Date: 2017/11/26
-- Time: 15:34
-- To change this template use File | Settings | File Templates.
--
a = {}
--a.bb = function(ppp)
-- print(ppp)
--end
function a.bb()
print(ppp)
end
for key,value in pairs(a) do
print(key)
print(value)
end |
function Client_PresentConfigureUI(rootParent)
if Mod.Settings.NumberOfHills == nil then initial0 = 2; else initial0 = Mod.Settings.NumberOfHills end
if Mod.Settings.SizeOfHills == nil then initial1 = 10; else initial1 = Mod.Settings.SizeOfHills end
local vert = UI.CreateVerticalLayoutGroup(rootParent);
local horz = UI.CreateHorizontalLayoutGroup(vert);
UI.CreateLabel(horz).SetText('Number of hills in the game');
NumberOfHillsSlider = UI.CreateNumberInputField(horz)
.SetSliderMinValue(1)
.SetSliderMaxValue(5)
.SetValue(initial0);
UI.CreateLabel(horz).SetText('Number of armies on each hill');
SizeOfHillsSlider = UI.CreateNumberInputField(horz)
.SetSliderMinValue(5)
.SetSliderMaxValue(15)
.SetValue(initial1);
end |
-- Item data (c) Grinding Gear Games
return {
["NORMAL"] = {
"Cast Word of Blades on Hit",
"Cast Word of Flames on Hit",
"Attack with Word of Force on Hit",
"Cast Word of Frost on Kill",
"Attack with Word of Fury on Hit",
"Cast Word of Inferno on Kill",
"Attack with Word of Ire when Hit",
"Attack with Word of Light when you take a Critical Strike",
"Cast Word of Reflection when Hit",
"Attack with Word of Spite when Hit",
"Cast Word of the Tempest on Hit",
"Cast Word of the Grave when your Skills or Minions Kill",
"Cast Word of Thunder on Kill",
"Attack with Word of War on Kill",
"Cast Word of Winter when Hit",
},
["CRUEL"] = {
"Cast Edict of Blades on Hit",
"Cast Edict of Flames on Hit",
"Attack with Edict of Force on Hit",
"Cast Edict of Frost on Kill",
"Attack with Edict of Fury on Hit",
"Cast Edict of Inferno on Kill",
"Attack with Edict of Ire when Hit",
"Attack with Edict of Light when you take a Critical Strike",
"Cast Edict of Reflection when Hit",
"Attack with Edict of Spite when Hit",
"Cast Edict of the Tempest on Hit",
"Cast Edict of the Grave when your Skills or Minions Kill",
"Cast Edict of Thunder on Kill",
"Attack with Edict of War on Kill",
"Cast Edict of Winter when Hit",
},
["MERCILESS"] = {
"Cast Decree of Blades on Hit",
"Cast Decree of Flames on Hit",
"Attack with Decree of Force on Hit",
"Cast Decree of Frost on Kill",
"Attack with Decree of Fury on Hit",
"Cast Decree of Inferno on Kill",
"Attack with Decree of Ire when Hit",
"Attack with Decree of Light when you take a Critical Strike",
"Cast Decree of Reflection when Hit",
"Attack with Decree of Spite when Hit",
"Cast Decree of the Tempest on Hit",
"Cast Decree of the Grave when your Skills or Minions Kill",
"Cast Decree of Thunder on Kill",
"Attack with Decree of War on Kill",
"Cast Decree of Winter when Hit",
},
["ENDGAME"] = {
"Cast Commandment of Blades on Hit",
"Cast Commandment of Flames on Hit",
"Attack with Commandment of Force on Hit",
"Cast Commandment of Frost on Kill",
"Attack with Commandment of Fury on Hit",
"Cast Commandment of Inferno on Kill",
"Attack with Commandment of Ire when Hit",
"Attack with Commandment of Light when you take a Critical Strike",
"Cast Commandment of Reflection when Hit",
"Attack with Commandment of Spite when Hit",
"Cast Commandment of the Tempest on Hit",
"Cast Commandment of the Grave when your Skills or Minions Kill",
"Cast Commandment of Thunder on Kill",
"Attack with Commandment of War on Kill",
"Cast Commandment of Winter when Hit",
},
} |
object_tangible_component_weapon_new_weapon_enhancement_ranged_slot_one_s14 = object_tangible_component_weapon_new_weapon_shared_enhancement_ranged_slot_one_s14:new {
}
ObjectTemplates:addTemplate(object_tangible_component_weapon_new_weapon_enhancement_ranged_slot_one_s14, "object/tangible/component/weapon/new_weapon/enhancement_ranged_slot_one_s14.iff")
|
-------------------------
-- Sassilization SMG
-- Spacetech
-------------------------
if(SERVER) then
AddCSLuaFile("shared.lua")
SWEP.Weight = 5
SWEP.AutoSwitchTo = true
SWEP.AutoSwitchFrom = true
else
SWEP.PrintName = "Sass SMG"
SWEP.Slot = 0
SWEP.SlotPos = 4
SWEP.DrawAmmo = false
SWEP.DrawCrosshair = true
SWEP.DrawWeaponInfoBox = false
end
SWEP.Base = "weapon_base"
SWEP.HoldType = "smg"
SWEP.ViewModel = Model("models/weapons/v_sass_smg.mdl")
SWEP.WorldModel = Model("models/weapons/w_sass_smg.mdl")
SWEP.ViewModelFlip = false
SWEP.Primary.ClipSize = 45
SWEP.Primary.DefaultClip = 90
SWEP.Primary.Automatic = true
SWEP.Primary.Ammo = "SMG1"
SWEP.Secondary.ClipSize = -1
SWEP.Secondary.DefaultClip = -1
SWEP.Secondary.Automatic = false
SWEP.Secondary.Ammo = "none"
SWEP.Punch = 0.25
SWEP.Spread = 0.04
SWEP.ShootSound = Sound("Weapon_M4A1.Single") -- Sound("Weapon_SMG1.Single")
SWEP.ReloadSound = Sound("Weapon_M4A1.Clipout") -- Sound("Weapon_SMG1.Reload")
SWEP.IronSightsPos = Vector(-4.2, -8, 1.58)
SWEP.IronSightsAng = Vector(0, 0, 0)
function SWEP:Initialize()
if(self.SetWeaponHoldType) then
self:SetWeaponHoldType(self.HoldType)
end
end
function SWEP:PrimaryAttack()
if(!self:CanPrimaryAttack()) then
return
end
self.Owner:FireBullets({
Num = 1,
Src = self.Owner:GetShootPos(),
Dir = self.Owner:GetAimVector(),
Spread = Vector(math.Rand(0, self.Spread), math.Rand(0, self.Spread), math.Rand(0, self.Spread)),
Tracer = 1,
Force = 5,
Damage = 14,
AmmoType = self.Primary.Ammo
})
self.Owner:MuzzleFlash()
self.Owner:SetAnimation(PLAYER_ATTACK1)
self.Weapon:SendWeaponAnim(ACT_VM_PRIMARYATTACK)
self.Owner:ViewPunch(Angle(math.Rand(0, self.Punch), math.Rand(0, self.Punch), math.Rand(0, self.Punch)))
self.Weapon:EmitSound(self.ShootSound, 75, math.random(90, 110))
self:TakePrimaryAmmo(1)
self.Weapon:SetNextPrimaryFire(CurTime() + 0.075)
end
/*
garry's Ironsights stuff
Semi edited
*/
local IRONSIGHT_TIME = 0.25
/*---------------------------------------------------------
Name: GetViewModelPosition
Desc: Allows you to re-position the view model
---------------------------------------------------------*/
function SWEP:GetViewModelPosition( pos, ang )
if ( !self.IronSightsPos ) then return pos, ang end
local bIron = self.Weapon:GetNetworkedBool( "Ironsights" )
if ( bIron != self.bLastIron ) then
self.bLastIron = bIron
self.fIronTime = CurTime()
if ( bIron ) then
self.SwayScale = 0.3
self.BobScale = 0.1
else
self.SwayScale = 1.0
self.BobScale = 1.0
end
end
local fIronTime = self.fIronTime or 0
if ( !bIron && fIronTime < CurTime() - IRONSIGHT_TIME ) then
return pos, ang
end
local Mul = 1.0
if ( fIronTime > CurTime() - IRONSIGHT_TIME ) then
Mul = math.Clamp( (CurTime() - fIronTime) / IRONSIGHT_TIME, 0, 1 )
if (!bIron) then Mul = 1 - Mul end
end
local Offset = self.IronSightsPos
if ( self.IronSightsAng ) then
ang = ang * 1
ang:RotateAroundAxis( ang:Right(), self.IronSightsAng.x * Mul )
ang:RotateAroundAxis( ang:Up(), self.IronSightsAng.y * Mul )
ang:RotateAroundAxis( ang:Forward(), self.IronSightsAng.z * Mul )
end
local Right = ang:Right()
local Up = ang:Up()
local Forward = ang:Forward()
pos = pos + Offset.x * Right * Mul
pos = pos + Offset.y * Forward * Mul
pos = pos + Offset.z * Up * Mul
return pos, ang
end
function SWEP:SetIronsights( b )
self.Weapon:SetNetworkedBool( "Ironsights", b )
end
SWEP.NextSecondaryAttack = 0
function SWEP:SecondaryAttack()
if ( self.NextSecondaryAttack > CurTime() ) then return end
self:SetIronsights(!self.Weapon:GetNetworkedBool( "Ironsights", false ))
self.NextSecondaryAttack = CurTime() + 0.3
end
|
push([[
-----------------------------------------------------------
--- /server/mysql_class.lua ---
--- Part of openFrame project ---
--- Written by Orange ---
--- Lately edited in revision number 13 by Orange ---
--- Licensed under BSD licence ---
-----------------------------------------------------------
-- Class: MySQL Class
-- MySQL Class allows you to use MySQL database easily.
MySQL = Class:Create();
-- Function: MySQL:Connect
-- Creates a MySQL connection object
--
-- Required Arguments:
-- host - (string) Hostname/IP address of MySQL server to connect.
-- user - (string) Username used to connect to MySQL server.
-- password - (string) Password used to connect to MySQL server.
-- db - (string) Name of database to select after connecting.
--
-- Optional Arguments:
-- reconnect - (bool) If true, reconnects every connection timeout.
--
-- Returns:
-- Returns MySQL connection object
function MySQL:Connect(host, user, pass, db, reconnect, socket)
local object = Class:Create(self);
object.connection = mysql_connect(host, user, pass, db, 3306, socket);
if reconnect == true then
object.reconnect = true;
end
object.host = host;
object.user = user;
object.pass = pass;
object.db = db;
if object.connection then
return object;
end
outputDebugString(mysql_error(object.connection))
return false;
end
-- Function: MySQL:Reconnect
-- Reconnects to database.
--
-- Returns:
-- Returns true if reconnected, false if not.
function MySQL:Reconnect()
self.connection = mysql_connect(self.host, self.user, self.pass, self.db);
if self:Ping() then
return true;
end
return false;
end
-- Function: MySQL:Query
-- Sends a query to database and makes a object from result.
--
-- Required Arguments:
-- str - (string) Query string.
--
-- Returns:
-- Returns MySQL result object.
function MySQL:Query(str)
if self.reconnect then
if self:Ping() ~= true then
self:Reconnect()
end
end
local object = Class:Create(MySQL.ret);
object.query = mysql_query(self.connection, str);
if object.query then
return object;
end
outputDebugString(self:Error())
return false;
end
function MySQL:Escape(str)
if self.reconnect then
if self:Ping() ~= true then
self:Reconnect()
end
end
return mysql_escape_string(self.connection, str);
end
-- Function: MySQL:Error
-- Returns last error string.
--
-- Returns:
-- Returns string with last error.
function MySQL:Error()
return mysql_error(self.connection)
end
-- Function: MySQL:Ping
-- Pings the server (checks the connection)
--
-- Returns:
-- Returns true if connection is alive, false if not.
function MySQL:Ping()
return mysql_ping(self.connection)
end
-- Function: MySQL:Errno
-- Returns last error number.
--
-- Returns:
-- Returns last error number.
function MySQL:Errno()
return mysql_errno(self.connection)
end
-- Class: MySQL.ret Class
-- Result extension of MySQL Class
MySQL.ret = Class:Create();
-- Function: MySQL.ret:fetchAssoc
-- Returns an associative table containing the current row of the query. You can call this function repeatedly to retreive all the result rows. When there aren't more rows in the result it returns nil.
--
-- Returns:
-- Returns table with current row.
function MySQL.ret:fetchAssoc()
return mysql_fetch_assoc(self.query)
end
-- Function: MySQL.ret:freeResult
-- Frees the last query result. This function should be called after every query, specially when these queries return any data.
--
-- Returns:
-- Returns true if freed, false if not.
function MySQL.ret:freeResult()
return mysql_free_result(self.query)
end
-- Function: MySQL.ret:numRows
-- Returns the number of rows in the result.
--
-- Returns:
-- Returns the number of rows in the result.
function MySQL.ret:numRows()
return mysql_num_rows(self.query)
end
function MySQL.ret:itTable()
local tab = {}
local i = 0
for k,v in mysql_rows(self.query) do
i = i + 1
tab[i] = {}
for k2, v2 in ipairs(v) do
tab[i][mysql_field_name(self.query, k2)] = v2
end
end
return tab;
end
]]) |
local c = require "levent.http.c"
local levent = require "levent.levent"
local httpUtil = require "levent.http.util"
local socketUtil = require "levent.socket_util"
local responseWriter = require "levent.http.response_writer"
local requestReader = require "levent.http.request_reader"
local server = {}
server.__index = server
function server.new(ip, port)
local obj = {
ip = ip,
port = port,
handlers = {}
}
return setmetatable(obj, server)
end
function server:register(handlers)
for k, v in pairs(handlers) do
assert(not self.handlers[k], "repeated register:" .. k)
self.handlers[k] = v
end
end
function server:handle_one_request(msg)
local path = msg.request_path
local rsp = responseWriter.new()
local handler = self.handlers[path]
if not handler then
rsp:set_code(404)
else
req = requestReader.new(msg)
local ok, err = xpcall(handler, debug.traceback, rsp, req)
if not ok then
print(string.format("handle request[%s] failed: %s", path, err))
rsp:set_code(502)
rsp:set_data(err)
end
end
return rsp
end
function server:handle_conn(conn)
local host, port = conn:getpeername()
print("new connection:", host, port)
local parser = c.new(c.HTTP_REQUEST)
local cached
while true do
local msg, left = httpUtil.read_message(conn, parser, cached)
if not msg then
print("read request failed:", left)
break
end
-- connection close
if not msg.complete then
break
end
local url = c.parse_url(msg.request_url)
if not url then
break
end
-- url info
msg.host = url.host
msg.port = url.port
msg.request_path = url.request_path
msg.query_string = url.query_string
msg.userinfo = url.userinfo
-- remote info
msg.remote_host = host
msg.remote_port = port
local rsp = self:handle_one_request(msg)
if not rsp then
break
end
conn:sendall(rsp:pack())
if not msg.keepalive then
break
end
cached = left
end
conn:close()
print("connection close:", host, port)
end
function server:serve()
local ln, err = socketUtil.listen(self.ip, self.port)
if not ln then
return false, err
end
self.ln = ln
while self.ln do
local conn, err = ln:accept()
if conn then
levent.spawn(self.handle_conn, self, conn)
end
if err then
print("accept error:", err)
end
end
return true
end
function server:close()
if self.ln then
local ln = self.ln
self.ln = nil
ln:close()
end
end
return server
|
local payload = 97
if settings.startup["bigger-cargo"].value then
payload = 197
end
data:extend(
{
-- entity
{
type = "logistic-robot",
name = "logistic-robot-nuclear",
icon = "__KingsNuclearBots__/graphics/icons/logistic-robot-nuclear.png",
icon_size = 32,
flags = {"placeable-player", "player-creation", "placeable-off-grid", "not-on-map"},
minable = {hardness = 0.1, mining_time = 0.1, result = "logistic-robot-nuclear"},
resistances = { { type = "fire", percent = 85 } },
max_health = 500,
dying_explosion = "massive-explosion",
collision_box = {{0, 0}, {0, 0}},
selection_box = {{-0.5, -1.5}, {0.5, -0.5}},
max_payload_size = payload,
speed = 0.05,
transfer_distance = 0.5,
max_energy = "1.5MJ",
energy_per_tick = "0kJ",
speed_multiplier_when_out_of_energy = 0.2,
energy_per_move = "0kJ",
min_to_charge = 0.2,
max_to_charge = 0.95,
idle = {
filename = "__KingsNuclearBots__/graphics/entity/logistic-robot/logistic-robot-nuclear.png",
priority = "high",
line_length = 16,
width = 41,
height = 42,
frame_count = 1,
shift = {0.015625, -0.09375},
direction_count = 16,
y = 42
},
idle_with_cargo = {
filename = "__KingsNuclearBots__/graphics/entity/logistic-robot/logistic-robot-nuclear.png",
priority = "high",
line_length = 16,
width = 41,
height = 42,
frame_count = 1,
shift = {0.015625, -0.09375},
direction_count = 16
},
in_motion = {
filename = "__KingsNuclearBots__/graphics/entity/logistic-robot/logistic-robot-nuclear.png",
priority = "high",
line_length = 16,
width = 41,
height = 42,
frame_count = 1,
shift = {0.015625, -0.09375},
direction_count = 16,
y = 126
},
in_motion_with_cargo = {
filename = "__KingsNuclearBots__/graphics/entity/logistic-robot/logistic-robot-nuclear.png",
priority = "high",
line_length = 16,
width = 41,
height = 42,
frame_count = 1,
shift = {0.015625, -0.09375},
direction_count = 16,
y = 84
},
shadow_idle = {
filename = "__KingsNuclearBots__/graphics/entity/logistic-robot/logistic-robot-nuclear-shadow.png",
priority = "high",
line_length = 16,
width = 59,
height = 23,
frame_count = 1,
shift = {0.96875, 0.609375},
direction_count = 16,
y = 23
},
shadow_idle_with_cargo = {
filename = "__KingsNuclearBots__/graphics/entity/logistic-robot/logistic-robot-nuclear-shadow.png",
priority = "high",
line_length = 16,
width = 59,
height = 23,
frame_count = 1,
shift = {0.96875, 0.609375},
direction_count = 16
},
shadow_in_motion = {
filename = "__KingsNuclearBots__/graphics/entity/logistic-robot/logistic-robot-nuclear-shadow.png",
priority = "high",
line_length = 16,
width = 59,
height = 23,
frame_count = 1,
shift = {0.96875, 0.609375},
direction_count = 16,
y = 23
},
shadow_in_motion_with_cargo = {
filename = "__KingsNuclearBots__/graphics/entity/logistic-robot/logistic-robot-nuclear-shadow.png",
priority = "high",
line_length = 16,
width = 59,
height = 23,
frame_count = 1,
shift = {0.96875, 0.609375},
direction_count = 16
},
working_sound = data.raw["logistic-robot"]["logistic-robot"].working_sound,
cargo_centered = {0.0, 0.2},
},
-- recipe
{
type = "recipe",
name = "logistic-robot-nuclear",
enabled = false,
ingredients =
{
{"logistic-robot", 5},
{"nuclear-reactor", 1},
{"heat-exchanger", 4},
{"steam-turbine", 7},
{"heat-pipe", 25},
{"uranium-fuel-cell", 1500}
},
result = "logistic-robot-nuclear"
},
-- item
{
type = "item",
name = "logistic-robot-nuclear",
icon = "__KingsNuclearBots__/graphics/icons/logistic-robot-nuclear.png",
icon_size = 32,
subgroup = "logistic-network",
order = "a[robot]-b[logistic-robot]-c[nuclear]",
place_result = "logistic-robot-nuclear",
stack_size = 50
},
})
|
---
--- Generated by EmmyLua(https://github.com/EmmyLua)
--- Created by z15085.
--- DateTime: 2019/9/5 20:16
---
local config = require "conf_constant"
local mysqlUtil = require "mysql_factory"
--接受前端数据的对象
local args = nil
--获取前端的请求方式,并获取传递的参数
local request_method = ngx.var.request_method
--判断是 get 请求,还是 post 请求,并分别拿出相应的数据
if "GET" == request_method then
args = ngx.req.get_uri_args()
elseif "POST" == request_method then
ngx.req.read_body()
args = ngx.req.get_post_args()
--兼容请求使用 post 请求,但是传参以 get 方式造成的无法获取数据的bug
if (args == nil or args.data == null) then
args = ngx.req.get_uri_args()
end
end
--前端传递的id
local id = args.id
--组装sql语句
local sql = "select * from test_table where id = " .. id
--执行sql语句
local ret, res, sqlstate = mysqlUtil:query(sql, config)
--ngx.log(ngx.DEBUG, "ret--", ret)
--ngx.log(ngx.DEBUG, "sqlstate--", sqlstate)
--判断查询结果
if (ret and res ~= nil and #res > 0) then
--取出最新的值
local user = res[1]
--组装响应参数
local reVa = "id:" .. user.id .. ";</br>name:" .. user.name .. ";</br>age:" .. user.age
--响应前端
ngx.say(reVa)
else
ngx.say("This user isn't existed!")
end |
-- This file is subject to copyright - contact swampservers@gmail.com for more information.
function PPM_SetPonyCfg(ent, cfg)
ent.ponydata = cfg
-- invalidate caches
ent.ponymaterials = nil
end
function PPM_UpdateLocalPonyCfg(k, v)
local ent = LocalPlayer()
ent.ponydata[k] = v
ent.ponymaterials = nil
end
PPM_PONIES_NEARBY = {}
function PPM_PrePonyDraw(ent)
if not ent:IsPPMPony() then return end
local ply = ent:PonyPlayer() -- conversion shop/editor model and ragdoll
if not IsValid(ply) then return end
if not ply.UpdatedPony then
net.Start("PonyRequest")
net.WriteEntity(ply)
net.SendToServer()
ply.UpdatedPony = true
end
PPM_PONIES_NEARBY[ply] = true
for k, v in ipairs(ply.ponymaterials or {}) do
if k == 10 and ((ply.ponydata or {}).imgurcmark or "") ~= "" then
-- big TODO: make imgur materials return a single material, and update the texture in think hook, so we dont need to reapply them constantly!!!!
v = ImgurMaterial({
id = ply.ponydata.imgurcmark,
owner = ent,
pos = IsValid(ent) and ent:IsPlayer() and ent:GetPos(),
stretch = false,
shader = "VertexLitGeneric",
params = [[{["$translucent"]=1}]]
})
end
ent:SetSubMaterial(k - 1, "!" .. v:GetName())
end
-- Only applies to editor models; ragdolls are handled in hook below and players are handled serverside
if ent:EntIndex() == -1 then
PPM_SetBodyGroups(ent)
end
end
-- gets removed when the shop is present
hook.Add("PrePlayerDraw", "PPM_PrePlayerDraw", function(ply)
if not ply:Alive() then return true end
ply:SetSubMaterial()
PPM_PrePonyDraw(ply)
end)
-- alternate path so sps materials stack correctly
function SS_PPM_SetSubMaterials(ent)
hook.Remove("PrePlayerDraw", "PPM_PrePlayerDraw")
RP_PUSH("ponydraw")
PPM_PrePonyDraw(ent)
RP_POP()
end
local UNIQUEVALUE = tostring(os.time())
-- draw textures
hook.Add("PreDrawHUD", "PPM_PreDrawHUD", function()
for ply, _ in pairs(PPM_PONIES_NEARBY) do
if ply.ponydata and not ply.ponymaterials then
ply.ponydata_tex = {} -- todo remove this
ply.ponymaterials = {}
for _, v in ipairs(PPM_player_mat) do
table.insert(ply.ponymaterials, PPM_CLONE_MATERIAL(v))
end
for k, v in pairs(PPM.rendertargettasks or {}) do
PPM.currt_ent = ply
PPM.currt_ponydata = ply.ponydata
PPM.currt_success = false
ply.ponydata_tex[k] = PPM_CreateTexture(UNIQUEVALUE .. tostring(ply:EntIndex()) .. k, v)
-- ply.ponydata_tex[k .. "_hash"] = v.hash(pony) --remove
ply.ponydata_tex[k .. "_draw"] = PPM.currt_success -- remove
-- if PPM.currt_success then
v.render(ply, ply.ponymaterials)
-- print(k)
-- mats = PPM_CLONE_MATERIALS(mats)
-- for _,v in ipairs(mats) do
-- ply.ponymaterials[v[2]] = v[1]
-- end
-- ent.ponydata_tex[k .. "_mat"] =
-- end
-- print(ent, k)
-- once per frame
-- return
-- end
end
end
end
PPM_PONIES_NEARBY = {}
end)
PPM_NEXT_CLONE_MAT = PPM_NEXT_CLONE_MAT or 0
function PPM_CLONE_MATERIAL(mat)
PPM_NEXT_CLONE_MAT = PPM_NEXT_CLONE_MAT + 1
local kvs = mat:GetKeyValues()
local junk = {}
for i, v in ipairs({"$flags", "$flags2", "$flags_defined", "$flags_defined2"}) do
junk[v] = kvs[v]
kvs[v] = nil
end
for k, v in pairs(kvs) do
if type(v) == "ITexture" then
kvs[k] = v:GetName()
end
if type(v) == "Vector" then
kvs[k] = "[" .. tostring(v) .. "]"
end
if type(v) == "VMatrix" then
assert(v:IsIdentity())
kvs[k] = nil
end
if type(v) == "number" then
kvs[k] = tostring(v)
end
if kvs[k] ~= nil then
assert(type(kvs[k]) == "string")
end
end
-- add os time because of materials getting saved when you rejoin
local clone = CreateMaterial("PPMCLONE" .. tostring(os.time()) .. "/" .. tostring(PPM_NEXT_CLONE_MAT), mat:GetShader(), kvs)
for k, v in pairs(junk) do
clone:SetInt(k, v)
end
return clone
end
concommand.Add("ppm_refresh", function(ply, cmd, args)
for _, ent in ipairs(player.GetAll()) do
ent.UpdatedPony = nil
ent.ponydata = nil
ent.ponymaterials = nil
end
end)
-- if this causes conflicts maybe just set the materials one time
function PPM_RagdollRender(self)
PPM_PrePonyDraw(self)
self:DrawModel()
end
hook.Add("CreateClientsideRagdoll", "PPM_CreateClientsideRagdoll", function(entity, ragdoll)
-- IsPPMPony check added because of outfitter issue
if entity:IsPlayer() and entity:IsPPMPony() then
ragdoll.RagdollSourcePlayer = entity
PPM_SetBodyGroups(ragdoll)
ragdoll.RenderOverride = PPM_RagdollRender
end
end) |
local Player = FindMetaTable("Player")
function Player:UseItem(Item)
local ItemTable = ItemTable(Item)
if ItemTable and ItemTable.Use and self:HasItem(Item) then
ItemTable:Use(self, ItemTable)
return true
end
return false
end
concommand.Add("UD_UseItem", function(ply, command, args)
ply:UseItem(tostring(args[1]))
end)
function Player:DropItem(Item, Amount)
Amount = math.floor(Amount)
local ItemTable = ItemTable(Item)
if self:HasItem(Item, Amount) and ItemTable.Dropable then
local Position = self:EyePos() + (self:GetAimVector() * 25)
local trace = self:GetEyeTrace()
if trace.HitPos:Distance(self:GetPos()) < 80 then Position = trace.HitPos end
local DropedItem = CreateWorldItem(Item, Amount, Position)
self:AddItem(Item, -Amount)
return true
end
return false
end
concommand.Add("UD_DropItem", function(ply, command, args)
local amount = math.Clamp(tonumber(args[2]), 1, ply.Data.Inventory[args[1]]) or 1
ply:DropItem(args[1], amount)
end)
function Player:GiveItem(Item, Amount, Target)
Amount = math.floor(Amount)
local ItemTable = ItemTable(Item)
if not ItemTable.Giveable then return false end
Target:TransferItem(self, Item, Amount)
Target:CreateNotification(self:Nick() .. " Gave you " .. tostring(math.Round(Amount)) .. " " .. ItemTable.PrintName)
end
concommand.Add("UD_GiveItem", function(ply, command, args) ply:GiveItem(args[1], args[2], player.GetByID(tonumber(args[3]))) end)
|
workspace "MiniEngine"
architecture "x86_64"
startproject "Editor"
configurations { "Debug", "Release", "Production" }
flags { "MultiProcessorCompile" }
outputdir = "%{cfg.buildcfg}-%{cfg.system}-%{cfg.architecture}"
group "Dependencies"
include "../Engine/External/GLFW"
include "../Engine/External/Glad"
include "../Engine/External/imgui"
group ""
group "Engine"
include "../Engine"
group ""
group "Editor"
include "../Editor"
group ""
|
return {'barentszzee','bargoens','bar','bara','barak','barakkenkamp','barbaar','barbaars','barbaarsheid','barbarij','barbarisme','barbecue','barbecues','barbecuesaus','barbecueen','barbediende','barbeel','barbeheerder','barbershop','barbertje','barbiepop','barbier','barbieren','barbiersvak','barbierswinkel','barbierszaak','barbituraat','barcarolle','barcode','barcodeapparatuur','barcodelezer','barcodescanner','bard','bardenzang','bareel','bareelwachter','barema','baren','barensnood','barenswee','barensweeen','baret','baretembleem','barette','baretten','barheid','bariet','baring','bariton','baritonsaxofonist','baritonsaxofoon','baritonzanger','barium','bariumpap','bariumsulfaat','barjuffrouw','bark','barkas','barkeeper','barkeepster','barkelner','barkruk','barman','barmeid','barmeisje','barmeubel','barmhartig','barmhartigheid','barnen','barnevelder','barnsteen','barnstenen','barnumreclame','barograaf','barok','barokcello','barokgebouwen','barokhobo','barokkunst','barokmuziek','barokopera','barokorkest','barokschilder','barokstijl','baroktijd','barokviool','barometer','barometerstand','barometrisch','baron','barones','baronesse','baronie','baronnentitel','baroscoop','barouchet','barpersoneel','barpianist','barracuda','barrage','barre','barrel','barrels','barreren','barrevoeter','barrevoets','barricade','barricadegevecht','barricaderen','barring','barriere','bars','barsheid','barst','barsten','barstens','barstensvol','bartender','barvrouw','barzoi','baroktuin','barokconcert','bartholomeusnacht','barbarakruid','barbershopkoor','baribal','barnumachtig','barragepartijtje','barre','barreakkoord','bardienst','barrierewerking','barbarendom','bardame','barbezetting','barblad','barcommissie','bareigenaar','bargedeelte','baritonsax','baritonstem','barjongen','barkast','barokkerk','barokperiode','barrageduel','barrierefunctie','barruimte','barstwond','baringskanaal','barmedewerker','barrieretraktaat','baragansteppe','barbadaan','barbadaans','barbadiaan','barbadiaans','barbados','barbara','barenaar','barendrecht','barendrechter','barendrechts','barentszburg','barentszeiland','barneveld','barnevelder','barnevelds','bart','bartina','bartolomeus','baran','barbera','barend','baris','barre','barrie','barry','bartel','bartha','bartholomeus','bartje','baruch','barth','bartelds','barendregt','barendse','barelds','barnhoorn','bartelink','barten','bartelen','bargeman','bartman','barnard','barto','barel','barents','barendsen','barentsen','barhorst','barink','barkmeijer','barmentlo','barmentloo','barreveld','barkel','bareman','barkey','bartelings','bartlema','barlag','bartelsman','barkema','barron','barning','barack','barker','barnes','barroso','bargoense','barakken','barbaarse','barbaarser','barbaarsheden','barbaarst','barbaren','barbarismen','barbelen','barbiers','barbiesjes','barcarolles','barcodes','barcodescanners','barden','barder','bare','bareeltje','bareelwachters','barelen','baremas','barende','barenden','baretemblemen','baringen','baritons','barkassen','barken','barkrukken','barmannen','barmeiden','barmhartige','barmhartiger','barmhartigere','barmhartigheden','barmhartigste','barografen','barokcomponisten','barokke','barokschilders','barokst','barometers','barometerstanden','barometrische','baronessen','baronieen','baronnen','barons','barrages','barrevoeters','barricadeer','barricadeerde','barricadeerden','barricadeert','barricadegevechten','barricaden','barricades','barrieres','barse','barser','barstende','barstte','barstten','barriererif','barbecuede','barbecuet','barbediendes','barbiepoppen','barbituraten','barend','baretje','baritonzangers','barkeepers','barkelners','barmeisjes','barmeubelen','barmeubels','barnevelders','barokorkesten','baroscopen','barouchetten','barreerde','barretje','barretjes','barstend','bartenders','baritonsaxofoons','barbadaanse','barbadiaanse','barstensvolle','barbedienden','barbertjes','barbershops','barracudas','baras','barbershopkoren','barettes','barettetje','baribals','baritonsaxofonisten','barkeepsters','barnumachtige','barokconcerten','barragepartijtjes','barrieretje','barreakkoorden','barres','barzois','barneveldse','barans','barbaras','barberas','baris','barres','barries','barrys','barts','barthas','bartholomeus','bartjes','baruchs','barmedewerkers','bardames','baretjes','barakkenkampen','barokoperas','barcodelezers','barrageduels','baronnetjes','barvrouwen','baronnetje','barokviolen','barchemse','barendrechtse','barstje','barstjes'} |
require "fmt"
loadmod "link"
room {
nam = 'main';
decor = [[{$link|http://instead.syscall.ru}^^
{$link|http://syscall.ru}]];
} |
--[[
====================
Overview
====================
Long Term Timer Manager is a library for setting timers that
last longer than a single play session. They can be used for
things like crops, that take hours to grow, or bonuses that
show up once per day, or similar!
Timers are created and managed using functions like StartPlayerTimer,
CancelPlayerTimer, GetTimerDetails, etc. They are alwyas associated
with a specific player, and live in that player's storage. (So you
will need to have "Enable Player Storage" checked in your game's
Game Settings object, for them to work!)
====================
How to use
====================
Long Term Timers is a library that is intended to be used via
Lua's `require` function. For scripts that need it, they should
include a custom property asset reference, pointing to
`_LongTermTimerManager`, and some code like this:
local prop_LongTermTimerManager = script:GetCustomProperty("_LongTermTimerManager")
local LTT = require(prop_LongTermTimerManager)
Once this is done, all of the functions can be accessed through the LTT object.
In general, you will want to include event handlers for when players join or leave
the game, to load/save any timers associated with them:
function OnPlayerJoined(player)
LTT.LoadFromPlayerData(player)
end
function OnPlayerLeft(player)
LTT.SaveAsPlayerData(player)
end
Once that is done, you can set and respond to timers fairly easily -
Creating a new timer is as easy as calling:
LTT.StartPlayerTimer(player, timerName, timerDuration)
You can respond to timers by connecting to the LTT.timerFiredEvent
event:
function OnTimerFired(player, id, start, duration)
if id == myTimerName then
-- do stuff
end
end
LTT.timerFiredEvent:Connect(OnTimerFired)
====================
Library Contents:
====================
timerFiredEvent
----------------------------
This is the main way you will receive events when timers complete. It
behaves identically to the Event class in the rest of the API. (So you can
Connect functions to it, etc.)
Functions connected to it will be called with the following arguments:
player: The player associated with the timer that completed.
id: The id of the timer that completed.
start: The time (via os.time) when the timer started.
duration: The duration of the timer, in seconds.
LoadFromPlayerData(player)
----------------------------
Loads timer data from the player storage directly. It will be stored
in a field named "lte_LTTimerTable" on the player storage table.
This is usually paired with SaveAsPlayerData()
Any timers that have expired while the player was not logged in will
fire when data is loaded.
SaveAsPlayerData(player)
----------------------------
Saves the timer data associated with a given player into their player
storage table, in a field named "lte_LTTimerTable".
Note that this function will preserve existing data in the table, so if
your game needs to save its own data into player storage, you can call
this function after you've saved your own data, and it should "just work."
ImportFromTable(player, dataTable)
----------------------------
Loads the data for a player's long term timers from a table.
(This is usually used if you are managing your own storage
and have saved the data as a table via ExportAsTable)
Any timers that have expired while the player was not logged in will
fire when data is loaded.
ExportAsTable(player)
----------------------------
Exports the timer data for a player as a table. This is
intended for use if you want to manage your own data
storage, and just want a raw table to save somewhere.
StartPlayerTimer(player, timerId, duration)
----------------------------
Creates a new timer for the given player. The arguments are the
player to create the timer for, the duration of the timer, and the
timerId.
timerId is a string that is used to identify the timer.
Note that if there is already an timer with the given timerId, it will be
overwritten.
GetTimerDetails(player, timerId)
----------------------------
Returns a table containing details about a given event for a player.
If the event ID does not match any current events, then nil is returned.
Otherwise, the table has the following data:
start: os.time when the event was created.
duration: duration in seconds for the event.
Remaining(): a function that returns the number of seconds remaining until the timer fires.
GetAllTimerDetails(player)
----------------------------
Returns a table, where the keys are the timerIds of every timer for the player,
and the values are tables such as are returned from GetTimerDetails()
CancelPlayerTimer(player, timerId)
----------------------------
Canceles a timer. It will not fire. It's just gone.
CancelAllPlayerTimers(player)
----------------------------
Cancels all timers on a given player.
]]
|
local LuaCall = require 'Common/LuaCall'
local M = {}
local CSM = {}
local RegUI = require('UI/Reg/RegUI')
function CreateSuccess(name)
local ui = RegUI.UI[name]
if ui == nil then
print('No RegUI : '.. name)
return nil, nil, nil, nil, nil
end
-- local init = LuaCall.RegisterVoid(ui.Init, ui);
-- local onCreated = LuaCall.RegisterOne(ui.OnCreated, ui);
-- local onEnable = LuaCall.RegisterOne(ui.OnEnable, ui);
-- local onDisable = LuaCall.RegisterVoid(ui.OnDisable, ui);
-- local onDestroy = LuaCall.RegisterVoid(ui.OnDestroy, ui);
local init = ui.Init
local onCreated = ui.OnCreated
local onEnable = ui.OnEnable
local onDisable = ui.OnDisable
local onDestroy = ui.OnDestroy
if ui.Init == nil then
print('ui.Init is nil')
end
if ui.OnCreated == nil then
print('ui.onCreated is nil')
end
return init, onCreated, onEnable, onDisable, onDestroy
end
function M.Init( ... )
CSM = CS.Younne.UIManager
print('M.2')
if CSM ~= nil then
print('CSM ~= nil')
else
print('CSM nil'..CSM)
end
CSM.Init(CreateSuccess)
print('M.3')
end
function M.OpenUIForLua(name)
CSM.OpenUIForLua(name)
end
M.Init()
return M |
object_intangible_pet_gcw_atst_familiar_pcd = object_intangible_pet_shared_gcw_atst_familiar_pcd:new {
}
ObjectTemplates:addTemplate(object_intangible_pet_gcw_atst_familiar_pcd, "object/intangible/pet/gcw_atst_familiar_pcd.iff")
|
object_tangible_veteran_reward_duel_recording_terminal = object_tangible_veteran_reward_shared_duel_recording_terminal:new {
}
ObjectTemplates:addTemplate(object_tangible_veteran_reward_duel_recording_terminal, "object/tangible/veteran_reward/duel_recording_terminal.iff")
|
local function hsvToRgb(h, s, v)
local r, g, b
local i = math.floor(h * 6);
local f = h * 6 - i;
local p = v * (1 - s);
local q = v * (1 - f * s);
local t = v * (1 - (1 - f) * s);
i = i % 6
if i == 0 then r, g, b = v, t, p
elseif i == 1 then r, g, b = q, v, p
elseif i == 2 then r, g, b = p, v, t
elseif i == 3 then r, g, b = p, q, v
elseif i == 4 then r, g, b = t, p, v
elseif i == 5 then r, g, b = v, p, q
end
return r * 255, g * 255, b * 255
end
function setup()
displayMode(FULLSCREEN)
parameter.boolean("UseGravity",false)
parameter.number("GravityScale",0,100,30)
parameter.boolean("DrawSize",false)
parameter.boolean("ColorSize",false)
parameter.boolean("DrawMaxMin",false)
font("HelveticaNeue-Bold")
shapes = {}
min,max = 10,40
for i = 1, 40 do
shapes[i] = {
x = math.random(WIDTH),
y = math.random(HEIGHT),
s = math.random(min,max)
}
end
end
function touched(touch)
if touch.state == MOVING then
for k,v in ipairs(shapes) do
v.x = v.x+(v.s/max*touch.deltaX)
v.y = v.y+(v.s/max*touch.deltaY)
if v.x+v.s<0 then
v.x = WIDTH+v.s
v.y = math.random(HEIGHT)
elseif v.x-v.s>WIDTH then
v.x = -v.s
v.y = math.random(HEIGHT)
end
if v.y+v.s<0 then
v.x = math.random(WIDTH)
v.y = HEIGHT+v.s
elseif v.y-v.s>HEIGHT then
v.x = math.random(WIDTH)
v.y = -v.s
end
end
end
if touch.tapCount > 1 then zoom = {x=touch.x,y=touch.y,t=ElapsedTime} end
end
function drawshape(x,y,s)
if ColorSize then
local frac = (s-min)/(max-min)
fill(hsvToRgb(frac,1,1))
else
fill(255)
end
ellipse(x,y,s)
if DrawSize then
fill(ColorSize and 255 or 0)
fontSize(s/2)
text(s,x,y)
end
if DrawMaxMin then
fill(255, 0, 0)
fontSize(s)
if s == max then
text("MAX",x,y+s)
elseif s == min then
text("MIN",x,y+s)
end
end
end
function zoomIn()
for k,v in ipairs(shapes) do
v.x = v.x+((v.x-zoom.x)/(max-v.s))*(0.5-(ElapsedTime-zoom.t))
v.y = v.y+((v.y-zoom.y)/(max-v.s))*(0.5-(ElapsedTime-zoom.t))
end
if ElapsedTime-zoom.t > 0.5 then zoom = nil end
end
function draw()
background(0)
if zoom then zoomIn() end
for k,v in ipairs(shapes) do
if UseGravity then
drawshape(v.x+Gravity.x*v.s*GravityScale,v.y+Gravity.y*v.s*GravityScale,v.s)
else
drawshape(v.x,v.y,v.s)
end
end
end
|
require "util"
pprint = require "pl.pretty"
debug = false
function strip(str)
return string.format( "%s", str:match( "^%s*(.-)%s*$" ) )
end
function replace_char(pos, str, r)
return ("%s%s%s"):format(str:sub(1,pos-1), r, str:sub(pos+1))
end
function splitLineToGroupArray(line)
local retVal = {}
local i = 1
for group in string.gmatch(line, "[^.]+") do
retVal[i] = group
i = i + 1
end
return retVal
end
function tableSize(table)
local size = 0
for i, v in pairs(table) do
size = size + 1
end
return size
end
function splitLine(str)
local openArr = 0
local openString = false
local beginLine = true
local keyGroup = false
local delNum = 1
for i = 1, #str do
local char = string.sub(str, i, i)
if char == '"' and string.sub(str, i-1, i-1) ~= '\\' then
openString = not openString
end
if keyGroup and (char == ' ' or char == '\t') then
keyGroup = false
end
if char == '#' and not openString and not keyGroup then
local j = i
while string.sub(str, j, j) ~= '\n' do
str = replace_char(j, str, ' ')
j = j + 1
end
end
if char == '[' and not openString and not keyGroup then
if beginLine then
keyGroup = true
else
openArr = openArr + 1
end
end
if char == ']' and not openString and not keyGroup then
if keyGroup then
keyGroup = false
else
openArr = openArr - 1
end
end
if char == '\n' then
if openString then error("Unbalanced Quotes") end
if openArr ~= 0 then
str = replace_char(i, str, ' ')
else
beginLine = true
end
elseif beginLine and char ~= ' ' and char ~= '\t' then
beginLine = false
keyGroup = true
else
end
end -- end of for loop
return str
end
function splitAssignment(str)
local retVal = {}
local i = 1
for group in string.gmatch(str, "[^=]+") do
retVal[i] = group
i = i + 1
end
return retVal
end
function load(str)
--[[--
Load a TOML string into Lua object (deserialization)
@Parameter: str
The str which is parsed in as TOML
@Returns: A table of nested components of TOML string
--]]--
local implicitGroups = {}
local retVal = {}
local currentLevel = retVal
str = splitLine(str)
for line in string.gmatch(str, "[^\n]+") do
line = strip(line)
if string.sub(line, 1, 1) == '[' then
line = string.sub(line, 2, #line-1) -- key group name
currentLevel = retVal
groups = splitLineToGroupArray(line)
for i, group in ipairs(groups) do
if group == "" then error("Can't have keygroup with empty name") end
if currentLevel[group] ~= nil then
if i == tableSize(groups) then
if implicitGroups[group] ~= nil then
implicitGroups[group] = nil
else
error("Group existed")
end
end
else
if i ~= tableSize(groups) then
implicitGroups[group] = true
end
currentLevel[group] = {}
end
currentLevel = currentLevel[group]
end -- end of for loop
elseif line:match("=") ~= nil then
assignment = splitAssignment(line)
variable = strip(assignment[1])
value = strip(assignment[2])
loadedVal = load_value(value)
value = loadedVal["value"]
if currentLevel[variable] ~= nil then
error("Duplicated key")
else
currentLevel[variable] = value
end
end
end
return retVal
end
function load_value(v)
-- boolean
if v == "true" then
return { value=true, type="boolean" }
-- boolean
elseif v == "false" then
return { value=false, type="boolean" }
-- string, handle simple string for now
elseif string.sub(v, 1, 1) == '"' then
local lengthV = string.len(v)
local str = string.sub(v, 2, lengthV-1)
return { value=str, type="string" }
-- array
elseif string.sub(v, 1, 1) == '[' then
return { value=load_array(v), type="table" }
-- datetime, handle as string for now
elseif string.len(v) == 20 and string.sub(v, 20, 20) == 'Z' then
local lengthV = string.len(v)
local str = string.sub(v, 1, lengthV-1)
return { value=str, type="string" }
-- number
else
local negative = false
if string.sub(v, 1, 1) == '-' then
negative = true
local lengthV = string.len(v)
v = string.sub(v, 2, lengthV)
end
v = tonumber(v)
if negative then v = 0 - v end
return { value=v, type="number" }
end
end
function load_array(a)
local retVal = {}
a = string.format( "%s", a:match( "^%s*(.-)%s*$" ) )
a = string.sub(a, 2, #a - 1)
local newArr = {}
local openArr = 0
local j = 1
local index = 1
for i = 1, #a do
local char = string.sub(a, i, i)
if char == "[" then
openArr = openArr + 1
elseif char == "]" then
openArr = openArr - 1
elseif char == "," and openArr == 0 then
local subStr = string.sub(a, j, i-1)
subStr = string.format( "%s", subStr:match( "^%s*(.-)%s*$" ) )
newArr[index] = subStr
j = i + 1
index = index + 1
end
end
local subStr = string.sub(a, j, #a)
subStr = string.format( "%s", subStr:match( "^%s*(.-)%s*$" ) )
newArr[index] = subStr
local aType = nil
local index = 1
for i, v in ipairs(newArr) do
if v ~= '' then
local loadedVal = load_value(v)
local nVal = loadedVal["value"]
local nType = loadedVal["type"]
if aType then
if aType ~= nType then
error("Not homogeneous array")
end
else
aType = nType
end
retVal[index] = nVal
index = index + 1
end
end
return retVal
end
function dump(obj)
--[[--
Dump Lua object into TOML string (serialization)
@Parameter: obj
The Lua table
@Returns: A TOML string
--]]--
local addToSections
local retVal = ""
local dumpedSection = dump_section(obj)
local addToRetVal = dumpedSection["retStr"]
local sections = dumpedSection["retDict"]
retVal = retVal .. addToRetVal
while tableSize(sections) ~= 0 do
local newSections = {}
for section, value in pairs(sections) do
dumpedSection = dump_section(sections[section])
addToRetVal = dumpedSection["retStr"]
addToSections = dumpedSection["retDict"]
if addToRetVal ~= nil then
retVal = retVal .. "[" .. section .. "]\n"
retVal = retVal .. addToRetVal
end
for s, value in pairs(addToSections) do
newSections[section .. "." .. s] = addToSections[s]
end
end
sections = newSections
end
return retVal
end
function dump_section(obj)
local retStr = ""
local retDict = {}
for i, section in pairs(obj) do
if type(obj[i]) ~= "table" then
retStr = retStr .. i .. " = "
retStr = retStr .. dump_value(obj[i]) .. '\n'
else
retDict[i] = obj[i]
end
end
return { retStr=retStr, retDict=retDict }
end
function dump_value(v)
if type(v) == "string" then
local retStr = '"' .. v .. '"'
return retStr
elseif type(v) == "boolean" then
return tostring(v)
else
return v
end
end
|
--[[
General Lua Libraries for Lua 5.1, 5.2 & 5.3
Copyright (C) 2002-2018 stdlib authors
]]
--[[--
Additions to the core io module.
The module table returned by `std.io` also contains all of the entries from
the core `io` module table. An hygienic way to import this module, then,
is simply to override core `io` locally:
local io = require 'std.io'
@corelibrary std.io
]]
local _ = require 'std._base'
local argscheck = _.typecheck and _.typecheck.argscheck
local catfile = _.io.catfile
local leaves = _.tree.leaves
local split = _.string.split
_ = nil
local _ENV = require 'std.normalize' {
'io',
_G = _G, -- FIXME: don't use the host _G as an API!
concat = 'table.concat',
dirsep = 'package.dirsep',
format = 'string.format',
gsub = 'string.gsub',
input = 'io.input',
insert = 'table.insert',
io_type = 'io.type',
merge = 'table.merge',
open = 'io.open',
output = 'io.output',
popen = 'io.popen',
stderr = 'io.stderr',
stdin = 'io.stdin',
write = 'io.write',
}
--[[ =============== ]]--
--[[ Implementation. ]]--
--[[ =============== ]]--
local M
local function input_handle(h)
if h == nil then
return input()
elseif type(h) == 'string' then
return open(h)
end
return h
end
local function slurp(file)
local h, err = input_handle(file)
if h == nil then
argerror('std.io.slurp', 1, err, 2)
end
if h then
local s = h:read('*a')
h:close()
return s
end
end
local function readlines(file)
local h, err = input_handle(file)
if h == nil then
argerror('std.io.readlines', 1, err, 2)
end
local l = {}
for line in h:lines() do
l[#l + 1] = line
end
h:close()
return l
end
local function writelines(h, ...)
if io_type(h) ~= 'file' then
write(h, '\n')
h = output()
end
for v in leaves(ipairs, {...}) do
h:write(v, '\n')
end
end
local function process_files(fn)
-- N.B. 'arg' below refers to the global array of command-line args
if len(arg) == 0 then
insert(arg, '-')
end
for i, v in ipairs(arg) do
if v == '-' then
input(stdin)
else
input(v)
end
fn(v, i)
end
end
local function warnfmt(msg, ...)
local prefix = ''
local prog = rawget(_G, 'prog') or {}
local opts = rawget(_G, 'opts') or {}
if prog.name then
prefix = prog.name .. ':'
if prog.line then
prefix = prefix .. str(prog.line) .. ':'
end
elseif prog.file then
prefix = prog.file .. ':'
if prog.line then
prefix = prefix .. str(prog.line) .. ':'
end
elseif opts.program then
prefix = opts.program .. ':'
if opts.line then
prefix = prefix .. str(opts.line) .. ':'
end
end
if #prefix > 0 then
prefix = prefix .. ' '
end
return prefix .. format(msg, ...)
end
local function warn(msg, ...)
writelines(stderr, warnfmt(msg, ...))
end
--[[ ================= ]]--
--[[ Public Interface. ]]--
--[[ ================= ]]--
local function X(decl, fn)
return argscheck and argscheck('std.io.' .. decl, fn) or fn
end
M = {
--- Diagnostic functions
-- @section diagnosticfuncs
--- Die with error.
-- This function uses the same rules to build a message prefix
-- as @{warn}.
-- @function die
-- @string msg format string
-- @param ... additional arguments to plug format string specifiers
-- @see warn
-- @usage
-- die('oh noes!(%s)', tostring(obj))
die = X('die(string, [any...])', function(...)
error(warnfmt(...), 0)
end),
--- Give warning with the name of program and file(if any).
-- If there is a global `prog` table, prefix the message with
-- `prog.name` or `prog.file`, and `prog.line` if any. Otherwise
-- if there is a global `opts` table, prefix the message with
-- `opts.program` and `opts.line` if any.
-- @function warn
-- @string msg format string
-- @param ... additional arguments to plug format string specifiers
-- @see die
-- @usage
-- local OptionParser = require 'std.optparse'
-- local parser = OptionParser 'eg 0\nUsage: eg\n'
-- _G.arg, _G.opts = parser:parse(_G.arg)
-- if not _G.opts.keep_going then
-- require 'std.io'.warn 'oh noes!'
-- end
warn = X('warn(string, [any...])', warn),
--- Path Functions
-- @section pathfuncs
--- Concatenate directory names into a path.
-- @function catdir
-- @string ... path components
-- @return path without trailing separator
-- @see catfile
-- @usage
-- dirpath = catdir('', 'absolute', 'directory')
catdir = X('catdir(string...)', function(...)
return(gsub(concat({...}, dirsep), '^$', dirsep))
end),
--- Concatenate one or more directories and a filename into a path.
-- @function catfile
-- @string ... path components
-- @treturn string path
-- @see catdir
-- @see splitdir
-- @usage
-- filepath = catfile('relative', 'path', 'filename')
catfile = X('catfile(string...)', catfile),
--- Remove the last dirsep delimited element from a path.
-- @function dirname
-- @string path file path
-- @treturn string a new path with the last dirsep and following
-- truncated
-- @usage
-- dir = dirname '/base/subdir/filename'
dirname = X('dirname(string)', function(path)
return(gsub(path, catfile('', '[^', ']*$'), ''))
end),
--- Split a directory path into components.
-- Empty components are retained: the root directory becomes `{'', ''}`.
-- @function splitdir
-- @param path path
-- @return list of path components
-- @see catdir
-- @usage
-- dir_components = splitdir(filepath)
splitdir = X('splitdir(string)', function(path)
return split(path, dirsep)
end),
--- IO Functions
-- @section iofuncs
--- Process files specified on the command-line.
-- Each filename is made the default input source with `io.input`, and
-- then the filename and argument number are passed to the callback
-- function. In list of filenames, `-` means `io.stdin`. If no
-- filenames were given, behave as if a single `-` was passed.
-- @todo Make the file list an argument to the function.
-- @function process_files
-- @tparam fileprocessor fn function called for each file argument
-- @usage
-- #! /usr/bin/env lua
-- -- minimal cat command
-- local io = require 'std.io'
-- io.process_files(function() io.write(io.slurp()) end)
process_files = X('process_files(function)', process_files),
--- Read a file or file handle into a list of lines.
-- The lines in the returned list are not `\n` terminated.
-- @function readlines
-- @tparam[opt=io.input()] file|string file file handle or name;
-- if file is a file handle, that file is closed after reading
-- @treturn list lines
-- @usage
-- list = readlines '/etc/passwd'
readlines = X('readlines(?file|string)', readlines),
--- Perform a shell command and return its output.
-- @function shell
-- @string c command
-- @treturn string output, or nil if error
-- @see os.execute
-- @usage
-- users = shell [[cat /etc/passwd | awk -F: '{print $1;}']]
shell = X('shell(string)', function(c) return slurp(popen(c)) end),
--- Slurp a file handle.
-- @function slurp
-- @tparam[opt=io.input()] file|string file file handle or name;
-- if file is a file handle, that file is closed after reading
-- @return contents of file or handle, or nil if error
-- @see process_files
-- @usage
-- contents = slurp(filename)
slurp = X('slurp(?file|string)', slurp),
--- Write values adding a newline after each.
-- @function writelines
-- @tparam[opt=io.output()] file h open writable file handle;
-- the file is **not** closed after writing
-- @tparam string|number ... values to write(as for write)
-- @usage
-- writelines(io.stdout, 'first line', 'next line')
writelines = X('writelines(?file|string|number, [string|number...])', writelines),
}
return merge(io, M)
--- Types
-- @section Types
--- Signature of @{process_files} callback function.
-- @function fileprocessor
-- @string filename filename
-- @int i argument number of *filename*
-- @usage
-- local fileprocessor = function(filename, i)
-- io.write(tostring(i) .. ':\n===\n' .. io.slurp(filename) .. '\n')
-- end
-- io.process_files(fileprocessor)
|
-- require'code_runner'.setup({})
-- vim.api.nvim_set_keymap('n', '<leader>r', ':RunCode<CR>', { noremap = true, silent = false })
print('hello')
|
local hl7=Class { }
hl7.__name='HL7 Message Object'
hl7._type='HL7'
function hl7:__init(hl7String)
self._originalData=hl7String and hl7String or DEFAULT_HL7_MESSAGE
self._fieldSeparator =self._originalData:sub(4,4)
self._componentSeparator =self._originalData:sub(5,5)
self._repetitionSeparator =self._originalData:sub(6,6)
self._escapeCharacter =self._originalData:sub(7,7)
self._subComponentSeparator=self._originalData:sub(8,8)
self._segmentSeparator =self._originalData:sub(#self._originalData,#self._originalData)
self._data={}
local segs=self._originalData:split(self._segmentSeparator)
for i=1,#segs do
if segs[i] and segs[i]~='' then
local seg=HL7Segment:new(
segs[i],
self._fieldSeparator,
self._componentSeparator,
self._repetitionSeparator,
self._escapeCharacter,
self._subComponentSeparator,
self._segmentSeparator
)
table.insert(self._data, seg)
end
end
end
function hl7:__tostring()
local s=''
local data=self._data
for i=1,#data do
s=s .. tostring(data[i]) .. self._segmentSeparator
end
return s
end
function hl7:getData(segment, field, component, repetition, subcomponent)
local data=self._data
for i=1,#data do
if data[i]._type==segment then
return data[i]:getData(field, component, repetition, subcomponent)
end
end
return nil
end
function hl7:setData(data, segment, field, component, repetition, subcomponent)
local d=self._data
if segment=='MSH' then
if tostring(field)=='1' then
self._fieldSeparator=data
for i=1,#d do d[i]:setFieldSeparator(data, field, component, repetition, subcomponent) end
return true
elseif tostring(field)=='2' and #data>3 then
self:setMSH2Chars(data)
for i=1,#d do d[i]:setMSH2Chars(data) end
return true
end
end
for i=1,#d do
if d[i]._type==segment then
return d[i]:setData(data, field, component, repetition, subcomponent)
end
end
local seg=HL7Segment:new(
segment .. self._fieldSeparator,
self._fieldSeparator,
self._componentSeparator,
self._repetitionSeparator,
self._escapeCharacter,
self._subComponentSeparator,
self._segmentSeparator
)
seg:setData(data, field, component, repetition, subcomponent)
table.insert(self._data, seg)
return true
end
function hl7:addSegment(segment)
local seg=HL7Segment:new(
segment .. self._fieldSeparator,
self._fieldSeparator,
self._componentSeparator,
self._repetitionSeparator,
self._escapeCharacter,
self._subComponentSeparator,
self._segmentSeparator
)
table.insert(self._data, seg)
return seg
end
function hl7._segments(data, n)
local self =data[1]
local segName=data[2]
local segs=self._data
while segs[n+1] do
n=n+1
if not segName or segs[n]._type==segName then
return n, segs[n]
end
end
end
function hl7:segments(segName)
return self._segments, {self, segName}, 0
end
function hl7:setFieldSeparator(s)
self._fieldSeparator=s
for _,seg in self:segments() do
seg:setFieldSeparator(s)
end
end
function hl7:setMSH2Chars(s)
self._componentSeparator =s:sub(1,1)
self._repetitionSeparator =s:sub(2,2)
self._escapeCharacter =s:sub(3,3)
self._subComponentSeparator=s:sub(4,4)
for _,seg in self:segments() do
seg:setMSH2Chars(s)
end
end
function hl7:unbatch()
local t={}
local msg
for _,k in self:segments() do
local segType=k._type
if segType == 'MSH' then
if msg ~= '' then
table.insert(t, msg)
end
msg=''
end
if not segType:match('[B|F][H|T]S') then
msg=msg .. tostring(k) .. self._segmentSeparator
end
end
table.insert(t, msg)
return t
end
return hl7
|
--- lifelines.lua © Dirk Laurie 2017 MIT License like that of Lua 5.3
-- LifeLines functions on GEDCOM objects.
-- See 'gedcom.lua' for the documentation of GEDCOM objects. This module
-- extends functionality by adding methods to the GEDCOM table and
-- defining EVENT, BIRT, CHR, DEAT, BURI, MARR method tables.
-- The documentation of the LifeLines Programming System and Report
-- generator remains largely valid for the implemented functions, except
-- that iterators follow Lua syntax: see comments. Note that Lua does
-- not allow expressions to be written to output automatically.
-- Many LifeLines functions have been moved into `gedcom.lua` because they
-- are so natural and so inevitable that writing code without them would be
-- painful. If you see its name in the list but not its code below, it is
-- already defined the moment that 'gedcom' has been required.
-- GEDCOM functions: fam firstfam firstindi forfam forindi indi lastfam
-- lastindi to_gedcom write
-- These all require object-oriented calls with an object constructed
-- by gedcom.read(FILENAME), e.g. `ged:fam"F1". Doing so, rather than
-- making the functions global, allows the LifeLines module to support
-- multiple GEDCOM files.
-- INDI functions: birth burial death families father female givens male
-- mother name nfamilies nspouses parents pn sex spousein spouses
-- surname title
-- FAM functions: children firstchild husband lastchild marriage nchildren
-- spouses wife
-- EVENT functions: date day month place year
-- LifeLines features that are adequately and sometimes better served in Lua
-- are not implemented, and there is no intention ever to do so. These
-- include e.g. program logic, string formatting and abstract (i.e. not
-- tied to GEDCOM ideas) data structures.
-- cache some routines as upvalues
local tremove, tunpack, tconcat, tsort =
table.remove, table.unpack, table.concat, table.sort
local append = table.insert
local Warning, Error = false, true
--- nonblank(s) is s if s is a non-blank string, otherwise nil
local function nonblank(s)
if type(s)=='string' and s:match"%S" then return s end
return nil
end
--- don't change the line below unless you understand the difference
--- between Lua 5.2 and Lua 5.3 'requre' and 'package'
local gedcom = require "gedcom" or require "gedcom.gedcom"
local meta = gedcom.meta
local GEDCOM, RECORD =
meta.GEDCOM, meta.RECORD
local Message = gedcom.util.Message
--- Tag-specific method tables
local INDI = meta.INDI
local FAM = meta.FAM
local DATE = meta.DATE
local NAME = meta.NAME
local EVENT = {}
for s in ("EVENT,BIRT,CHR,DEAT,BURI,MARR,DIV"):gmatch"%u+" do
meta[s] = EVENT
end
local key_pattern = '^@(.+)@$'
-- GEDCOM functions
--- for indi,k in gedcom:forindi() do
GEDCOM.forindi = function(gedcom)
local INDI = gedcom._INDI
local k=0
return function()
k=k+1
local indi = INDI[k]
if indi then return indi,k end
end
end
--- for fam,k in gedcom:forfam() do
GEDCOM.forfam = function(gedcom)
local FAM = gedcom._FAM
local k=0
return function()
k=k+1
local fam = FAM[k]
if fam then return fam,k end
end
end
GEDCOM.firstindi = function(gedcom)
return gedcom._INDI[1]
end
GEDCOM.lastindi = function(gedcom)
return gedcom._INDI[#gedcom._INDI]
end
GEDCOM.firstfam = function(gedcom)
return gedcom._FAM[1]
end
GEDCOM.lastfam = function(gedcom)
return gedcom._FAM[#gedcom._FAM]
end
-- Person functions
-- will not be implemented: key, soundex, inode, root
-- not implemented: fullname, trimname, nextsib, prevsib, nextindi, previndi
-- to be implemented: mothers, fathers, Parents
-- implemented as GEDCOM functions: indi forindi firstindi lastindi
-- implemented but not in lifelines: spousein
INDI.givens = function(indi)
return indi.NAME.data:match "^[^%/]*"
end
INDI.birth = function(indi)
return indi.BIRT
end
INDI.death = function(indi)
return indi.DEAT
end
INDI.burial = function(indi)
return indi.BURI
end
do
local pronoun = {M={"He","he","His","his","him"},
F={"She","she","Her","her","her"}}
INDI.pn = function(indi,typ)
return pronoun[indi:sex()][typ]
end
end
INDI.title = function(indi)
return indi.TITL.data
end
--- for spouse,family,k in indi:spouses() do
INDI.spouses = function(indi)
local fams = indi:families()
local n=0
return function()
local family, spouse
repeat -- it is possible for a family to have no spouse!
family, spouse = fams()
until spouse or not family
n=n+1
if spouse then return spouse, family, n end
end
end
INDI.nspouses = function(indi)
local n=0
for _ in indi:spouses() do
n=n+1
end
return n
end
INDI.nfamilies = function(indi)
local n=0
for _ in indi:families() do
n=n+1
end
return n
end
-- Family functions
-- will not be inmplemented: key fnode root
-- not implemented: nextfam prevfam
-- implemented as GEDCOM functions: fam forfam
FAM.marriage = function(fam)
return fam.MARR
end
FAM.nchildren = function(fam)
local n=0
for _ in fam:children() do
n=n+1
end
return n
end
FAM.firstchild = function(fam)
return (fam:children()())
end
FAM.lastchild = function(fam)
local child
for ch in fam:children() do child=ch end
return child
end
--- for spouse,k in fam:spouses() do
FAM.spouses = function(fam)
local k=0
return function()
repeat
k=k+1
local spouse=fam[k]
until not spouse or spouse.tag=='HUSB' or spouse.tag=='WIFE'
return fam.prev:indi(spouse.data),spouse and k
end
end
-- Event functions
EVENT.date = function(event)
return event.DATE and event.DATE.data
end
EVENT.place = function(event)
return event.PLAC and event.PLAC.data
end
EVENT.year = function(event)
return event.DATE and event.DATE:year()
end
EVENT.month = function(event)
return event.DATE and event.DATE:month()
end
EVENT.day = function(event)
return event.DATE and event.DATE:day()
end
EVENT.status = function(event)
return event.DATE and event.DATE:status()
end
-- Additional functions beyond what is in gedcom.lua. They can
-- be seen as applications of LifeLines.
FAM.check = function(fam,options)
local msg = fam.msg or Message()
options = options or {}
fam.msg = msg
if fam.HUSB then -- TODO
else msg:append("Family %s has no husband",fam.key)
end
if fam.WIFE then -- TODO
else msg:append("Family %s has no wife",fam.key)
end
if options.chronological then
local prev
for child in fam:children() do
if prev and child:birthyear() and prev:birthyear() then
local compare = prev.BIRT.DATE:compare(child.BIRT.DATE)
if compare==1 or compare==2 then
msg:append("In family %s child %s should come after child %s",
fam.key, prev.key, child.key)
end
end
prev = child
end
end
end
INDI.check = function(indi,options)
local msg = indi.msg or Message()
indi.msg = msg
local birthyear, deathyear = indi:birthyear(), indi:deathyear()
local date_error
if indi.BIRT then
if indi.DEAT then
local compare = DATE.compare(indi.BIRT.DATE,indi.DEAT.DATE)
if compare==1 or compare==2 then date_error = true end
end
else
date_error = true
end
if date_error then msg:append("%s %s ",indi.key,indi:refname()) end
end
GEDCOM.check = function(gedcom,options)
for indi in gedcom:forindi() do
indi:check(options)
end
for fam in gedcom:forfam() do
fam:check(options)
end
end
-- Superseded by Toolkit functions in gedcom.lua
--[[---- Subcollections
-- If you make a new collection of individuals selected from a larger
-- collection, the new GEDCOM might lack some families referred to.
-- If you included those families as you go along, some individuals
-- not included in the collection might be left over in those families.
--- gedcom:prune()
-- remove individuals not in the container from families
GEDCOM.prune = function(gedcom)
local schedule = {}
for fam in gedcom:forfam() do
for k=#fam,1,-1 do
if indi.tag=='INDI' and not gedcom[indi.key] then
tremove(fam,k)
end
end
end
end
--- gedcom:make_families()
-- Create families from individuals in the container
GEDCOM.make_families = function(gedcom)
for indi in gedcom:forindi() do
for tag in ("FAMC,FAMS"):gmatch"[^,]+" do
for field in indi:tagged(tag) do
fam = gedcom:new_family(field.data:match(key_pattern))
fam:include(indi,tag)
end
end
end
end
--- family:include(indi,tag)
-- Add an item for this individual, as HUSB, WIFE or CHIL depending on
-- whether 'tag' is FAMS or FAMC.
FAM.include = function(family,indi,tag)
local item
if tag=='FAMC' then
item=ITEM.new('CHIL',key_format:format(indi.key))
elseif tag=='FAMS' then
if indi:male() then
item=ITEM.new('HUSB',key_format:format(indi.key))
elseif indi:female() then
item=ITEM.new('WIFE',key_format:format(indi.key))
else assert(false,"Neither hisband nor wife")
end
else assert(false,"Neither FAMS nor FAMC") -- HIESA
end
end
--- gedcom:new_family(key)
-- Return the family with the given key, making a new one if necessary
GEDCOM.new_family = function(gedcom,key)
local fam = gedcom[key]
if not fam then
fam = FAM.new(key)
gedcom:append(fam)
end
return fam
end
--]]
|
local srep = string.rep
-- all of these functions return their result and a boolean
-- to notify the caller if the string was even changed
-- pad the left side
lpad =
function (s, l, c)
local res = srep(c or ' ', l - #s) .. s
return res, res ~= s
end
-- pad the right side
rpad =
function (s, l, c)
local res = s .. srep(c or ' ', l - #s)
return res, res ~= s
end
-- pad on both sides (centering with left justification)
pad =
function (s, l, c)
c = c or ' '
local res1, stat1 = rpad(s, (l / 2) + #s, c) -- pad to half-length + the length of s
local res2, stat2 = lpad(res1, l, c) -- right-pad our left-padded string to the full length
return res2, stat1 or stat2
end
return _M |
-----------------------------------
-- Area: Windurst Woods
-- NPC: Wani Casdohry
-----------------------------------
require("scripts/globals/quests")
-----------------------------------
function onTrade(player, npc, trade)
end
function onTrigger(player, npc)
local TwinstoneBonding = player:getQuestStatus(WINDURST, tpz.quest.id.windurst.TWINSTONE_BONDING)
if TwinstoneBonding == QUEST_COMPLETED then
player:startEvent(492, 0, 13360)
elseif TwinstoneBonding == QUEST_ACCEPTED then
player:startEvent(489, 0, 13360)
else
player:startEvent(425)
end
end
function onEventUpdate(player, csid, option)
end
function onEventFinish(player, csid, option)
end
|
local luaunit = require("luaunit")
require("switch_manual_enum_invalid")
TestSwitchManualEnumInvalid = {}
function TestSwitchManualEnumInvalid:test_switch_manual_enum_invalid()
local r = SwitchManualEnumInvalid:from_file("src/enum_negative.bin")
luaunit.assertEquals(#r.opcodes, 2)
luaunit.assertNil(r.opcodes[0 + 1].code)
luaunit.assertNil(r.opcodes[0 + 1].body)
luaunit.assertNil(r.opcodes[1 + 1].code)
luaunit.assertNil(r.opcodes[1 + 1].body)
end
|
local request = require("http.request")
local mt = {__call = function(_, room, user, token)
if not room then return nil, 'No room given' end
if not user then return nil, 'No user given' end
if not token then return nil, 'No token given' end
local room_id = room.id
local user_id = user[1].id
local uri = 'https://api.gitter.im/v1/rooms/' .. room_id ..'/users/' .. user_id
local req_body = '{}'
local req_timeout = 10
local req = request.new_from_uri(uri)
req.headers:upsert(':method', 'DELETE')
req.headers:upsert('content-type', 'application/json')
req.headers:upsert('accept', 'application/json')
req.headers:upsert('authorization', 'Bearer ' .. token, true)
req:set_body(req_body)
local headers, stream = req:go(req_timeout)
local body, err = stream:get_body_as_string()
if err then return nil, err end
if headers:get(':status') ~= '200' then return nil, body end
return body
end}
return setmetatable({}, mt)
|
-- Dependencies
local Assets = require("engine.Assets")
local State = require("engine.State")
local Table = require("engine.Table")
local ActionBar = require("game.editor.layers.ActionBar")
local Layer = require("game.editor.layers.Layer")
local ToolBar = require("game.editor.layers.ToolBar")
local Editor = require("game.states.Editor")
local Mapping = require("game.Mapping")
-- UI Layer class
local UILayer = Layer:derive("UILayer")
-- Variables
local sprites = Assets.sprites.editor
-- Constructor
function UILayer:UILayer(width, height)
self:Layer(width, height) -- Call superclass constructor
self.actionBar = ActionBar() -- Bar of action buttons
self.toolBar = ToolBar(height - 1) -- Bar of tool buttons
-- Initialize both bars
self:initActions()
self:initTools()
-- Listen for command stack changes
Editor.getCommandStack():addListener(function(commandStack)
self.actionBar:getButton("save").enabled = not commandStack:isMarkedAsSaved() or not Editor.isLevelOpened()
self.actionBar:getButton("rename").enabled = Editor.isLevelOpened()
self.actionBar:getButton("delete").enabled = Editor.isLevelOpened()
self.actionBar:getButton("undo").enabled = commandStack:canUndo()
self.actionBar:getButton("redo").enabled = commandStack:canRedo()
end)
end
-- Initializes actions
function UILayer:initActions()
local actionBar = self.actionBar
-- File operations
actionBar:addButton {
id = "new",
tooltip = "Create new level",
image = sprites[2],
redo = Editor.newLevel
}
actionBar:addButton {
id = "open",
tooltip = "Open level",
image = sprites[3],
redo = Editor.openLevel
}
actionBar:addButton {
id = "save",
tooltip = "Save level",
image = sprites[4],
redo = Editor.saveLevel
}
actionBar:addButton {
id = "save-as",
tooltip = "Save level as...",
image = sprites[5],
redo = Editor.saveLevelAs
}
actionBar:addButton {
id = "rename",
tooltip = "Rename level",
image = sprites[6],
redo = Editor.renameLevel
}
actionBar:addButton {
id = "delete",
tooltip = "Delete level",
image = sprites[7],
redo = Editor.deleteLevel
}
actionBar:addButton {
id = "quit",
tooltip = "Quit editor",
image = sprites[8],
redo = Editor.quitEditor
}
-- Movement
actionBar:addButton {
id = "left",
tooltip = "Move left",
image = sprites[17],
redo = function() Editor.moveGrid("left") end
}
actionBar:addButton {
id = "up",
tooltip = "Move up",
image = sprites[18],
redo = function() Editor.moveGrid("up") end
}
actionBar:addButton {
id = "center",
tooltip = "Center view",
image = sprites[23],
redo = Editor.centerGrid
}
actionBar:addButton {
id = "down",
tooltip = "Move down",
image = sprites[19],
redo = function() Editor.moveGrid("down") end
}
actionBar:addButton {
id = "right",
tooltip = "Move right",
image = sprites[20],
redo = function() Editor.moveGrid("right") end
}
-- Editing
actionBar:addButton {
id = "undo",
tooltip = "Undo last action",
image = sprites[9],
redo = function() Editor.getCommandStack():undo() end
}
actionBar:addButton {
id = "redo",
tooltip = "Redo undone action",
image = sprites[10],
redo = function() Editor.getCommandStack():redo() end
}
actionBar:addButton {
id = "play",
tooltip = "Play level",
image = sprites[15],
redo = Editor.playLevel
}
actionBar:addButton {
id = "metadata",
tooltip = "Edit level metadata",
image = sprites[14],
redo = Editor.editLevelMetadata
}
actionBar:addButton {
id = "grid",
tooltip = "Toggle grid visibility",
image = sprites[13],
redo = function()
local button = actionBar:getButton("grid")
button.checked = not button.checked
self.showGrid = not self.showGrid
end
}
actionBar:addButton {
id = "clear",
tooltip = "Clear level data",
image = sprites[12],
redo = function(self)
self.data = Table.copy(Editor.getLevel().data)
Editor.getLevel():clear()
end,
undo = function(self)
Editor.getLevel().data = self.data
end
}
-- Others
actionBar:addButton {
id = "fm",
tooltip = "Open levels directory in file manager",
image = sprites[11],
redo = Editor.openFileManager
}
actionBar:addButton {
id = "help",
tooltip = "Show help",
image = sprites[25],
redo = Editor.showHelp
}
end
-- Initializes tools
function UILayer:initTools()
local toolBar = self.toolBar
for item in Mapping.getIterator() do
toolBar:addButton {
character = item.character,
tooltip = item.description,
image = item.image
}
end
toolBar:updateScrollButtons()
end
-- Returns selected button
function UILayer:findButton(x, y)
if y == 1 then
return self.actionBar:getButton(x)
elseif x == self.width then
return self.toolBar:getButton(y - 1)
end
end
-- Draws UI layer
function UILayer:draw()
Layer.draw(self)
local width = 16 * self.width
local height = 16 * self.height
-- Draw grid
if self.showGrid then
love.graphics.setColor(255, 255, 255, 48)
for x = 0, width, 16 do
love.graphics.line(x, 0, x, height)
end
for y = 16, height, 16 do
love.graphics.line(0, y, width, y)
end
love.graphics.setColor(255, 255, 255)
end
-- Draw bars
self.actionBar:draw(0, 0)
self.toolBar:draw(width - 16, 16)
end
-- Processes cursor press event
function UILayer:cursorPressed(x, y)
local button = self:findButton(x, y)
if button then
self.pressedButton = button
button:press()
else
Layer.cursorPressed(self, x, y)
end
end
-- Processes cursor release event
function UILayer:cursorReleased(x, y)
local button = self.pressedButton
if button then
self.pressedButton = nil
button:release()
end
Layer.cursorReleased(self, x, y)
end
-- Process cursor move event
function UILayer:cursorMoved(oldX, oldY, newX, newY)
if self.selectedButton then
self.selectedButton.selected = false
end
self.selectedButton = self:findButton(newX, newY)
if self.selectedButton then
self.selectedButton.selected = true
end
Layer.cursorMoved(self, oldX, oldY, newX, newY)
end
return UILayer
|
local game = require 'game'
local Block = {}
Block.__index = Block
function Block.new(node, collider, ice)
local block = {}
setmetatable(block, Block)
block.bb = collider:addRectangle(node.x, node.y, node.width, node.height)
block.bb.node = block
block.node = node
collider:setPassive(block.bb)
block.isSolid = true
block.ice = (ice and true) or false
return block
end
function Block:collide( node, dt, mtv_x, mtv_y, bb)
bb = bb or node.bb
if not (node.floor_pushback or node.wall_pushback) then return end
node.bottom_bb = node.bottom_bb or node.bb
node.top_bb = node.top_bb or node.bb
if not node.top_bb or not node.bottom_bb then return end
local _, wy1, _, wy2 = self.bb:bbox()
local _, _, _, py2 = node.bottom_bb:bbox()
local _, py1, _, _ = node.top_bb:bbox()
if mtv_x ~= 0 and node.wall_pushback and node.position.y + node.height > wy1 + 2 then
-- horizontal block
node:wall_pushback(self, node.position.x+mtv_x)
end
if mtv_y > 0 and node.ceiling_pushback then
-- bouncing off bottom
node:ceiling_pushback(self, node.position.y + mtv_y)
end
if mtv_y < 0 and (not node.isPlayer or bb == node.bottom_bb) and node.velocity.y >= 0 then
-- standing on top
node:floor_pushback(self, self.node.y - node.height)
node.on_ice = self.ice
if self.ice and math.abs(node.velocity.x) < 500 then
if node.velocity.x < 0 then
node.velocity.x = math.min(node.velocity.x - game.friction * dt / 6, 0)
elseif node.velocity.x > 0 then
node.velocity.x = math.max(node.velocity.x + game.friction * dt / 6, 0)
end
end
end
end
function Block:collide_end( node ,dt )
end
return Block
|
AIGroup =
{
defendPressureThreshold = 0.75,
OnSaveAI = function(self, save)
save.deathContext = self.deathContext
end,
OnLoadAI = function(self, saved)
self.deathContext = saved.deathContext
end,
} |
--------------------------------------------------------------------------
-- Crytek Source File.
-- Copyright (C), Crytek Studios, 2001-2005.
--------------------------------------------------------------------------
-- $Id$
-- $DateTime$
-- Description: FlowGraph node which executes a script command
--
--------------------------------------------------------------------------
-- History:
-- - 11/10/2005 : Created by Sascha Gundlach
--
--------------------------------------------------------------------------
ScriptCommand = {
Category = "advanced",
Inputs = {{"t_Activate","bool"},{"Command","string"}},
Outputs = {{"Done","bool"}},
Implementation=function(bActivate,sCommand)
if(sCommand~="")then
local f=loadstring(sCommand);
if (f~=nil) then
f();
return 1;
else
return 0;
end;
else
return 0;
end;
end;
}
|
local poop_interval = 600
local poop_to_fertalize = 3
local function player_is_connected(player)
--
-- Check if player is connected
--
for _, connected in ipairs(minetest.get_connected_players()) do
if player:get_player_name() == connected:get_player_name() then
return true
end
end
return false
end
local function poop(player)
--
-- Drop poop
--
if player_is_connected(player) then
minetest.sound_play("luppoop_poop", {pos = player:get_pos()}, true)
minetest.item_drop(ItemStack("luppoop:poop"), nil, player:get_pos())
end
end
local function queue_poop(player)
--
-- Queue up random poop for player
--
minetest.after(math.random(poop_interval), poop, player)
end
local function queue_poops()
--
-- Queue up poops for all connected players
--
for _, player in ipairs(minetest.get_connected_players()) do
queue_poop(player)
end
minetest.after(poop_interval, queue_poops)
end
local function fertalize(itemstack, user, pointed_thing)
--
-- Use $poop_to_fertalize poop to fertalize something
--
-- TODO: support more node types
--
if not pointed_thing or itemstack:get_count() < poop_to_fertalize then
return
end
if pointed_thing.type == "node" then
local pos = pointed_thing.under
local node = minetest.get_node(pos)
local is_sapling = node and node.name:match("default:.*sapling")
if is_sapling and default.can_grow(pos) then
itemstack:take_item(poop_to_fertalize)
default.grow_sapling(pos)
end
end
return itemstack
end
minetest.register_craftitem("luppoop:poop", {
description = "Poop",
inventory_image = "luppoop_poop.png",
on_use = fertalize,
})
queue_poops()
|
oevitt_piboi = Creature:new {
objectName = "",
customName = "O'Evitt Piboi (en escapee)",
socialGroup = "warren_imperial_worker",
faction = "",
level = 12,
chanceHit = 0.29,
damageMin = 130,
damageMax = 140,
baseXp = 430,
baseHAM = 1200,
baseHAMmax = 1400,
armor = 0,
resists = {0,0,0,0,0,0,0,0,-1},
meatType = "",
meatAmount = 0,
hideType = "",
hideAmount = 0,
boneType = "",
boneAmount = 0,
milk = 0,
tamingChance = 0,
ferocity = 0,
pvpBitmask = NONE,
creatureBitmask = NONE,
optionsBitmask = AIENABLED + CONVERSABLE,
diet = HERBIVORE,
templates = {"object/mobile/warren_escapee.iff"},
lootGroups = {},
weapons = {},
conversationTemplate = "OevittPiboiConversationTemplate",
attacks = {
}
}
CreatureTemplates:addCreatureTemplate(oevitt_piboi, "oevitt_piboi")
|
Elona.Equipment = {
ArmorClass = {
Light = "(軽装備)",
Medium = "(中装備)",
Heavy = "(重装備)",
},
YouChangeYourEquipment = "装備を変更した。",
Layer = {
Window = {
Title = "装備品",
},
Topic = {
CategoryName = "部位/装備品名称",
Weight = "重さ",
},
Stats = {
EquipWeight = "装備重量",
HitBonus = "命中修正",
DamageBonus = "ダメージ修正",
},
MainHand = "利手",
},
}
|
modifier_boss_charger_pillar_debuff = class(ModifierBaseClass)
function modifier_boss_charger_pillar_debuff:OnCreated(keys)
if not IsServer() then
return
end
local ability = self:GetAbility()
end
function modifier_boss_charger_pillar_debuff:DeclareFunctions()
return {
MODIFIER_PROPERTY_PHYSICAL_ARMOR_BONUS,
MODIFIER_PROPERTY_MAGICAL_RESISTANCE_BONUS,
MODIFIER_PROPERTY_OVERRIDE_ANIMATION,
}
end
function modifier_boss_charger_pillar_debuff:GetModifierPhysicalArmorBonus()
return self:GetAbility():GetSpecialValueFor( "debuff_armor" )
end
function modifier_boss_charger_pillar_debuff:GetModifierMagicalResistanceBonus()
return self:GetAbility():GetSpecialValueFor( "debuff_magic_resist" )
end
function modifier_boss_charger_pillar_debuff:IsDebuff()
return true
end
function modifier_boss_charger_pillar_debuff:IsHidden()
return false
end
function modifier_boss_charger_pillar_debuff:IsPurgable()
return false
end
function modifier_boss_charger_pillar_debuff:IsStunDebuff()
return true
end
function modifier_boss_charger_pillar_debuff:GetEffectName()
return "particles/charger/charger_charge_debuff.vpcf"
end
function modifier_boss_charger_pillar_debuff:GetEffectAttachType()
return PATTACH_OVERHEAD_FOLLOW
end
function modifier_boss_charger_pillar_debuff:GetOverrideAnimation( params )
return ACT_DOTA_DISABLED
end
function modifier_boss_charger_pillar_debuff:CheckState()
local state = {
[MODIFIER_STATE_STUNNED] = true,
[MODIFIER_STATE_PASSIVES_DISABLED] = true,
[MODIFIER_STATE_BLOCK_DISABLED] = true,
[MODIFIER_STATE_EVADE_DISABLED] = true
}
return state
end
|
local Action = require(script.Parent.Parent.Action)
return Action("SetTabList", function(tabList, initIndex, isDeveloperView)
return {
tabList = tabList,
initIndex = initIndex,
isDeveloperView = isDeveloperView,
}
end) |
--// Package Metadata
return {
Name = "System.UI";
Version = 1.0;
Description = [[ Responsible for UI functionality. ]];
Author = "Sceleratis";
Package = script.Parent;
Dependencies = {
"System.Core",
"System.Utilities",
"System.Libraries"
};
Settings = {
["UI_ModuleGroup"] = {
DefaultValue = "Default",
Description = "Default UI module group",
Package = script.Parent,
ClientAllowed = true,
},
["UI_PrefabGroup"] = {
DefaultValue = "Default",
Description = "Default UI prefab group.",
Package = script.Parent,
ClientAllowed = true,
},
["UI_ThemeSettings"] = {
DefaultValue = {
PrimaryColor = Color3.fromRGB(0, 59, 255),
SecondaryColor = Color3.fromRGB(227, 73, 67),
TertiaryColor = Color3.fromRGB(255, 255, 255),
QuaternaryColor = Color3.fromRGB(56, 0, 79),
TextColor = Color3.fromRGB(255, 255, 255),
IconColor = Color3.fromRGB(255, 255, 255),
Font = "Gotham",
},
Description = "UI Colors. Must be supported by the currently selected prefab or module group.",
Package = script.Parent,
ClientAllowed = true,
}
};
}
|
local str = require 'lulz.str'
local fn = require 'lulz.functional'
local list = require 'lulz.collections.list'
local TestCase = require 'lulz.testcase'
local TestStrJoin = TestCase:inherit 'Str Join'
function TestStrJoin:test_empty_separator_join()
self:assert_equal(str.join('', {'a', 'b', 'c'}), 'abc')
end
function TestStrJoin:test_space_separator_join()
self:assert_equal(str.join(' ', {'a', 'b', 'c'}), 'a b c')
end
function TestStrJoin:test_numbers_join()
self:assert_equal(str.join(' ', {0, 1, 2}), '0 1 2')
end
function TestStrJoin:test_boolean_join()
self:assert_equal(str.join(' ', {false, true}), 'false true')
end
function TestStrJoin:test_iterator_join()
self:assert_equal(str.join(' ', fn.range(3)), '1 2 3')
end
local TestStrSplit = TestCase:inherit 'Str Split'
TestStrSplit.test_words = TestCase.args_test {
call = function(self, text, words)
self:assert_equal(list:new(str.words(text)), list(words))
end,
argsset = {
{ 'aa, bb,dd i', { 'aa,', 'bb,dd', 'i' } },
{
[[
aaa b c d
aaa bbbb
]],
{'aaa', 'b', 'c', 'd', 'aaa', 'bbbb'}
}
}
}
TestStrSplit.test_lines = TestCase.args_test {
call = function(self, text, lines)
self:assert_equal(list:new(str.lines(text)), list(lines))
end,
argsset = {
{ 'aa, bb,dd i', { 'aa, bb,dd i' } },
{
[[aaa b c d
aaa bbbb]],
{'aaa b c d', 'aaa bbbb' }
},
{
[[
aaa b c d
aaa bbbb
]],
{' aaa b c d', '', ' aaa bbbb', '' }
}
}
}
TestStrSplit.test_split = TestCase.args_test {
call = function(self, text, sep, parts)
self:assert_equal(list:new(str.split(text, sep)), list(parts))
end,
argsset = {
{ 'path.to.module', '.', { 'path', 'to', 'module' } }
}
}
|
-- Generated By protoc-gen-lua Do not Edit
local protobuf = require "protobuf"
module('BseGhostMoveStop_pb', package.seeall)
local BSEGHOSTMOVESTOP = protobuf.Descriptor();
local BSEGHOSTMOVESTOP_SESSIONID_FIELD = protobuf.FieldDescriptor();
local BSEGHOSTMOVESTOP_PASSFRAMES_FIELD = protobuf.FieldDescriptor();
local BSEGHOSTMOVESTOP_X_FIELD = protobuf.FieldDescriptor();
local BSEGHOSTMOVESTOP_Y_FIELD = protobuf.FieldDescriptor();
BSEGHOSTMOVESTOP_SESSIONID_FIELD.name = "sessionId"
BSEGHOSTMOVESTOP_SESSIONID_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseGhostMoveStop.sessionId"
BSEGHOSTMOVESTOP_SESSIONID_FIELD.number = 1
BSEGHOSTMOVESTOP_SESSIONID_FIELD.index = 0
BSEGHOSTMOVESTOP_SESSIONID_FIELD.label = 2
BSEGHOSTMOVESTOP_SESSIONID_FIELD.has_default_value = false
BSEGHOSTMOVESTOP_SESSIONID_FIELD.default_value = ""
BSEGHOSTMOVESTOP_SESSIONID_FIELD.type = 9
BSEGHOSTMOVESTOP_SESSIONID_FIELD.cpp_type = 9
BSEGHOSTMOVESTOP_PASSFRAMES_FIELD.name = "passFrames"
BSEGHOSTMOVESTOP_PASSFRAMES_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseGhostMoveStop.passFrames"
BSEGHOSTMOVESTOP_PASSFRAMES_FIELD.number = 2
BSEGHOSTMOVESTOP_PASSFRAMES_FIELD.index = 1
BSEGHOSTMOVESTOP_PASSFRAMES_FIELD.label = 2
BSEGHOSTMOVESTOP_PASSFRAMES_FIELD.has_default_value = false
BSEGHOSTMOVESTOP_PASSFRAMES_FIELD.default_value = 0
BSEGHOSTMOVESTOP_PASSFRAMES_FIELD.type = 13
BSEGHOSTMOVESTOP_PASSFRAMES_FIELD.cpp_type = 3
BSEGHOSTMOVESTOP_X_FIELD.name = "x"
BSEGHOSTMOVESTOP_X_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseGhostMoveStop.x"
BSEGHOSTMOVESTOP_X_FIELD.number = 3
BSEGHOSTMOVESTOP_X_FIELD.index = 2
BSEGHOSTMOVESTOP_X_FIELD.label = 2
BSEGHOSTMOVESTOP_X_FIELD.has_default_value = false
BSEGHOSTMOVESTOP_X_FIELD.default_value = 0
BSEGHOSTMOVESTOP_X_FIELD.type = 5
BSEGHOSTMOVESTOP_X_FIELD.cpp_type = 1
BSEGHOSTMOVESTOP_Y_FIELD.name = "y"
BSEGHOSTMOVESTOP_Y_FIELD.full_name = ".com.xinqihd.sns.gameserver.proto.BseGhostMoveStop.y"
BSEGHOSTMOVESTOP_Y_FIELD.number = 4
BSEGHOSTMOVESTOP_Y_FIELD.index = 3
BSEGHOSTMOVESTOP_Y_FIELD.label = 2
BSEGHOSTMOVESTOP_Y_FIELD.has_default_value = false
BSEGHOSTMOVESTOP_Y_FIELD.default_value = 0
BSEGHOSTMOVESTOP_Y_FIELD.type = 5
BSEGHOSTMOVESTOP_Y_FIELD.cpp_type = 1
BSEGHOSTMOVESTOP.name = "BseGhostMoveStop"
BSEGHOSTMOVESTOP.full_name = ".com.xinqihd.sns.gameserver.proto.BseGhostMoveStop"
BSEGHOSTMOVESTOP.nested_types = {}
BSEGHOSTMOVESTOP.enum_types = {}
BSEGHOSTMOVESTOP.fields = {BSEGHOSTMOVESTOP_SESSIONID_FIELD, BSEGHOSTMOVESTOP_PASSFRAMES_FIELD, BSEGHOSTMOVESTOP_X_FIELD, BSEGHOSTMOVESTOP_Y_FIELD}
BSEGHOSTMOVESTOP.is_extendable = false
BSEGHOSTMOVESTOP.extensions = {}
BseGhostMoveStop = protobuf.Message(BSEGHOSTMOVESTOP)
_G.BSEGHOSTMOVESTOP_PB_BSEGHOSTMOVESTOP = BSEGHOSTMOVESTOP
|
--------------------------------------------------------------------------------
-- 0330-tpretty.lua: tests for pretty-printer
-- This file is a part of lua-nucleo library
-- Copyright (c) lua-nucleo authors (see file `COPYRIGHT` for the license)
--------------------------------------------------------------------------------
local pairs = pairs
local make_suite = assert(loadfile('test/test-lib/init/strict.lua'))(...)
local ensure,
ensure_equals,
ensure_strequals,
ensure_tequals,
ensure_fails_with_substring
= import 'lua-nucleo/ensure.lua'
{
'ensure',
'ensure_equals',
'ensure_strequals',
'ensure_tequals',
'ensure_fails_with_substring'
}
local tpretty_ex,
tpretty,
tpretty_ordered,
tpretty_exports
= import 'lua-nucleo/tpretty.lua'
{
'tpretty_ex',
'tpretty',
'tpretty_ordered'
}
--------------------------------------------------------------------------------
local test = make_suite("tpretty", tpretty_exports)
--------------------------------------------------------------------------------
test:group "tpretty_ex"
--------------------------------------------------------------------------------
test "tpretty_ex-not-a-table" (function()
ensure_strequals(
"t is not a table",
tpretty_ex(pairs, 42),
'42'
)
end)
test "tpretty_ex-simple-table" (function()
ensure_strequals(
"t is a simple table",
tpretty_ex(pairs, {"DEPLOY_MACHINE"}),
'{ "DEPLOY_MACHINE" }'
)
end)
test "tpretty_ex-without-optional-params" (function()
local s1 = [[
{
result =
{
stats =
{
{
garden =
{
views_total = "INTEGER";
unique_visits_total = "INTEGER";
id = "GARDEN_ID";
views_yesterday = "INTEGER";
unique_visits_yesterday = "INTEGER";
};
};
};
};
events = { };
}]]
ensure_strequals(
[[default values for optional params is 80 and " "]],
tpretty_ex(pairs, ensure("parse", (loadstring("return " .. s1))())),
tpretty_ex(
pairs,
ensure("parse", loadstring("return " .. s1))(),
" ",
80
)
)
end)
-- Based on actual bug scenario
test "tpretty_ex-bug-concat-nil-minimal" (function()
local s1 = [[
{
stats = { };
}]]
local s2 = [[{ }]]
ensure_strequals(
"first result matches expected",
ensure(
"render first",
tpretty_ex(
pairs,
ensure("parse", loadstring("return " .. s1))(),
" ",
80
)
),
s1
)
-- [[
ensure_strequals(
"second result matches expected",
ensure(
"render second",
tpretty_ex(
pairs,
ensure("parse", loadstring("return " .. s2))(),
" ",
80
)
),
s2
)--]]
end)
-- Based on actual bug scenario
test "tpretty_ex-bug-concat-nil-full" (function()
local s1 = [[
{
result =
{
stats =
{
garden =
{
views_total = "INTEGER";
unique_visits_total = "INTEGER";
id = "GARDEN_ID";
views_yesterday = "INTEGER";
unique_visits_yesterday = "INTEGER";
};
};
};
events = { };
}]]
local s2 = [[
{
result =
{
money_real = "MONEY_REAL";
money_referral = "MONEY_REFERRAL";
money_game = "MONEY_GAME";
};
events = { };
}]]
ensure_strequals(
"first result matches expected",
ensure(
"render first",
tpretty_ex(
pairs,
ensure("parse", loadstring("return " .. s1))(),
" ",
80
)
),
s1
)
ensure_strequals(
"second result matches expected",
ensure(
"render second",
tpretty_ex(
pairs,
ensure("parse", loadstring("return " .. s2))(),
" ",
80
)
),
s2
)
end)
-- Test based on real bug scenario
-- #2304 and #2317
--
-- In case of failure. `this_field_was_empty' miss in output
test "tpretty_ex-fieldname-bug" (function ()
local cache_file_contents = [[
{
projects =
{
["lua-nucleo"] =
{
clusters =
{
["localhost-an"] =
{
machines =
{
localhost = { this_field_was_empty = true };
};
};
};
};
};
}]]
ensure_strequals(
"second result matches expected",
ensure(
"render second",
tpretty_ex(
pairs,
ensure("parse error", loadstring("return " .. cache_file_contents))(),
" ",
80
)
),
cache_file_contents
)
end)
--------------------------------------------------------------------------------
-- Test based on real bug scenario
-- #3067
--
-- Extra = is rendered as a table separator instead of ;
-- and after opening {.
test "tpretty_ex-wrong-table-list-separator-bug" (function ()
local data = [[
{
{
{
{ };
};
{
{ };
};
};
}]]
ensure_strequals(
"second result matches expected",
ensure(
"render second",
tpretty_ex(
pairs,
ensure("data string loads", loadstring("return " .. data))(),
" ",
80
)
),
data
)
end)
test "tpretty_ex-wrong-key-indent-bug" (function ()
local data = [[
{
{ };
foo =
{
{ };
};
}]]
ensure_strequals(
"second result matches expected",
ensure(
"render second",
tpretty_ex(
pairs,
ensure("data string loads", loadstring("return " .. data))(),
" ",
80
)
),
data
)
end)
--------------------------------------------------------------------------------
-- Test based on real bug scenario
-- #3836
test "tpretty_ex-serialize-inf-bug" (function ()
local table_with_inf = "{ 1/0, -1/0, 0/0 }"
ensure_strequals(
"second result matches expected",
ensure(
"render second",
tpretty_ex(
pairs,
ensure("parse error", loadstring("return " .. table_with_inf))(),
" ",
80
)
),
table_with_inf
)
end)
--------------------------------------------------------------------------------
test "tpretty_ex-custom-iterator" (function()
local t = { 1, 2, 3 }
local iterator_invocations_counter = 0
local custom_iterator = function(table)
local iterator_function = function(table, pos)
iterator_invocations_counter = iterator_invocations_counter + 1
pos = pos or 0
if pos < #table then
pos = pos + 1
return pos, table[pos]
end
end
return iterator_function, table, nil
end
tpretty_ex(custom_iterator, t)
ensure_equals(
"iterator invocations counter must match expected",
iterator_invocations_counter,
4
)
end)
--------------------------------------------------------------------------------
test:group "tpretty"
--------------------------------------------------------------------------------
test "tpretty-simple" (function()
local input = [[
{
1;
2;
3;
a =
{
b =
{
c = { };
};
};
}]]
ensure_strequals(
"result matches expected",
ensure(
"render is OK",
tpretty(ensure("parse error", loadstring("return " .. input))())
),
input
)
end)
--------------------------------------------------------------------------------
test:group "tpretty_ordered"
--------------------------------------------------------------------------------
test "tpretty-ordered" (function()
local input = [[
{
result =
{
stats2 =
{
a3333333333333 = "INTEGER";
a2222222222222 = "INTEGER";
a1111111111111 = "GARDEN_ID";
};
stats1 =
{
bbbbbbbbbbbbbb = "INTEGER";
cccccccccccccc = "INTEGER";
aaaaaaaaaaaaaa = "GARDEN_ID";
};
};
}]]
local expected = [[
{
result =
{
stats1 =
{
aaaaaaaaaaaaaa = "GARDEN_ID";
bbbbbbbbbbbbbb = "INTEGER";
cccccccccccccc = "INTEGER";
};
stats2 =
{
a1111111111111 = "GARDEN_ID";
a2222222222222 = "INTEGER";
a3333333333333 = "INTEGER";
};
};
}]]
ensure_strequals(
"first result matches expected",
ensure(
"render first",
tpretty_ordered(
ensure("parse", loadstring("return " .. input))(),
" ",
80
)
),
expected
)
end)
|
require('externals.luaSimpleTest.sources.luaSimpleTest')
require('01_GettingStarted.factorial')
require('03_Expressions.bool')
require('03_Expressions.solve_polynomial')
require('04_Statements.maze')
require('05_Functions.concat')
require('05_Functions.return')
local test = Test:new()
local block1 = test:blockNew()
block1:setDescription("Factorial tests")
block1:equal(fact(5), 120)
block1:equal(fact(0), 1)
block1:equal(fact(-1), nil)
block1:equal(fact(1.2), nil)
local block2 = test:blockNew()
block2:setDescription("Verifying if it is bool without using type")
block2:equal(verifyBool(true), true)
block2:equal(verifyBool(false), true)
block2:equal(verifyBool("true"), false)
block2:equal(verifyBool("false"), false)
block2:equal(verifyBool(nil), false)
block2:equal(verifyBool(0), false)
local block3 = test:blockNew()
block3:setDescription("Solving a polynomial")
block3:equal(solve_polynomial({2, 4, 8}, 10), 842)
block3:equal(solve_polynomial({5}, 10), 5)
local block4 = test:blockNew()
block4:setDescription("Moving in a maze game")
block4:equal(moveInMaze({1, 2}), true)
block4:equal(moveInMaze({2, 3, 4, 1, 1}), false)
local block5 = test:blockNew()
block5:setDescription("Concat strings")
block5:equal(concat("daniel","cabral"), "danielcabral")
block5:equal(concat("", "parte1", " parte2"), "parte1 parte2")
block5:equal(concat(nil), "")
local block6 = test:blockNew()
block6:setDescription("return but first")
local a1= return_but_first({1, 2, 3, 4, 5})
block6:equal(return_but_first(1, 2, 3, 4, 5), {2, 3, 4, 5})
block6:equal(return_but_first(1), {})
block6:equal(return_but_first(), {})
test:runTests()
|
local loadstring = loadstring
--Dx Functions
local dxDrawImage = dxDrawImageExt
local dxGetPixelsSize = dxGetPixelsSize
local dxGetPixelColor = dxGetPixelColor
local dxSetRenderTarget = dxSetRenderTarget
local dxGetTextWidth = dxGetTextWidth
--
local triggerEvent = triggerEvent
local createElement = createElement
local dgsSetType = dgsSetType
local dgsSetParent = dgsSetParent
local dgsSetData = dgsSetData
local assert = assert
local type = type
detectAreaBuiltIn = {}
function dgsCreateDetectArea(...)
local x,y,w,h,relative,parent
if select("#",...) == 1 and type(select(1,...)) == "table" then
local argTable = ...
x = argTable.x or argTable[1]
y = argTable.y or argTable[2]
w = argTable.width or argTable.w or argTable[3]
h = argTable.height or argTable.h or argTable[4]
relative = argTable.relative or argTable.rlt or argTable[5]
parent = argTable.parent or argTable.p or argTable[6]
else
x,y,w,h,relative,parent = ...
end
if not x then
local detectarea = createElement("dgs-dxdetectarea")
dgsSetType(detectarea,"dgs-dxdetectarea")
triggerEvent("onDgsCreate",detectarea,sourceResource)
dgsDetectAreaSetFunction(detectarea,detectAreaBuiltIn.default)
dgsSetData(detectarea,"debugTextureSize",{sW/2,sH/2})
dgsSetData(detectarea,"debugModeAlpha",128)
return detectarea
else
if not(type(x) == "number") then error(dgsGenAsrt(x,"dgsCreateDetectArea",1,"number")) end
if not(type(y) == "number") then error(dgsGenAsrt(y,"dgsCreateDetectArea",2,"number")) end
if not(type(w) == "number") then error(dgsGenAsrt(w,"dgsCreateDetectArea",3,"number")) end
if not(type(h) == "number") then error(dgsGenAsrt(h,"dgsCreateDetectArea",4,"number")) end
local detectarea = createElement("dgs-dxdetectarea")
dgsSetType(detectarea,"dgs-dxdetectarea")
dgsSetParent(detectarea,parent,true,true)
dgsSetData(detectarea,"debugMode",false)
dgsSetData(detectarea,"debugModeAlpha",128)
calculateGuiPositionSize(detectarea,x,y,relative or false,w,h,relative or false,true)
triggerEvent("onDgsCreate",detectarea,sourceResource)
dgsDetectAreaSetFunction(detectarea,detectAreaBuiltIn.default)
return detectarea
end
end
detectAreaPreDefine = [[
local args = {...}
local mxRlt,myRlt,mxAbs,myAbs = args[1],args[2],args[3],args[4]
]]
detectAreaBuiltIn.default = [[
return true
]]
detectAreaBuiltIn.circle = [[
return math.sqrt((mxRlt-0.5)^2+(myRlt-0.5)^2)<0.5
]]
function dgsDetectAreaDefaultFunction(mxRlt,myRlt,mxAbs,myAbs)
return true
end
function dgsDetectAreaSetFunction(detectarea,fncStr)
if dgsGetType(detectarea) ~= "dgs-dxdetectarea" then error(dgsGenAsrt(detectarea,"dgsDetectAreaSetFunction",1,"dgs-dxdetectarea")) end
if not (dgsIsType(fncStr,"string") or dgsIsType(fncStr,"texture") or dgsIsType(fncStr,"svg")) then error(dgsGenAsrt(fncStr,"dgsDetectAreaSetFunction",2,"string/texture")) end
if type(fncStr) == "string" then
fncStr = detectAreaBuiltIn[fncStr] or fncStr
local fnc,err = loadstring(detectAreaPreDefine..fncStr)
if not fnc then error(dgsGenAsrt(fnc,"dgsDetectAreaSetFunction",2,_,_,_,"Failed to load function:"..err)) end
dgsSetData(detectarea,"checkFunction",fnc)
dgsSetData(detectarea,"checkFunctionImage",nil)
else
local pixels = dxGetTexturePixels(fncStr)
dgsSetData(detectarea,"checkFunction",pixels)
dgsSetData(detectarea,"checkFunctionImage",fncStr)
end
dgsDetectAreaUpdateDebugView(detectarea)
return true
end
function dgsDetectAreaSetDebugModeEnabled(detectarea,state,alpha)
if dgsGetType(detectarea) ~= "dgs-dxdetectarea" then error(dgsGenAsrt(detectarea,"dgsDetectAreaSetDebugModeEnabled",1,"dgs-dxdetectarea")) end
dgsSetData(detectarea,"debugMode",state)
dgsSetData(detectarea,"debugModeAlpha",alpha or dgsElementData[detectarea].debugModeAlpha)
if state then
dgsDetectAreaUpdateDebugView(detectarea)
elseif isElement(dgsElementData[detectarea].debugTexture) then
destroyElement(dgsElementData[detectarea].debugTexture)
end
end
function dgsDetectAreaGetDebugModeEnabled(detectarea)
if dgsGetType(detectarea) ~= "dgs-dxdetectarea" then error(dgsGenAsrt(detectarea,"dgsDetectAreaGetDebugModeEnabled",1,"dgs-dxdetectarea")) end
return dgsElementData[detectarea].debugMode
end
function dgsDetectAreaUpdateDebugView(detectarea)
if not dgsElementData[detectarea].debugMode then return end
local checkFunction = dgsElementData[detectarea].checkFunction
local absSize = dgsElementData[detectarea].absSize or dgsElementData[detectarea].debugTextureSize
if isElement(dgsElementData[detectarea].debugTexture) then
local mX,mY = dxGetMaterialSize(dgsElementData[detectarea].debugTexture)
if mX ~= absSize[1] and mY ~= absSize[2] then
if isElement(dgsElementData[detectarea].debugTexture) then
destroyElement(dgsElementData[detectarea].debugTexture)
end
end
end
if not isElement(dgsElementData[detectarea].debugTexture) then
local texture = dxCreateEmptyTexture(absSize[1],absSize[2])
dgsSetData(detectarea,"debugTexture",texture)
end
if type(checkFunction) == "function" then
local pixels = dxGetTexturePixels(dgsElementData[detectarea].debugTexture)
for i=0,absSize[1]-1 do
for j=0,absSize[2]-1 do
local color = checkFunction((i+1)/absSize[1],(j+1)/absSize[2]) and {255,255,255,255} or {0,0,0,0}
dxSetPixelColor(pixels,i,j,color[1],color[2],color[3],color[4])
end
end
dxSetTexturePixels(dgsElementData[detectarea].debugTexture,pixels)
else
dxSetTexturePixels(dgsElementData[detectarea].debugTexture,checkFunction)
end
return true
end
function dgsDetectAreaAttachToElement(da,ele)
local fnc = function(source,mx,my,x,y,w,h)
if mx >= x and mx <= x+w and my >= y and my <= y+h then
return source
end
end
dgsSetData(ele,"dgsCollider",fnc)
end
----------------------------------------------------------------
--------------------------Renderer------------------------------
----------------------------------------------------------------
dgsRenderer["dgs-dxdetectarea"] = function(source,x,y,w,h,mx,my,cx,cy,enabledInherited,enabledSelf,eleData,parentAlpha,isPostGUI,rndtgt)
local color = 0xFFFFFFFF
if enabledInherited[1] and mx then
local checkPixel = eleData.checkFunction
if checkPixel then
local _mx,_my = (mx-x)/w,(my-y)/h
if _mx > 0 and _my > 0 and _mx <= 1 and _my <= 1 then
if type(checkPixel) == "function" then
local checkFnc = eleData.checkFunction
if checkFnc((mx-x)/w,(my-y)/h,mx,my) then
MouseData.hit = source
color = 0xFFFF0000
end
else
local px,py = dxGetPixelsSize(checkPixel)
local pixX,pixY = _mx*px,_my*py
local r,g,b = dxGetPixelColor(checkPixel,pixX-1,pixY-1)
if r then
local gray = (r+g+b)/3
if gray >= 128 then
MouseData.hit = source
color = 0xFFFF0000
end
end
end
end
end
end
local debugTexture = eleData.debugTexture
if eleData.debugMode and isElement(debugTexture) then
dxDrawImage(x,y,w,h,debugTexture,0,0,0,color,isPostGUI,rndtgt)
end
return rndtgt,false,mx,my,0,0
end |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.